@pyric/cli 0.1.0-alpha.30.2 → 0.1.0-alpha.31

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 (1327) hide show
  1. package/dist/assurance/.generated/conformance-verdicts.d.ts +107 -40
  2. package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
  3. package/dist/assurance/.generated/conformance-verdicts.js +107 -40
  4. package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
  5. package/dist/assurance/capabilities.d.ts.map +1 -1
  6. package/dist/assurance/capabilities.js +12 -14
  7. package/dist/assurance/capabilities.js.map +1 -1
  8. package/dist/bounded-request.d.ts +27 -5
  9. package/dist/bounded-request.d.ts.map +1 -1
  10. package/dist/bounded-request.js +48 -4
  11. package/dist/bounded-request.js.map +1 -1
  12. package/dist/bridge/client/bridge-url.d.ts +5 -1
  13. package/dist/bridge/client/bridge-url.d.ts.map +1 -1
  14. package/dist/bridge/client/bridge-url.js +5 -1
  15. package/dist/bridge/client/bridge-url.js.map +1 -1
  16. package/dist/bridge/client/bridge.d.ts +9 -3
  17. package/dist/bridge/client/bridge.d.ts.map +1 -1
  18. package/dist/bridge/client/bridge.js +17 -3
  19. package/dist/bridge/client/bridge.js.map +1 -1
  20. package/dist/bridge/frame-output.d.ts.map +1 -1
  21. package/dist/bridge/frame-output.js +46 -0
  22. package/dist/bridge/frame-output.js.map +1 -1
  23. package/dist/bridge/protocol.d.ts +10 -0
  24. package/dist/bridge/protocol.d.ts.map +1 -1
  25. package/dist/bridge/protocol.js +10 -0
  26. package/dist/bridge/protocol.js.map +1 -1
  27. package/dist/bridge/server/in-process.d.ts +16 -7
  28. package/dist/bridge/server/in-process.d.ts.map +1 -1
  29. package/dist/bridge/server/in-process.js +51 -17
  30. package/dist/bridge/server/in-process.js.map +1 -1
  31. package/dist/bridge/server/peer.d.ts +8 -0
  32. package/dist/bridge/server/peer.d.ts.map +1 -1
  33. package/dist/bridge/server/peer.js +10 -0
  34. package/dist/bridge/server/peer.js.map +1 -1
  35. package/dist/bridge/server/standalone.d.ts +7 -2
  36. package/dist/bridge/server/standalone.d.ts.map +1 -1
  37. package/dist/bridge/server/standalone.js +27 -99
  38. package/dist/bridge/server/standalone.js.map +1 -1
  39. package/dist/bridge/surface/arguments/firestore.d.ts +6 -6
  40. package/dist/bridge/surface/arguments/sandbox.d.ts +0 -47
  41. package/dist/bridge/surface/arguments/sandbox.d.ts.map +1 -1
  42. package/dist/bridge/surface/arguments/sandbox.js +2 -59
  43. package/dist/bridge/surface/arguments/sandbox.js.map +1 -1
  44. package/dist/bridge/surface/arguments/seed.d.ts +61 -0
  45. package/dist/bridge/surface/arguments/seed.d.ts.map +1 -0
  46. package/dist/bridge/surface/arguments/seed.js +67 -0
  47. package/dist/bridge/surface/arguments/seed.js.map +1 -0
  48. package/dist/bridge/surface/arguments/storage.d.ts +2 -2
  49. package/dist/bridge/surface/context.d.ts +5 -10
  50. package/dist/bridge/surface/context.d.ts.map +1 -1
  51. package/dist/bridge/surface/context.js +11 -23
  52. package/dist/bridge/surface/context.js.map +1 -1
  53. package/dist/bridge/surface/database-instance-catalog.d.ts +0 -3
  54. package/dist/bridge/surface/database-instance-catalog.d.ts.map +1 -1
  55. package/dist/bridge/surface/database-instance-catalog.js +4 -27
  56. package/dist/bridge/surface/database-instance-catalog.js.map +1 -1
  57. package/dist/bridge/surface/database-instance-project.d.ts +5 -0
  58. package/dist/bridge/surface/database-instance-project.d.ts.map +1 -0
  59. package/dist/bridge/surface/database-instance-project.js +32 -0
  60. package/dist/bridge/surface/database-instance-project.js.map +1 -0
  61. package/dist/bridge/surface/database-instance.d.ts +3 -3
  62. package/dist/bridge/surface/database-instance.d.ts.map +1 -1
  63. package/dist/bridge/surface/database-instance.js +1 -2
  64. package/dist/bridge/surface/database-instance.js.map +1 -1
  65. package/dist/bridge/surface/functions-runtime.d.ts +2 -2
  66. package/dist/bridge/surface/functions-runtime.js +5 -5
  67. package/dist/bridge/surface/functions-runtime.js.map +1 -1
  68. package/dist/bridge/surface/held-identity.d.ts +4 -4
  69. package/dist/bridge/surface/held-identity.d.ts.map +1 -1
  70. package/dist/bridge/surface/held-identity.js.map +1 -1
  71. package/dist/bridge/surface/manifest.sandbox.generated.d.ts +3 -0
  72. package/dist/bridge/surface/manifest.sandbox.generated.d.ts.map +1 -0
  73. package/dist/bridge/surface/manifest.sandbox.generated.js +135 -0
  74. package/dist/bridge/surface/manifest.sandbox.generated.js.map +1 -0
  75. package/dist/bridge/surface/method-types.d.ts +48 -7
  76. package/dist/bridge/surface/method-types.d.ts.map +1 -1
  77. package/dist/bridge/surface/method-types.js +15 -0
  78. package/dist/bridge/surface/method-types.js.map +1 -1
  79. package/dist/bridge/surface/methods/ai_logic/clearScripts.d.ts +2 -1
  80. package/dist/bridge/surface/methods/ai_logic/clearScripts.d.ts.map +1 -1
  81. package/dist/bridge/surface/methods/ai_logic/clearScripts.js +2 -1
  82. package/dist/bridge/surface/methods/ai_logic/clearScripts.js.map +1 -1
  83. package/dist/bridge/surface/methods/ai_logic/script.d.ts +2 -1
  84. package/dist/bridge/surface/methods/ai_logic/script.d.ts.map +1 -1
  85. package/dist/bridge/surface/methods/ai_logic/script.js +2 -1
  86. package/dist/bridge/surface/methods/ai_logic/script.js.map +1 -1
  87. package/dist/bridge/surface/methods/ai_logic/scripts.d.ts +2 -1
  88. package/dist/bridge/surface/methods/ai_logic/scripts.d.ts.map +1 -1
  89. package/dist/bridge/surface/methods/ai_logic/scripts.js +2 -1
  90. package/dist/bridge/surface/methods/ai_logic/scripts.js.map +1 -1
  91. package/dist/bridge/surface/methods/ai_logic/status.d.ts +2 -1
  92. package/dist/bridge/surface/methods/ai_logic/status.d.ts.map +1 -1
  93. package/dist/bridge/surface/methods/ai_logic/status.js +1 -0
  94. package/dist/bridge/surface/methods/ai_logic/status.js.map +1 -1
  95. package/dist/bridge/surface/methods/assurance/attach.d.ts +1 -0
  96. package/dist/bridge/surface/methods/assurance/attach.d.ts.map +1 -1
  97. package/dist/bridge/surface/methods/assurance/attach.js +1 -0
  98. package/dist/bridge/surface/methods/assurance/attach.js.map +1 -1
  99. package/dist/bridge/surface/methods/assurance/canIUse.d.ts +1 -0
  100. package/dist/bridge/surface/methods/assurance/canIUse.d.ts.map +1 -1
  101. package/dist/bridge/surface/methods/assurance/canIUse.js +1 -0
  102. package/dist/bridge/surface/methods/assurance/canIUse.js.map +1 -1
  103. package/dist/bridge/surface/methods/assurance/define.d.ts +1 -0
  104. package/dist/bridge/surface/methods/assurance/define.d.ts.map +1 -1
  105. package/dist/bridge/surface/methods/assurance/define.js +1 -0
  106. package/dist/bridge/surface/methods/assurance/define.js.map +1 -1
  107. package/dist/bridge/surface/methods/assurance/export.d.ts +1 -0
  108. package/dist/bridge/surface/methods/assurance/export.d.ts.map +1 -1
  109. package/dist/bridge/surface/methods/assurance/export.js +1 -0
  110. package/dist/bridge/surface/methods/assurance/export.js.map +1 -1
  111. package/dist/bridge/surface/methods/assurance/inspect.d.ts +1 -0
  112. package/dist/bridge/surface/methods/assurance/inspect.d.ts.map +1 -1
  113. package/dist/bridge/surface/methods/assurance/inspect.js +1 -0
  114. package/dist/bridge/surface/methods/assurance/inspect.js.map +1 -1
  115. package/dist/bridge/surface/methods/assurance/map.d.ts +1 -0
  116. package/dist/bridge/surface/methods/assurance/map.d.ts.map +1 -1
  117. package/dist/bridge/surface/methods/assurance/map.js +1 -0
  118. package/dist/bridge/surface/methods/assurance/map.js.map +1 -1
  119. package/dist/bridge/surface/methods/assurance/minimize.d.ts +1 -0
  120. package/dist/bridge/surface/methods/assurance/minimize.d.ts.map +1 -1
  121. package/dist/bridge/surface/methods/assurance/minimize.js +1 -0
  122. package/dist/bridge/surface/methods/assurance/minimize.js.map +1 -1
  123. package/dist/bridge/surface/methods/assurance/propose.d.ts +1 -0
  124. package/dist/bridge/surface/methods/assurance/propose.d.ts.map +1 -1
  125. package/dist/bridge/surface/methods/assurance/propose.js +1 -0
  126. package/dist/bridge/surface/methods/assurance/propose.js.map +1 -1
  127. package/dist/bridge/surface/methods/assurance/replaySession.d.ts +1 -0
  128. package/dist/bridge/surface/methods/assurance/replaySession.d.ts.map +1 -1
  129. package/dist/bridge/surface/methods/assurance/replaySession.js +1 -0
  130. package/dist/bridge/surface/methods/assurance/replaySession.js.map +1 -1
  131. package/dist/bridge/surface/methods/assurance/run.d.ts +1 -0
  132. package/dist/bridge/surface/methods/assurance/run.d.ts.map +1 -1
  133. package/dist/bridge/surface/methods/assurance/run.js +1 -0
  134. package/dist/bridge/surface/methods/assurance/run.js.map +1 -1
  135. package/dist/bridge/surface/methods/assurance/start.d.ts +1 -0
  136. package/dist/bridge/surface/methods/assurance/start.d.ts.map +1 -1
  137. package/dist/bridge/surface/methods/assurance/start.js +1 -0
  138. package/dist/bridge/surface/methods/assurance/start.js.map +1 -1
  139. package/dist/bridge/surface/methods/assurance/testRulesHosted.d.ts +1 -0
  140. package/dist/bridge/surface/methods/assurance/testRulesHosted.d.ts.map +1 -1
  141. package/dist/bridge/surface/methods/assurance/testRulesHosted.js +1 -0
  142. package/dist/bridge/surface/methods/assurance/testRulesHosted.js.map +1 -1
  143. package/dist/bridge/surface/methods/assurance/verify.d.ts +1 -0
  144. package/dist/bridge/surface/methods/assurance/verify.d.ts.map +1 -1
  145. package/dist/bridge/surface/methods/assurance/verify.js +1 -0
  146. package/dist/bridge/surface/methods/assurance/verify.js.map +1 -1
  147. package/dist/bridge/surface/methods/assurance/verifyCases.d.ts +1 -0
  148. package/dist/bridge/surface/methods/assurance/verifyCases.d.ts.map +1 -1
  149. package/dist/bridge/surface/methods/assurance/verifyCases.js +1 -0
  150. package/dist/bridge/surface/methods/assurance/verifyCases.js.map +1 -1
  151. package/dist/bridge/surface/methods/auth/actAsAdmin.d.ts +2 -1
  152. package/dist/bridge/surface/methods/auth/actAsAdmin.d.ts.map +1 -1
  153. package/dist/bridge/surface/methods/auth/actAsAdmin.js +1 -0
  154. package/dist/bridge/surface/methods/auth/actAsAdmin.js.map +1 -1
  155. package/dist/bridge/surface/methods/auth/actAsAnonymous.d.ts +2 -1
  156. package/dist/bridge/surface/methods/auth/actAsAnonymous.d.ts.map +1 -1
  157. package/dist/bridge/surface/methods/auth/actAsAnonymous.js +1 -0
  158. package/dist/bridge/surface/methods/auth/actAsAnonymous.js.map +1 -1
  159. package/dist/bridge/surface/methods/auth/createCustomToken.d.ts +1 -0
  160. package/dist/bridge/surface/methods/auth/createCustomToken.d.ts.map +1 -1
  161. package/dist/bridge/surface/methods/auth/createCustomToken.js +1 -0
  162. package/dist/bridge/surface/methods/auth/createCustomToken.js.map +1 -1
  163. package/dist/bridge/surface/methods/auth/createUser.d.ts +2 -1
  164. package/dist/bridge/surface/methods/auth/createUser.d.ts.map +1 -1
  165. package/dist/bridge/surface/methods/auth/createUser.js +2 -1
  166. package/dist/bridge/surface/methods/auth/createUser.js.map +1 -1
  167. package/dist/bridge/surface/methods/auth/deleteUser.d.ts +2 -1
  168. package/dist/bridge/surface/methods/auth/deleteUser.d.ts.map +1 -1
  169. package/dist/bridge/surface/methods/auth/deleteUser.js +2 -1
  170. package/dist/bridge/surface/methods/auth/deleteUser.js.map +1 -1
  171. package/dist/bridge/surface/methods/auth/getUser.d.ts +2 -1
  172. package/dist/bridge/surface/methods/auth/getUser.d.ts.map +1 -1
  173. package/dist/bridge/surface/methods/auth/getUser.js +2 -1
  174. package/dist/bridge/surface/methods/auth/getUser.js.map +1 -1
  175. package/dist/bridge/surface/methods/auth/getUserByEmail.d.ts +2 -1
  176. package/dist/bridge/surface/methods/auth/getUserByEmail.d.ts.map +1 -1
  177. package/dist/bridge/surface/methods/auth/getUserByEmail.js +2 -1
  178. package/dist/bridge/surface/methods/auth/getUserByEmail.js.map +1 -1
  179. package/dist/bridge/surface/methods/auth/impersonate.d.ts +2 -1
  180. package/dist/bridge/surface/methods/auth/impersonate.d.ts.map +1 -1
  181. package/dist/bridge/surface/methods/auth/impersonate.js +1 -0
  182. package/dist/bridge/surface/methods/auth/impersonate.js.map +1 -1
  183. package/dist/bridge/surface/methods/auth/importUsers.d.ts +2 -1
  184. package/dist/bridge/surface/methods/auth/importUsers.d.ts.map +1 -1
  185. package/dist/bridge/surface/methods/auth/importUsers.js +3 -2
  186. package/dist/bridge/surface/methods/auth/importUsers.js.map +1 -1
  187. package/dist/bridge/surface/methods/auth/listUsers.d.ts +2 -1
  188. package/dist/bridge/surface/methods/auth/listUsers.d.ts.map +1 -1
  189. package/dist/bridge/surface/methods/auth/listUsers.js +2 -1
  190. package/dist/bridge/surface/methods/auth/listUsers.js.map +1 -1
  191. package/dist/bridge/surface/methods/auth/sessions.d.ts +2 -1
  192. package/dist/bridge/surface/methods/auth/sessions.d.ts.map +1 -1
  193. package/dist/bridge/surface/methods/auth/sessions.js +1 -0
  194. package/dist/bridge/surface/methods/auth/sessions.js.map +1 -1
  195. package/dist/bridge/surface/methods/auth/setCustomUserClaims.d.ts +2 -1
  196. package/dist/bridge/surface/methods/auth/setCustomUserClaims.d.ts.map +1 -1
  197. package/dist/bridge/surface/methods/auth/setCustomUserClaims.js +2 -1
  198. package/dist/bridge/surface/methods/auth/setCustomUserClaims.js.map +1 -1
  199. package/dist/bridge/surface/methods/auth/signInAnonymously.d.ts +2 -1
  200. package/dist/bridge/surface/methods/auth/signInAnonymously.d.ts.map +1 -1
  201. package/dist/bridge/surface/methods/auth/signInAnonymously.js +1 -0
  202. package/dist/bridge/surface/methods/auth/signInAnonymously.js.map +1 -1
  203. package/dist/bridge/surface/methods/auth/signInWithCredential.d.ts +2 -1
  204. package/dist/bridge/surface/methods/auth/signInWithCredential.d.ts.map +1 -1
  205. package/dist/bridge/surface/methods/auth/signInWithCredential.js +1 -0
  206. package/dist/bridge/surface/methods/auth/signInWithCredential.js.map +1 -1
  207. package/dist/bridge/surface/methods/auth/signInWithCustomToken.d.ts +2 -1
  208. package/dist/bridge/surface/methods/auth/signInWithCustomToken.d.ts.map +1 -1
  209. package/dist/bridge/surface/methods/auth/signInWithCustomToken.js +1 -0
  210. package/dist/bridge/surface/methods/auth/signInWithCustomToken.js.map +1 -1
  211. package/dist/bridge/surface/methods/auth/signInWithEmailAndPassword.d.ts +2 -1
  212. package/dist/bridge/surface/methods/auth/signInWithEmailAndPassword.d.ts.map +1 -1
  213. package/dist/bridge/surface/methods/auth/signInWithEmailAndPassword.js +1 -0
  214. package/dist/bridge/surface/methods/auth/signInWithEmailAndPassword.js.map +1 -1
  215. package/dist/bridge/surface/methods/auth/signOut.d.ts +2 -1
  216. package/dist/bridge/surface/methods/auth/signOut.d.ts.map +1 -1
  217. package/dist/bridge/surface/methods/auth/signOut.js +1 -0
  218. package/dist/bridge/surface/methods/auth/signOut.js.map +1 -1
  219. package/dist/bridge/surface/methods/auth/takeAuthMail.d.ts +2 -1
  220. package/dist/bridge/surface/methods/auth/takeAuthMail.d.ts.map +1 -1
  221. package/dist/bridge/surface/methods/auth/takeAuthMail.js +1 -0
  222. package/dist/bridge/surface/methods/auth/takeAuthMail.js.map +1 -1
  223. package/dist/bridge/surface/methods/auth/updateUser.d.ts +2 -1
  224. package/dist/bridge/surface/methods/auth/updateUser.d.ts.map +1 -1
  225. package/dist/bridge/surface/methods/auth/updateUser.js +2 -1
  226. package/dist/bridge/surface/methods/auth/updateUser.js.map +1 -1
  227. package/dist/bridge/surface/methods/auth/useAppSession.d.ts +2 -1
  228. package/dist/bridge/surface/methods/auth/useAppSession.d.ts.map +1 -1
  229. package/dist/bridge/surface/methods/auth/useAppSession.js +1 -0
  230. package/dist/bridge/surface/methods/auth/useAppSession.js.map +1 -1
  231. package/dist/bridge/surface/methods/auth/whoami.d.ts +2 -1
  232. package/dist/bridge/surface/methods/auth/whoami.d.ts.map +1 -1
  233. package/dist/bridge/surface/methods/auth/whoami.js +1 -0
  234. package/dist/bridge/surface/methods/auth/whoami.js.map +1 -1
  235. package/dist/bridge/surface/methods/database/crawl.d.ts +2 -1
  236. package/dist/bridge/surface/methods/database/crawl.d.ts.map +1 -1
  237. package/dist/bridge/surface/methods/database/crawl.js +1 -0
  238. package/dist/bridge/surface/methods/database/crawl.js.map +1 -1
  239. package/dist/bridge/surface/methods/database/get.d.ts +2 -1
  240. package/dist/bridge/surface/methods/database/get.d.ts.map +1 -1
  241. package/dist/bridge/surface/methods/database/get.js +1 -0
  242. package/dist/bridge/surface/methods/database/get.js.map +1 -1
  243. package/dist/bridge/surface/methods/database/push.d.ts +2 -1
  244. package/dist/bridge/surface/methods/database/push.d.ts.map +1 -1
  245. package/dist/bridge/surface/methods/database/push.js +1 -0
  246. package/dist/bridge/surface/methods/database/push.js.map +1 -1
  247. package/dist/bridge/surface/methods/database/query.d.ts +2 -1
  248. package/dist/bridge/surface/methods/database/query.d.ts.map +1 -1
  249. package/dist/bridge/surface/methods/database/query.js +1 -0
  250. package/dist/bridge/surface/methods/database/query.js.map +1 -1
  251. package/dist/bridge/surface/methods/database/remove.d.ts +2 -1
  252. package/dist/bridge/surface/methods/database/remove.d.ts.map +1 -1
  253. package/dist/bridge/surface/methods/database/remove.js +1 -0
  254. package/dist/bridge/surface/methods/database/remove.js.map +1 -1
  255. package/dist/bridge/surface/methods/database/set.d.ts +2 -1
  256. package/dist/bridge/surface/methods/database/set.d.ts.map +1 -1
  257. package/dist/bridge/surface/methods/database/set.js +1 -0
  258. package/dist/bridge/surface/methods/database/set.js.map +1 -1
  259. package/dist/bridge/surface/methods/database/update.d.ts +2 -1
  260. package/dist/bridge/surface/methods/database/update.d.ts.map +1 -1
  261. package/dist/bridge/surface/methods/database/update.js +1 -0
  262. package/dist/bridge/surface/methods/database/update.js.map +1 -1
  263. package/dist/bridge/surface/methods/firestore/addDoc.d.ts +2 -1
  264. package/dist/bridge/surface/methods/firestore/addDoc.d.ts.map +1 -1
  265. package/dist/bridge/surface/methods/firestore/addDoc.js +2 -1
  266. package/dist/bridge/surface/methods/firestore/addDoc.js.map +1 -1
  267. package/dist/bridge/surface/methods/firestore/deleteDoc.d.ts +2 -1
  268. package/dist/bridge/surface/methods/firestore/deleteDoc.d.ts.map +1 -1
  269. package/dist/bridge/surface/methods/firestore/deleteDoc.js +2 -1
  270. package/dist/bridge/surface/methods/firestore/deleteDoc.js.map +1 -1
  271. package/dist/bridge/surface/methods/firestore/discoverPaths.d.ts +2 -1
  272. package/dist/bridge/surface/methods/firestore/discoverPaths.d.ts.map +1 -1
  273. package/dist/bridge/surface/methods/firestore/discoverPaths.js +1 -0
  274. package/dist/bridge/surface/methods/firestore/discoverPaths.js.map +1 -1
  275. package/dist/bridge/surface/methods/firestore/extractIndexes.d.ts +7 -6
  276. package/dist/bridge/surface/methods/firestore/extractIndexes.d.ts.map +1 -1
  277. package/dist/bridge/surface/methods/firestore/extractIndexes.js +1 -0
  278. package/dist/bridge/surface/methods/firestore/extractIndexes.js.map +1 -1
  279. package/dist/bridge/surface/methods/firestore/findCollectionGroup.d.ts +2 -1
  280. package/dist/bridge/surface/methods/firestore/findCollectionGroup.d.ts.map +1 -1
  281. package/dist/bridge/surface/methods/firestore/findCollectionGroup.js +1 -0
  282. package/dist/bridge/surface/methods/firestore/findCollectionGroup.js.map +1 -1
  283. package/dist/bridge/surface/methods/firestore/getAggregateFromServer.d.ts +6 -5
  284. package/dist/bridge/surface/methods/firestore/getAggregateFromServer.d.ts.map +1 -1
  285. package/dist/bridge/surface/methods/firestore/getAggregateFromServer.js +1 -0
  286. package/dist/bridge/surface/methods/firestore/getAggregateFromServer.js.map +1 -1
  287. package/dist/bridge/surface/methods/firestore/getCountFromServer.d.ts +6 -5
  288. package/dist/bridge/surface/methods/firestore/getCountFromServer.d.ts.map +1 -1
  289. package/dist/bridge/surface/methods/firestore/getCountFromServer.js +1 -0
  290. package/dist/bridge/surface/methods/firestore/getCountFromServer.js.map +1 -1
  291. package/dist/bridge/surface/methods/firestore/getDoc.d.ts +2 -1
  292. package/dist/bridge/surface/methods/firestore/getDoc.d.ts.map +1 -1
  293. package/dist/bridge/surface/methods/firestore/getDoc.js +2 -1
  294. package/dist/bridge/surface/methods/firestore/getDoc.js.map +1 -1
  295. package/dist/bridge/surface/methods/firestore/getDocs.d.ts +6 -5
  296. package/dist/bridge/surface/methods/firestore/getDocs.d.ts.map +1 -1
  297. package/dist/bridge/surface/methods/firestore/getDocs.js +2 -1
  298. package/dist/bridge/surface/methods/firestore/getDocs.js.map +1 -1
  299. package/dist/bridge/surface/methods/firestore/setDoc.d.ts +2 -1
  300. package/dist/bridge/surface/methods/firestore/setDoc.d.ts.map +1 -1
  301. package/dist/bridge/surface/methods/firestore/setDoc.js +2 -1
  302. package/dist/bridge/surface/methods/firestore/setDoc.js.map +1 -1
  303. package/dist/bridge/surface/methods/firestore/updateDoc.d.ts +2 -1
  304. package/dist/bridge/surface/methods/firestore/updateDoc.d.ts.map +1 -1
  305. package/dist/bridge/surface/methods/firestore/updateDoc.js +2 -1
  306. package/dist/bridge/surface/methods/firestore/updateDoc.js.map +1 -1
  307. package/dist/bridge/surface/methods/firestore/writeBatch.d.ts +2 -1
  308. package/dist/bridge/surface/methods/firestore/writeBatch.d.ts.map +1 -1
  309. package/dist/bridge/surface/methods/firestore/writeBatch.js +2 -1
  310. package/dist/bridge/surface/methods/firestore/writeBatch.js.map +1 -1
  311. package/dist/bridge/surface/methods/firestore/writeIndexes.d.ts +1 -0
  312. package/dist/bridge/surface/methods/firestore/writeIndexes.d.ts.map +1 -1
  313. package/dist/bridge/surface/methods/firestore/writeIndexes.js +1 -0
  314. package/dist/bridge/surface/methods/firestore/writeIndexes.js.map +1 -1
  315. package/dist/bridge/surface/methods/functions/executions.d.ts +3 -2
  316. package/dist/bridge/surface/methods/functions/executions.d.ts.map +1 -1
  317. package/dist/bridge/surface/methods/functions/executions.js +2 -1
  318. package/dist/bridge/surface/methods/functions/executions.js.map +1 -1
  319. package/dist/bridge/surface/methods/functions/fire.d.ts +1 -0
  320. package/dist/bridge/surface/methods/functions/fire.d.ts.map +1 -1
  321. package/dist/bridge/surface/methods/functions/fire.js +6 -5
  322. package/dist/bridge/surface/methods/functions/fire.js.map +1 -1
  323. package/dist/bridge/surface/methods/functions/listTriggers.d.ts +2 -1
  324. package/dist/bridge/surface/methods/functions/listTriggers.d.ts.map +1 -1
  325. package/dist/bridge/surface/methods/functions/listTriggers.js +1 -0
  326. package/dist/bridge/surface/methods/functions/listTriggers.js.map +1 -1
  327. package/dist/bridge/surface/methods/messaging/deliveries.d.ts +2 -1
  328. package/dist/bridge/surface/methods/messaging/deliveries.d.ts.map +1 -1
  329. package/dist/bridge/surface/methods/messaging/deliveries.js +1 -0
  330. package/dist/bridge/surface/methods/messaging/deliveries.js.map +1 -1
  331. package/dist/bridge/surface/methods/messaging/send.d.ts +2 -1
  332. package/dist/bridge/surface/methods/messaging/send.d.ts.map +1 -1
  333. package/dist/bridge/surface/methods/messaging/send.js +2 -1
  334. package/dist/bridge/surface/methods/messaging/send.js.map +1 -1
  335. package/dist/bridge/surface/methods/messaging/subscribeToTopic.d.ts +2 -1
  336. package/dist/bridge/surface/methods/messaging/subscribeToTopic.d.ts.map +1 -1
  337. package/dist/bridge/surface/methods/messaging/subscribeToTopic.js +1 -0
  338. package/dist/bridge/surface/methods/messaging/subscribeToTopic.js.map +1 -1
  339. package/dist/bridge/surface/methods/messaging/tokens.d.ts +2 -1
  340. package/dist/bridge/surface/methods/messaging/tokens.d.ts.map +1 -1
  341. package/dist/bridge/surface/methods/messaging/tokens.js +1 -0
  342. package/dist/bridge/surface/methods/messaging/tokens.js.map +1 -1
  343. package/dist/bridge/surface/methods/messaging/unsubscribeFromTopic.d.ts +2 -1
  344. package/dist/bridge/surface/methods/messaging/unsubscribeFromTopic.d.ts.map +1 -1
  345. package/dist/bridge/surface/methods/messaging/unsubscribeFromTopic.js +1 -0
  346. package/dist/bridge/surface/methods/messaging/unsubscribeFromTopic.js.map +1 -1
  347. package/dist/bridge/surface/methods/registry.d.ts.map +1 -1
  348. package/dist/bridge/surface/methods/registry.js +2 -8
  349. package/dist/bridge/surface/methods/registry.js.map +1 -1
  350. package/dist/bridge/surface/methods/rules/explainDenial.d.ts +1 -0
  351. package/dist/bridge/surface/methods/rules/explainDenial.d.ts.map +1 -1
  352. package/dist/bridge/surface/methods/rules/explainDenial.js +1 -0
  353. package/dist/bridge/surface/methods/rules/explainDenial.js.map +1 -1
  354. package/dist/bridge/surface/methods/rules/getStdlib.d.ts +1 -0
  355. package/dist/bridge/surface/methods/rules/getStdlib.d.ts.map +1 -1
  356. package/dist/bridge/surface/methods/rules/getStdlib.js +1 -0
  357. package/dist/bridge/surface/methods/rules/getStdlib.js.map +1 -1
  358. package/dist/bridge/surface/methods/rules/lint.d.ts +1 -0
  359. package/dist/bridge/surface/methods/rules/lint.d.ts.map +1 -1
  360. package/dist/bridge/surface/methods/rules/lint.js +1 -0
  361. package/dist/bridge/surface/methods/rules/lint.js.map +1 -1
  362. package/dist/bridge/surface/methods/rules/listStdlib.d.ts +1 -0
  363. package/dist/bridge/surface/methods/rules/listStdlib.d.ts.map +1 -1
  364. package/dist/bridge/surface/methods/rules/listStdlib.js +1 -0
  365. package/dist/bridge/surface/methods/rules/listStdlib.js.map +1 -1
  366. package/dist/bridge/surface/methods/rules/set.d.ts +1 -0
  367. package/dist/bridge/surface/methods/rules/set.d.ts.map +1 -1
  368. package/dist/bridge/surface/methods/rules/set.js +1 -0
  369. package/dist/bridge/surface/methods/rules/set.js.map +1 -1
  370. package/dist/bridge/surface/methods/rules/simulate.d.ts +1 -0
  371. package/dist/bridge/surface/methods/rules/simulate.d.ts.map +1 -1
  372. package/dist/bridge/surface/methods/rules/simulate.js +1 -0
  373. package/dist/bridge/surface/methods/rules/simulate.js.map +1 -1
  374. package/dist/bridge/surface/methods/sandbox/activity.d.ts +2 -1
  375. package/dist/bridge/surface/methods/sandbox/activity.d.ts.map +1 -1
  376. package/dist/bridge/surface/methods/sandbox/activity.js +2 -1
  377. package/dist/bridge/surface/methods/sandbox/activity.js.map +1 -1
  378. package/dist/bridge/surface/methods/sandbox/advanceClock.d.ts +2 -1
  379. package/dist/bridge/surface/methods/sandbox/advanceClock.d.ts.map +1 -1
  380. package/dist/bridge/surface/methods/sandbox/advanceClock.js +1 -0
  381. package/dist/bridge/surface/methods/sandbox/advanceClock.js.map +1 -1
  382. package/dist/bridge/surface/methods/sandbox/apply.d.ts +1 -0
  383. package/dist/bridge/surface/methods/sandbox/apply.d.ts.map +1 -1
  384. package/dist/bridge/surface/methods/sandbox/apply.js +1 -0
  385. package/dist/bridge/surface/methods/sandbox/apply.js.map +1 -1
  386. package/dist/bridge/surface/methods/sandbox/checkpoint.d.ts +1 -0
  387. package/dist/bridge/surface/methods/sandbox/checkpoint.d.ts.map +1 -1
  388. package/dist/bridge/surface/methods/sandbox/checkpoint.js +1 -0
  389. package/dist/bridge/surface/methods/sandbox/checkpoint.js.map +1 -1
  390. package/dist/bridge/surface/methods/sandbox/deleteCapture.d.ts +1 -0
  391. package/dist/bridge/surface/methods/sandbox/deleteCapture.d.ts.map +1 -1
  392. package/dist/bridge/surface/methods/sandbox/deleteCapture.js +1 -1
  393. package/dist/bridge/surface/methods/sandbox/deleteCapture.js.map +1 -1
  394. package/dist/bridge/surface/methods/sandbox/deleteCheckpoint.d.ts +1 -0
  395. package/dist/bridge/surface/methods/sandbox/deleteCheckpoint.d.ts.map +1 -1
  396. package/dist/bridge/surface/methods/sandbox/deleteCheckpoint.js +1 -0
  397. package/dist/bridge/surface/methods/sandbox/deleteCheckpoint.js.map +1 -1
  398. package/dist/bridge/surface/methods/sandbox/diff.d.ts +1 -0
  399. package/dist/bridge/surface/methods/sandbox/diff.d.ts.map +1 -1
  400. package/dist/bridge/surface/methods/sandbox/diff.js +1 -0
  401. package/dist/bridge/surface/methods/sandbox/diff.js.map +1 -1
  402. package/dist/bridge/surface/methods/sandbox/discard.d.ts +1 -0
  403. package/dist/bridge/surface/methods/sandbox/discard.d.ts.map +1 -1
  404. package/dist/bridge/surface/methods/sandbox/discard.js +1 -0
  405. package/dist/bridge/surface/methods/sandbox/discard.js.map +1 -1
  406. package/dist/bridge/surface/methods/sandbox/events.d.ts +2 -1
  407. package/dist/bridge/surface/methods/sandbox/events.d.ts.map +1 -1
  408. package/dist/bridge/surface/methods/sandbox/events.js +2 -1
  409. package/dist/bridge/surface/methods/sandbox/events.js.map +1 -1
  410. package/dist/bridge/surface/methods/sandbox/exportFixture.d.ts +1 -0
  411. package/dist/bridge/surface/methods/sandbox/exportFixture.d.ts.map +1 -1
  412. package/dist/bridge/surface/methods/sandbox/exportFixture.js +1 -0
  413. package/dist/bridge/surface/methods/sandbox/exportFixture.js.map +1 -1
  414. package/dist/bridge/surface/methods/sandbox/fork.d.ts +1 -0
  415. package/dist/bridge/surface/methods/sandbox/fork.d.ts.map +1 -1
  416. package/dist/bridge/surface/methods/sandbox/fork.js +1 -0
  417. package/dist/bridge/surface/methods/sandbox/fork.js.map +1 -1
  418. package/dist/bridge/surface/methods/sandbox/inspect.d.ts +2 -1
  419. package/dist/bridge/surface/methods/sandbox/inspect.d.ts.map +1 -1
  420. package/dist/bridge/surface/methods/sandbox/inspect.js +2 -1
  421. package/dist/bridge/surface/methods/sandbox/inspect.js.map +1 -1
  422. package/dist/bridge/surface/methods/sandbox/listBranches.d.ts +1 -0
  423. package/dist/bridge/surface/methods/sandbox/listBranches.d.ts.map +1 -1
  424. package/dist/bridge/surface/methods/sandbox/listBranches.js +1 -0
  425. package/dist/bridge/surface/methods/sandbox/listBranches.js.map +1 -1
  426. package/dist/bridge/surface/methods/sandbox/listCaptures.d.ts +1 -0
  427. package/dist/bridge/surface/methods/sandbox/listCaptures.d.ts.map +1 -1
  428. package/dist/bridge/surface/methods/sandbox/listCaptures.js +1 -1
  429. package/dist/bridge/surface/methods/sandbox/listCaptures.js.map +1 -1
  430. package/dist/bridge/surface/methods/sandbox/listCheckpoints.d.ts +1 -0
  431. package/dist/bridge/surface/methods/sandbox/listCheckpoints.d.ts.map +1 -1
  432. package/dist/bridge/surface/methods/sandbox/listCheckpoints.js +1 -0
  433. package/dist/bridge/surface/methods/sandbox/listCheckpoints.js.map +1 -1
  434. package/dist/bridge/surface/methods/sandbox/listeners.d.ts +2 -1
  435. package/dist/bridge/surface/methods/sandbox/listeners.d.ts.map +1 -1
  436. package/dist/bridge/surface/methods/sandbox/listeners.js +1 -0
  437. package/dist/bridge/surface/methods/sandbox/listeners.js.map +1 -1
  438. package/dist/bridge/surface/methods/sandbox/openCapture.d.ts +1 -0
  439. package/dist/bridge/surface/methods/sandbox/openCapture.d.ts.map +1 -1
  440. package/dist/bridge/surface/methods/sandbox/openCapture.js +1 -1
  441. package/dist/bridge/surface/methods/sandbox/openCapture.js.map +1 -1
  442. package/dist/bridge/surface/methods/sandbox/promote.d.ts +1 -0
  443. package/dist/bridge/surface/methods/sandbox/promote.d.ts.map +1 -1
  444. package/dist/bridge/surface/methods/sandbox/promote.js +1 -0
  445. package/dist/bridge/surface/methods/sandbox/promote.js.map +1 -1
  446. package/dist/bridge/surface/methods/sandbox/renameCapture.d.ts +3 -2
  447. package/dist/bridge/surface/methods/sandbox/renameCapture.d.ts.map +1 -1
  448. package/dist/bridge/surface/methods/sandbox/renameCapture.js +1 -1
  449. package/dist/bridge/surface/methods/sandbox/renameCapture.js.map +1 -1
  450. package/dist/bridge/surface/methods/sandbox/reset.d.ts +3 -2
  451. package/dist/bridge/surface/methods/sandbox/reset.d.ts.map +1 -1
  452. package/dist/bridge/surface/methods/sandbox/reset.js +1 -0
  453. package/dist/bridge/surface/methods/sandbox/reset.js.map +1 -1
  454. package/dist/bridge/surface/methods/sandbox/resetClock.d.ts +2 -1
  455. package/dist/bridge/surface/methods/sandbox/resetClock.d.ts.map +1 -1
  456. package/dist/bridge/surface/methods/sandbox/resetClock.js +1 -0
  457. package/dist/bridge/surface/methods/sandbox/resetClock.js.map +1 -1
  458. package/dist/bridge/surface/methods/sandbox/restore.d.ts +1 -0
  459. package/dist/bridge/surface/methods/sandbox/restore.d.ts.map +1 -1
  460. package/dist/bridge/surface/methods/sandbox/restore.js +1 -0
  461. package/dist/bridge/surface/methods/sandbox/restore.js.map +1 -1
  462. package/dist/bridge/surface/methods/sandbox/saveCapture.d.ts +1 -0
  463. package/dist/bridge/surface/methods/sandbox/saveCapture.d.ts.map +1 -1
  464. package/dist/bridge/surface/methods/sandbox/saveCapture.js +1 -1
  465. package/dist/bridge/surface/methods/sandbox/saveCapture.js.map +1 -1
  466. package/dist/bridge/surface/methods/sandbox/seed.d.ts +2 -1
  467. package/dist/bridge/surface/methods/sandbox/seed.d.ts.map +1 -1
  468. package/dist/bridge/surface/methods/sandbox/seed.js +3 -2
  469. package/dist/bridge/surface/methods/sandbox/seed.js.map +1 -1
  470. package/dist/bridge/surface/methods/sandbox/seedFromFixture.d.ts +1 -0
  471. package/dist/bridge/surface/methods/sandbox/seedFromFixture.d.ts.map +1 -1
  472. package/dist/bridge/surface/methods/sandbox/seedFromFixture.js +1 -0
  473. package/dist/bridge/surface/methods/sandbox/seedFromFixture.js.map +1 -1
  474. package/dist/bridge/surface/methods/sandbox/setClock.d.ts +2 -1
  475. package/dist/bridge/surface/methods/sandbox/setClock.d.ts.map +1 -1
  476. package/dist/bridge/surface/methods/sandbox/setClock.js +1 -0
  477. package/dist/bridge/surface/methods/sandbox/setClock.js.map +1 -1
  478. package/dist/bridge/surface/methods/sandbox-registry.d.ts +6 -0
  479. package/dist/bridge/surface/methods/sandbox-registry.d.ts.map +1 -0
  480. package/dist/bridge/surface/methods/sandbox-registry.js +21 -0
  481. package/dist/bridge/surface/methods/sandbox-registry.js.map +1 -0
  482. package/dist/bridge/surface/methods/storage/deleteObject.d.ts +2 -1
  483. package/dist/bridge/surface/methods/storage/deleteObject.d.ts.map +1 -1
  484. package/dist/bridge/surface/methods/storage/deleteObject.js +1 -0
  485. package/dist/bridge/surface/methods/storage/deleteObject.js.map +1 -1
  486. package/dist/bridge/surface/methods/storage/getBytes.d.ts +2 -1
  487. package/dist/bridge/surface/methods/storage/getBytes.d.ts.map +1 -1
  488. package/dist/bridge/surface/methods/storage/getBytes.js +1 -0
  489. package/dist/bridge/surface/methods/storage/getBytes.js.map +1 -1
  490. package/dist/bridge/surface/methods/storage/getDownloadURL.d.ts +2 -1
  491. package/dist/bridge/surface/methods/storage/getDownloadURL.d.ts.map +1 -1
  492. package/dist/bridge/surface/methods/storage/getDownloadURL.js +1 -0
  493. package/dist/bridge/surface/methods/storage/getDownloadURL.js.map +1 -1
  494. package/dist/bridge/surface/methods/storage/getMetadata.d.ts +2 -1
  495. package/dist/bridge/surface/methods/storage/getMetadata.d.ts.map +1 -1
  496. package/dist/bridge/surface/methods/storage/getMetadata.js +1 -0
  497. package/dist/bridge/surface/methods/storage/getMetadata.js.map +1 -1
  498. package/dist/bridge/surface/methods/storage/listAll.d.ts +2 -1
  499. package/dist/bridge/surface/methods/storage/listAll.d.ts.map +1 -1
  500. package/dist/bridge/surface/methods/storage/listAll.js +1 -0
  501. package/dist/bridge/surface/methods/storage/listAll.js.map +1 -1
  502. package/dist/bridge/surface/methods/storage/provision.d.ts +1 -0
  503. package/dist/bridge/surface/methods/storage/provision.d.ts.map +1 -1
  504. package/dist/bridge/surface/methods/storage/provision.js +1 -0
  505. package/dist/bridge/surface/methods/storage/provision.js.map +1 -1
  506. package/dist/bridge/surface/methods/storage/setCrossServiceIam.d.ts +2 -1
  507. package/dist/bridge/surface/methods/storage/setCrossServiceIam.d.ts.map +1 -1
  508. package/dist/bridge/surface/methods/storage/setCrossServiceIam.js +1 -0
  509. package/dist/bridge/surface/methods/storage/setCrossServiceIam.js.map +1 -1
  510. package/dist/bridge/surface/methods/storage/status.d.ts +1 -0
  511. package/dist/bridge/surface/methods/storage/status.d.ts.map +1 -1
  512. package/dist/bridge/surface/methods/storage/status.js +1 -0
  513. package/dist/bridge/surface/methods/storage/status.js.map +1 -1
  514. package/dist/bridge/surface/methods/storage/updateMetadata.d.ts +6 -5
  515. package/dist/bridge/surface/methods/storage/updateMetadata.d.ts.map +1 -1
  516. package/dist/bridge/surface/methods/storage/updateMetadata.js +1 -0
  517. package/dist/bridge/surface/methods/storage/updateMetadata.js.map +1 -1
  518. package/dist/bridge/surface/methods/storage/uploadBytes.d.ts +1 -0
  519. package/dist/bridge/surface/methods/storage/uploadBytes.d.ts.map +1 -1
  520. package/dist/bridge/surface/methods/storage/uploadBytes.js +1 -0
  521. package/dist/bridge/surface/methods/storage/uploadBytes.js.map +1 -1
  522. package/dist/bridge/surface/render/discriminator-schemas.d.ts +2 -2
  523. package/dist/bridge/surface/request-instant.d.ts +2 -2
  524. package/dist/bridge/surface/request-instant.d.ts.map +1 -1
  525. package/dist/bridge/surface/request-instant.js.map +1 -1
  526. package/dist/bridge/surface/rules-engines/database.d.ts.map +1 -1
  527. package/dist/bridge/surface/rules-engines/database.js +1 -2
  528. package/dist/bridge/surface/rules-engines/database.js.map +1 -1
  529. package/dist/bridge/surface/rules-engines/storage-request-resource.d.ts +38 -0
  530. package/dist/bridge/surface/rules-engines/storage-request-resource.d.ts.map +1 -0
  531. package/dist/bridge/surface/rules-engines/storage-request-resource.js +246 -0
  532. package/dist/bridge/surface/rules-engines/storage-request-resource.js.map +1 -0
  533. package/dist/bridge/surface/rules-engines/storage.d.ts.map +1 -1
  534. package/dist/bridge/surface/rules-engines/storage.js +44 -65
  535. package/dist/bridge/surface/rules-engines/storage.js.map +1 -1
  536. package/dist/bridge/surface/sandbox-context.d.ts +25 -0
  537. package/dist/bridge/surface/sandbox-context.d.ts.map +1 -0
  538. package/dist/bridge/surface/sandbox-context.js +29 -0
  539. package/dist/bridge/surface/sandbox-context.js.map +1 -0
  540. package/dist/bridge/surface/service-handles.d.ts +6 -6
  541. package/dist/bridge/surface/service-handles.d.ts.map +1 -1
  542. package/dist/bridge/surface/service-handles.js +7 -4
  543. package/dist/bridge/surface/service-handles.js.map +1 -1
  544. package/dist/bridge/surface/sign-in.d.ts +2 -2
  545. package/dist/bridge/surface/sign-in.d.ts.map +1 -1
  546. package/dist/bridge/surface/sign-in.js +1 -1
  547. package/dist/bridge/surface/sign-in.js.map +1 -1
  548. package/dist/bridge/surface/storage-rules.d.ts +2 -9
  549. package/dist/bridge/surface/storage-rules.d.ts.map +1 -1
  550. package/dist/bridge/surface/storage-rules.js +0 -10
  551. package/dist/bridge/surface/storage-rules.js.map +1 -1
  552. package/dist/bridge/surface/stored-identity.d.ts +3 -3
  553. package/dist/bridge/surface/stored-identity.d.ts.map +1 -1
  554. package/dist/bridge/surface/stored-identity.js.map +1 -1
  555. package/dist/bridge/surface/types.d.ts +29 -8
  556. package/dist/bridge/surface/types.d.ts.map +1 -1
  557. package/dist/cli/firebase-json.d.ts +35 -7
  558. package/dist/cli/firebase-json.d.ts.map +1 -1
  559. package/dist/cli/firebase-json.js +13 -0
  560. package/dist/cli/firebase-json.js.map +1 -1
  561. package/dist/cli/firestore-indexes.d.ts.map +1 -1
  562. package/dist/cli/firestore-indexes.js +2 -1
  563. package/dist/cli/firestore-indexes.js.map +1 -1
  564. package/dist/cli/index.d.ts +6 -0
  565. package/dist/cli/index.d.ts.map +1 -1
  566. package/dist/cli/index.js +44 -11
  567. package/dist/cli/index.js.map +1 -1
  568. package/dist/cli/public-dir-hint.d.ts +8 -0
  569. package/dist/cli/public-dir-hint.d.ts.map +1 -0
  570. package/dist/cli/public-dir-hint.js +30 -0
  571. package/dist/cli/public-dir-hint.js.map +1 -0
  572. package/dist/cli/run.d.ts +8 -2
  573. package/dist/cli/run.d.ts.map +1 -1
  574. package/dist/cli/run.js +28 -5
  575. package/dist/cli/run.js.map +1 -1
  576. package/dist/cli/sandbox-runner.d.ts.map +1 -1
  577. package/dist/cli/sandbox-runner.js +11 -2
  578. package/dist/cli/sandbox-runner.js.map +1 -1
  579. package/dist/cli/serve-diagnostics.d.ts.map +1 -1
  580. package/dist/cli/serve-diagnostics.js +11 -1
  581. package/dist/cli/serve-diagnostics.js.map +1 -1
  582. package/dist/cli/serve.d.ts.map +1 -1
  583. package/dist/cli/serve.js +25 -24
  584. package/dist/cli/serve.js.map +1 -1
  585. package/dist/cli/snapshot.d.ts.map +1 -1
  586. package/dist/cli/snapshot.js +13 -5
  587. package/dist/cli/snapshot.js.map +1 -1
  588. package/dist/cli/surface-method-runner.js +1 -1
  589. package/dist/cli/surface-method-runner.js.map +1 -1
  590. package/dist/cli/verify.d.ts.map +1 -1
  591. package/dist/cli/verify.js +10 -1
  592. package/dist/cli/verify.js.map +1 -1
  593. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  594. package/dist/conformance/.generated/can-i-use-browser.js +19 -3
  595. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  596. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  597. package/dist/conformance/.generated/can-i-use.js +1 -1
  598. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  599. package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
  600. package/dist/conformance/.generated/conformance-docs.js +1 -1
  601. package/dist/conformance/.generated/conformance-docs.js.map +1 -1
  602. package/dist/conformance/.generated/served-availability.d.ts.map +1 -1
  603. package/dist/conformance/.generated/served-availability.js +1 -1
  604. package/dist/conformance/.generated/served-availability.js.map +1 -1
  605. package/dist/discover/merge.d.ts.map +1 -1
  606. package/dist/discover/merge.js +11 -3
  607. package/dist/discover/merge.js.map +1 -1
  608. package/dist/functions/child-protocol.d.ts +43 -0
  609. package/dist/functions/child-protocol.d.ts.map +1 -0
  610. package/dist/functions/child-protocol.js +14 -0
  611. package/dist/functions/child-protocol.js.map +1 -0
  612. package/dist/functions/child.d.ts +2 -0
  613. package/dist/functions/child.d.ts.map +1 -0
  614. package/dist/functions/child.js +92 -0
  615. package/dist/functions/child.js.map +1 -0
  616. package/dist/{functions-rtdb → functions}/development-runtime.d.ts +5 -4
  617. package/dist/functions/development-runtime.d.ts.map +1 -0
  618. package/dist/{functions-rtdb → functions}/development-runtime.js +2 -2
  619. package/dist/functions/development-runtime.js.map +1 -0
  620. package/dist/functions/endpoints.d.ts +39 -0
  621. package/dist/functions/endpoints.d.ts.map +1 -0
  622. package/dist/functions/endpoints.js +48 -0
  623. package/dist/functions/endpoints.js.map +1 -0
  624. package/dist/functions/events.d.ts.map +1 -0
  625. package/dist/functions/events.js.map +1 -0
  626. package/dist/functions/execution-log.d.ts.map +1 -0
  627. package/dist/functions/execution-log.js.map +1 -0
  628. package/dist/functions/module-loader.d.ts.map +1 -0
  629. package/dist/functions/module-loader.js.map +1 -0
  630. package/dist/functions/project.d.ts +7 -0
  631. package/dist/functions/project.d.ts.map +1 -0
  632. package/dist/{functions-rtdb → functions}/project.js +1 -1
  633. package/dist/functions/project.js.map +1 -0
  634. package/dist/functions/rtdb/child-runtime.d.ts +23 -0
  635. package/dist/functions/rtdb/child-runtime.d.ts.map +1 -0
  636. package/dist/functions/rtdb/child-runtime.js +102 -0
  637. package/dist/functions/rtdb/child-runtime.js.map +1 -0
  638. package/dist/functions/rtdb/delivery.d.ts.map +1 -0
  639. package/dist/functions/rtdb/delivery.js.map +1 -0
  640. package/dist/{functions-rtdb → functions/rtdb}/discovery.d.ts +3 -20
  641. package/dist/functions/rtdb/discovery.d.ts.map +1 -0
  642. package/dist/{functions-rtdb → functions/rtdb}/discovery.js +6 -21
  643. package/dist/functions/rtdb/discovery.js.map +1 -0
  644. package/dist/functions/rtdb/event.d.ts.map +1 -0
  645. package/dist/functions/rtdb/event.js.map +1 -0
  646. package/dist/functions/rtdb/execution.d.ts.map +1 -0
  647. package/dist/functions/rtdb/execution.js.map +1 -0
  648. package/dist/functions/rtdb/in-memory-delivery.d.ts.map +1 -0
  649. package/dist/functions/rtdb/in-memory-delivery.js.map +1 -0
  650. package/dist/functions/rtdb/projection.d.ts.map +1 -0
  651. package/dist/functions/rtdb/projection.js.map +1 -0
  652. package/dist/functions/rtdb/reference-pattern.d.ts.map +1 -0
  653. package/dist/functions/rtdb/reference-pattern.js.map +1 -0
  654. package/dist/{functions-rtdb → functions/rtdb}/remote-delivery.d.ts +1 -1
  655. package/dist/functions/rtdb/remote-delivery.d.ts.map +1 -0
  656. package/dist/functions/rtdb/remote-delivery.js.map +1 -0
  657. package/dist/{functions-rtdb/child.d.ts → functions/spawn.d.ts} +16 -38
  658. package/dist/functions/spawn.d.ts.map +1 -0
  659. package/dist/functions/spawn.js +166 -0
  660. package/dist/functions/spawn.js.map +1 -0
  661. package/dist/functions/unsupported.d.ts +23 -0
  662. package/dist/functions/unsupported.d.ts.map +1 -0
  663. package/dist/functions/unsupported.js +25 -0
  664. package/dist/functions/unsupported.js.map +1 -0
  665. package/dist/google-endpoints.d.ts +9 -2
  666. package/dist/google-endpoints.d.ts.map +1 -1
  667. package/dist/google-endpoints.js +72 -3
  668. package/dist/google-endpoints.js.map +1 -1
  669. package/dist/next/bridge-import-loader.d.ts +9 -0
  670. package/dist/next/bridge-import-loader.d.ts.map +1 -0
  671. package/dist/next/bridge-import-loader.js +45 -0
  672. package/dist/next/bridge-import-loader.js.map +1 -0
  673. package/dist/next/bridge-imports.d.ts +26 -0
  674. package/dist/next/bridge-imports.d.ts.map +1 -0
  675. package/dist/next/bridge-imports.js +90 -0
  676. package/dist/next/bridge-imports.js.map +1 -0
  677. package/dist/next/client-aliases.d.ts +13 -5
  678. package/dist/next/client-aliases.d.ts.map +1 -1
  679. package/dist/next/client-aliases.js +14 -27
  680. package/dist/next/client-aliases.js.map +1 -1
  681. package/dist/next/guard.d.ts +3 -2
  682. package/dist/next/guard.d.ts.map +1 -1
  683. package/dist/next/guard.js +28 -10
  684. package/dist/next/guard.js.map +1 -1
  685. package/dist/next/turbopack-config.d.ts +9 -0
  686. package/dist/next/turbopack-config.d.ts.map +1 -1
  687. package/dist/next/turbopack-config.js +21 -0
  688. package/dist/next/turbopack-config.js.map +1 -1
  689. package/dist/next/webpack-config.d.ts +9 -0
  690. package/dist/next/webpack-config.d.ts.map +1 -1
  691. package/dist/next/webpack-config.js +18 -0
  692. package/dist/next/webpack-config.js.map +1 -1
  693. package/dist/next/with-pyric.d.ts +1 -0
  694. package/dist/next/with-pyric.d.ts.map +1 -1
  695. package/dist/next/with-pyric.js +25 -0
  696. package/dist/next/with-pyric.js.map +1 -1
  697. package/dist/register/activation.d.ts +16 -0
  698. package/dist/register/activation.d.ts.map +1 -0
  699. package/dist/register/activation.js +22 -0
  700. package/dist/register/activation.js.map +1 -0
  701. package/dist/register/app-bridge-admin-app-check.d.ts.map +1 -1
  702. package/dist/register/app-bridge-admin-app-check.js +3 -1
  703. package/dist/register/app-bridge-admin-app-check.js.map +1 -1
  704. package/dist/register/child-process-guard.d.ts +43 -0
  705. package/dist/register/child-process-guard.d.ts.map +1 -0
  706. package/dist/register/child-process-guard.js +165 -0
  707. package/dist/register/child-process-guard.js.map +1 -0
  708. package/dist/register/client/bootstrap.js +6 -1
  709. package/dist/register/client/bootstrap.js.map +1 -1
  710. package/dist/register/connect-prototypes.d.ts +9 -0
  711. package/dist/register/connect-prototypes.d.ts.map +1 -1
  712. package/dist/register/connect-prototypes.js +11 -0
  713. package/dist/register/connect-prototypes.js.map +1 -1
  714. package/dist/register/hooks.d.ts +7 -1
  715. package/dist/register/hooks.d.ts.map +1 -1
  716. package/dist/register/hooks.js +44 -2
  717. package/dist/register/hooks.js.map +1 -1
  718. package/dist/register/index.d.ts.map +1 -1
  719. package/dist/register/index.js +93 -23
  720. package/dist/register/index.js.map +1 -1
  721. package/dist/register/mapping.d.ts +33 -0
  722. package/dist/register/mapping.d.ts.map +1 -1
  723. package/dist/register/mapping.js +45 -3
  724. package/dist/register/mapping.js.map +1 -1
  725. package/dist/register/net-guard.d.ts +17 -0
  726. package/dist/register/net-guard.d.ts.map +1 -1
  727. package/dist/register/net-guard.js +118 -41
  728. package/dist/register/net-guard.js.map +1 -1
  729. package/dist/register/package-identity.d.ts +16 -0
  730. package/dist/register/package-identity.d.ts.map +1 -0
  731. package/dist/register/package-identity.js +97 -0
  732. package/dist/register/package-identity.js.map +1 -0
  733. package/dist/register/swap-or-stop.d.ts +27 -0
  734. package/dist/register/swap-or-stop.d.ts.map +1 -0
  735. package/dist/register/swap-or-stop.js +170 -0
  736. package/dist/register/swap-or-stop.js.map +1 -0
  737. package/dist/register/worker-guard.d.ts +20 -0
  738. package/dist/register/worker-guard.d.ts.map +1 -0
  739. package/dist/register/worker-guard.js +77 -0
  740. package/dist/register/worker-guard.js.map +1 -0
  741. package/dist/remote/resolve-host.d.ts +9 -0
  742. package/dist/remote/resolve-host.d.ts.map +1 -1
  743. package/dist/remote/resolve-host.js +13 -2
  744. package/dist/remote/resolve-host.js.map +1 -1
  745. package/dist/serve/ai-proxy.d.ts +2 -0
  746. package/dist/serve/ai-proxy.d.ts.map +1 -1
  747. package/dist/serve/ai-proxy.js +33 -8
  748. package/dist/serve/ai-proxy.js.map +1 -1
  749. package/dist/serve/app-ports.d.ts +48 -0
  750. package/dist/serve/app-ports.d.ts.map +1 -0
  751. package/dist/serve/app-ports.js +82 -0
  752. package/dist/serve/app-ports.js.map +1 -0
  753. package/dist/serve/bridge-mount.d.ts +13 -0
  754. package/dist/serve/bridge-mount.d.ts.map +1 -1
  755. package/dist/serve/bridge-mount.js +28 -8
  756. package/dist/serve/bridge-mount.js.map +1 -1
  757. package/dist/serve/bundler.d.ts +6 -0
  758. package/dist/serve/bundler.d.ts.map +1 -1
  759. package/dist/serve/bundler.js +78 -26
  760. package/dist/serve/bundler.js.map +1 -1
  761. package/dist/serve/discovery.d.ts +17 -3
  762. package/dist/serve/discovery.d.ts.map +1 -1
  763. package/dist/serve/discovery.js +199 -63
  764. package/dist/serve/discovery.js.map +1 -1
  765. package/dist/serve/entries/auth.d.ts.map +1 -1
  766. package/dist/serve/entries/auth.js +19 -1
  767. package/dist/serve/entries/auth.js.map +1 -1
  768. package/dist/serve/entries/firestore-surface.d.ts +1 -0
  769. package/dist/serve/entries/firestore-surface.d.ts.map +1 -1
  770. package/dist/serve/entries/firestore-surface.js +1 -0
  771. package/dist/serve/entries/firestore-surface.js.map +1 -1
  772. package/dist/serve/entries/init-payload.d.ts +9 -2
  773. package/dist/serve/entries/init-payload.d.ts.map +1 -1
  774. package/dist/serve/entries/init-payload.js +25 -5
  775. package/dist/serve/entries/init-payload.js.map +1 -1
  776. package/dist/serve/entries/moved-host.d.ts +18 -0
  777. package/dist/serve/entries/moved-host.d.ts.map +1 -0
  778. package/dist/serve/entries/moved-host.js +14 -0
  779. package/dist/serve/entries/moved-host.js.map +1 -0
  780. package/dist/serve/entries/runtime-origin.d.ts +6 -0
  781. package/dist/serve/entries/runtime-origin.d.ts.map +1 -1
  782. package/dist/serve/entries/runtime-origin.js.map +1 -1
  783. package/dist/serve/entries/unsupported/firestore.d.ts +0 -1
  784. package/dist/serve/entries/unsupported/firestore.d.ts.map +1 -1
  785. package/dist/serve/entries/unsupported/firestore.js +0 -1
  786. package/dist/serve/entries/unsupported/firestore.js.map +1 -1
  787. package/dist/serve/entries/worker-runtime.d.ts.map +1 -1
  788. package/dist/serve/entries/worker-runtime.js +19 -7
  789. package/dist/serve/entries/worker-runtime.js.map +1 -1
  790. package/dist/serve/firebase-module-swap.d.ts +19 -2
  791. package/dist/serve/firebase-module-swap.d.ts.map +1 -1
  792. package/dist/serve/firebase-module-swap.js +92 -16
  793. package/dist/serve/firebase-module-swap.js.map +1 -1
  794. package/dist/serve/gemini-proxy.js +2 -2
  795. package/dist/serve/gemini-proxy.js.map +1 -1
  796. package/dist/serve/hosted/runtime.d.ts.map +1 -1
  797. package/dist/serve/hosted/runtime.js +10 -3
  798. package/dist/serve/hosted/runtime.js.map +1 -1
  799. package/dist/serve/namespace.d.ts +7 -0
  800. package/dist/serve/namespace.d.ts.map +1 -1
  801. package/dist/serve/namespace.js +32 -24
  802. package/dist/serve/namespace.js.map +1 -1
  803. package/dist/serve/repro/compare.d.ts +2 -1
  804. package/dist/serve/repro/compare.d.ts.map +1 -1
  805. package/dist/serve/repro/compare.js +9 -1
  806. package/dist/serve/repro/compare.js.map +1 -1
  807. package/dist/serve/rules-fixture-check.d.ts.map +1 -1
  808. package/dist/serve/rules-fixture-check.js +22 -10
  809. package/dist/serve/rules-fixture-check.js.map +1 -1
  810. package/dist/serve/rules.d.ts +35 -9
  811. package/dist/serve/rules.d.ts.map +1 -1
  812. package/dist/serve/rules.js +72 -21
  813. package/dist/serve/rules.js.map +1 -1
  814. package/dist/serve/sandbox-session.d.ts +3 -0
  815. package/dist/serve/sandbox-session.d.ts.map +1 -1
  816. package/dist/serve/sandbox-session.js +10 -3
  817. package/dist/serve/sandbox-session.js.map +1 -1
  818. package/dist/serve/server.d.ts +10 -2
  819. package/dist/serve/server.d.ts.map +1 -1
  820. package/dist/serve/server.js +24 -4
  821. package/dist/serve/server.js.map +1 -1
  822. package/dist/serve/site-ui/_astro/{RulesCodeEditor.Cp_-FK3b.js → RulesCodeEditor.D-eQLCvu.js} +1 -1
  823. package/dist/serve/site-ui/_astro/app.BjQiEBOY.js +1 -0
  824. package/dist/serve/site-ui/_astro/app.C84Qr10v.js +151 -0
  825. package/dist/serve/site-ui/_astro/{chess-showcase.CVhCNUi_.js → chess-showcase.CsH1s4g7.js} +1 -1
  826. package/dist/serve/site-ui/_astro/{example-runtime.zC1l-Yka.js → example-runtime.CTp8mh7I.js} +1 -1
  827. package/dist/serve/site-ui/_astro/sandbox-controls.DI8MTU3L.js +1725 -0
  828. package/dist/serve/site-ui/_astro/{seed.B4vza_Bv.js → seed.BvtbLu-q.js} +1 -1
  829. package/dist/serve/site-ui/_astro/writes.D8gcuovU.js +1 -0
  830. package/dist/serve/site-ui/auth/index.html +1 -1
  831. package/dist/serve/site-ui/docs/ai-compat/index.html +48 -9
  832. package/dist/serve/site-ui/docs/ai-compat.md +53 -8
  833. package/dist/serve/site-ui/docs/app-check-compat/index.html +102 -26
  834. package/dist/serve/site-ui/docs/app-check-compat.md +107 -25
  835. package/dist/serve/site-ui/docs/auth-compat/index.html +33 -21
  836. package/dist/serve/site-ui/docs/auth-compat.md +35 -20
  837. package/dist/serve/site-ui/docs/build/ai-logic/index.html +13 -4
  838. package/dist/serve/site-ui/docs/build/ai-logic.md +14 -4
  839. package/dist/serve/site-ui/docs/conformance-scores/index.html +2 -2
  840. package/dist/serve/site-ui/docs/conformance-scores.md +2 -2
  841. package/dist/serve/site-ui/docs/database-compat/index.html +113 -49
  842. package/dist/serve/site-ui/docs/database-compat.md +118 -48
  843. package/dist/serve/site-ui/docs/firestore-compat/index.html +144 -37
  844. package/dist/serve/site-ui/docs/firestore-compat.md +149 -36
  845. package/dist/serve/site-ui/docs/firestore-swift-compat/index.html +1 -1
  846. package/dist/serve/site-ui/docs/firestore-swift-compat.md +1 -1
  847. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +12 -12
  848. package/dist/serve/site-ui/docs/functions-rtdb-compat.md +12 -12
  849. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
  850. package/dist/serve/site-ui/docs/get-started/how-the-swap-works.md +1 -1
  851. package/dist/serve/site-ui/docs/get-started/node-host/index.html +1 -0
  852. package/dist/serve/site-ui/docs/get-started/node-host.md +2 -0
  853. package/dist/serve/site-ui/docs/index.json +45 -5
  854. package/dist/serve/site-ui/docs/messaging-compat/index.html +2 -2
  855. package/dist/serve/site-ui/docs/messaging-compat.md +2 -2
  856. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +3 -1
  857. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api.md +2 -0
  858. package/dist/serve/site-ui/docs/pyric-app-check-reference-api/index.html +11 -3
  859. package/dist/serve/site-ui/docs/pyric-app-check-reference-api.md +13 -3
  860. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  861. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api.md +1 -1
  862. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -0
  863. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api.md +1 -0
  864. package/dist/serve/site-ui/docs/pyric-cli-register-client-firestore-reference-api/index.html +1 -1
  865. package/dist/serve/site-ui/docs/pyric-cli-register-client-firestore-reference-api.md +1 -1
  866. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +17 -9
  867. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api.md +13 -11
  868. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +8 -4
  869. package/dist/serve/site-ui/docs/pyric-database-reference-api.md +9 -4
  870. package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +15 -4
  871. package/dist/serve/site-ui/docs/pyric-rules-reference-api.md +21 -4
  872. package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +7 -1
  873. package/dist/serve/site-ui/docs/pyric-storage-reference-api.md +1 -0
  874. package/dist/serve/site-ui/docs/reference/cli/index.html +4 -3
  875. package/dist/serve/site-ui/docs/reference/cli.md +5 -3
  876. package/dist/serve/site-ui/docs/rules-compat/index.html +150 -49
  877. package/dist/serve/site-ui/docs/rules-compat.md +149 -51
  878. package/dist/serve/site-ui/docs/storage-compat/index.html +20 -20
  879. package/dist/serve/site-ui/docs/storage-compat.md +20 -20
  880. package/dist/serve/site-ui/docs/tutorial/index.html +2 -1
  881. package/dist/serve/site-ui/docs/tutorial.md +2 -1
  882. package/dist/serve/site-ui/examples/chess/index.html +1 -1
  883. package/dist/serve/site-ui/firestore/index.html +1 -1
  884. package/dist/serve/site-ui/rtdb/index.html +1 -1
  885. package/dist/serve/site-ui/settings/index.html +1 -1
  886. package/dist/serve/site-ui/storage/index.html +1 -1
  887. package/dist/serve/site-ui/studio/index.html +1 -1
  888. package/dist/serve/site-ui/traffic/index.html +1 -1
  889. package/dist/serve/vite-ai-config.d.ts +8 -0
  890. package/dist/serve/vite-ai-config.d.ts.map +1 -1
  891. package/dist/serve/vite-ai-config.js +16 -1
  892. package/dist/serve/vite-ai-config.js.map +1 -1
  893. package/dist/serve/vite-functions-development.d.ts +3 -3
  894. package/dist/serve/vite-functions-development.d.ts.map +1 -1
  895. package/dist/serve/vite-functions-development.js +1 -1
  896. package/dist/serve/vite-functions-development.js.map +1 -1
  897. package/dist/serve/vite-generation-bridge.d.ts +2 -2
  898. package/dist/serve/vite-generation-bridge.d.ts.map +1 -1
  899. package/dist/serve/vite-generation-functions.d.ts +3 -3
  900. package/dist/serve/vite-generation-functions.d.ts.map +1 -1
  901. package/dist/serve/vite-generation-functions.js +1 -1
  902. package/dist/serve/vite-generation-functions.js.map +1 -1
  903. package/dist/serve/vite-generation-middleware.d.ts +1 -1
  904. package/dist/serve/vite-generation-middleware.d.ts.map +1 -1
  905. package/dist/serve/vite-generation-middleware.js +36 -1
  906. package/dist/serve/vite-generation-middleware.js.map +1 -1
  907. package/dist/serve/vite-module-swap.d.ts.map +1 -1
  908. package/dist/serve/vite-module-swap.js +8 -0
  909. package/dist/serve/vite-module-swap.js.map +1 -1
  910. package/dist/serve/vite-page-runtime.d.ts.map +1 -1
  911. package/dist/serve/vite-page-runtime.js +7 -1
  912. package/dist/serve/vite-page-runtime.js.map +1 -1
  913. package/dist/serve/vite-rules-source.d.ts +1 -1
  914. package/dist/serve/vite-rules-source.d.ts.map +1 -1
  915. package/dist/serve/vite-rules-source.js +2 -4
  916. package/dist/serve/vite-rules-source.js.map +1 -1
  917. package/dist/serve/vite-sandbox-generation.d.ts +2 -2
  918. package/dist/serve/vite-sandbox-generation.d.ts.map +1 -1
  919. package/dist/serve/vite-sandbox-generation.js +2 -2
  920. package/dist/serve/vite-sandbox-generation.js.map +1 -1
  921. package/dist/serve/worker/client/auth.d.ts +29 -5
  922. package/dist/serve/worker/client/auth.d.ts.map +1 -1
  923. package/dist/serve/worker/client/auth.js +61 -11
  924. package/dist/serve/worker/client/auth.js.map +1 -1
  925. package/dist/serve/worker/client/clock.d.ts +0 -16
  926. package/dist/serve/worker/client/clock.d.ts.map +1 -1
  927. package/dist/serve/worker/client/clock.js +23 -10
  928. package/dist/serve/worker/client/clock.js.map +1 -1
  929. package/dist/serve/worker/client/firestore-reads.d.ts +12 -5
  930. package/dist/serve/worker/client/firestore-reads.d.ts.map +1 -1
  931. package/dist/serve/worker/client/firestore-reads.js +47 -16
  932. package/dist/serve/worker/client/firestore-reads.js.map +1 -1
  933. package/dist/serve/worker/client/firestore-refs.d.ts.map +1 -1
  934. package/dist/serve/worker/client/firestore-refs.js +4 -14
  935. package/dist/serve/worker/client/firestore-refs.js.map +1 -1
  936. package/dist/serve/worker/client/rtdb-connection-lifecycle.d.ts.map +1 -1
  937. package/dist/serve/worker/client/rtdb-connection-lifecycle.js +5 -0
  938. package/dist/serve/worker/client/rtdb-connection-lifecycle.js.map +1 -1
  939. package/dist/serve/worker/client/rtdb-snapshots.d.ts +7 -0
  940. package/dist/serve/worker/client/rtdb-snapshots.d.ts.map +1 -1
  941. package/dist/serve/worker/client/rtdb-snapshots.js +25 -1
  942. package/dist/serve/worker/client/rtdb-snapshots.js.map +1 -1
  943. package/dist/serve/worker/client/rtdb-value-validation.d.ts +21 -0
  944. package/dist/serve/worker/client/rtdb-value-validation.d.ts.map +1 -0
  945. package/dist/serve/worker/client/rtdb-value-validation.js +183 -0
  946. package/dist/serve/worker/client/rtdb-value-validation.js.map +1 -0
  947. package/dist/serve/worker/client/rtdb-writes.d.ts.map +1 -1
  948. package/dist/serve/worker/client/rtdb-writes.js +7 -0
  949. package/dist/serve/worker/client/rtdb-writes.js.map +1 -1
  950. package/dist/serve/worker/client/snapshots.d.ts +2 -0
  951. package/dist/serve/worker/client/snapshots.d.ts.map +1 -1
  952. package/dist/serve/worker/client/snapshots.js +13 -7
  953. package/dist/serve/worker/client/snapshots.js.map +1 -1
  954. package/dist/serve/worker/client/websocket-connection.d.ts +6 -0
  955. package/dist/serve/worker/client/websocket-connection.d.ts.map +1 -1
  956. package/dist/serve/worker/client/websocket-connection.js +32 -3
  957. package/dist/serve/worker/client/websocket-connection.js.map +1 -1
  958. package/dist/serve/worker/host/auth-credential-sign-in.d.ts +33 -0
  959. package/dist/serve/worker/host/auth-credential-sign-in.d.ts.map +1 -0
  960. package/dist/serve/worker/host/auth-credential-sign-in.js +70 -0
  961. package/dist/serve/worker/host/auth-credential-sign-in.js.map +1 -0
  962. package/dist/serve/worker/host/auth-reauthentication.js +3 -3
  963. package/dist/serve/worker/host/auth-reauthentication.js.map +1 -1
  964. package/dist/serve/worker/host/rules.d.ts +15 -1
  965. package/dist/serve/worker/host/rules.d.ts.map +1 -1
  966. package/dist/serve/worker/host/rules.js +43 -34
  967. package/dist/serve/worker/host/rules.js.map +1 -1
  968. package/dist/serve/worker/host/staged-sign-in-results.d.ts +24 -0
  969. package/dist/serve/worker/host/staged-sign-in-results.d.ts.map +1 -0
  970. package/dist/serve/worker/host/staged-sign-in-results.js +40 -0
  971. package/dist/serve/worker/host/staged-sign-in-results.js.map +1 -0
  972. package/dist/serve/worker/host/storage.d.ts.map +1 -1
  973. package/dist/serve/worker/host/storage.js +20 -12
  974. package/dist/serve/worker/host/storage.js.map +1 -1
  975. package/dist/serve/worker/host/subscriptions.d.ts.map +1 -1
  976. package/dist/serve/worker/host/subscriptions.js +6 -2
  977. package/dist/serve/worker/host/subscriptions.js.map +1 -1
  978. package/dist/serve/worker/host-auth.d.ts +3 -0
  979. package/dist/serve/worker/host-auth.d.ts.map +1 -1
  980. package/dist/serve/worker/host-auth.js +32 -13
  981. package/dist/serve/worker/host-auth.js.map +1 -1
  982. package/dist/serve/worker/inbound-validation/operation-arguments.d.ts.map +1 -1
  983. package/dist/serve/worker/inbound-validation/operation-arguments.js +27 -14
  984. package/dist/serve/worker/inbound-validation/operation-arguments.js.map +1 -1
  985. package/dist/serve/worker/operation-persistence.d.ts +1 -0
  986. package/dist/serve/worker/operation-persistence.d.ts.map +1 -1
  987. package/dist/serve/worker/operation-persistence.js +1 -0
  988. package/dist/serve/worker/operation-persistence.js.map +1 -1
  989. package/dist/serve/worker/protocol.d.ts +9 -1
  990. package/dist/serve/worker/protocol.d.ts.map +1 -1
  991. package/dist/serve/worker/protocol.js.map +1 -1
  992. package/dist/serve/worker/rtdb-value-equality.d.ts.map +1 -1
  993. package/dist/serve/worker/rtdb-value-equality.js +3 -1
  994. package/dist/serve/worker/rtdb-value-equality.js.map +1 -1
  995. package/dist/serve/worker/serve-init.d.ts.map +1 -1
  996. package/dist/serve/worker/serve-init.js +3 -9
  997. package/dist/serve/worker/serve-init.js.map +1 -1
  998. package/dist/serve/worker-build-lock.d.ts +23 -0
  999. package/dist/serve/worker-build-lock.d.ts.map +1 -0
  1000. package/dist/serve/worker-build-lock.js +179 -0
  1001. package/dist/serve/worker-build-lock.js.map +1 -0
  1002. package/dist/serve/worker-bundle-cache.d.ts +17 -0
  1003. package/dist/serve/worker-bundle-cache.d.ts.map +1 -0
  1004. package/dist/serve/worker-bundle-cache.js +89 -0
  1005. package/dist/serve/worker-bundle-cache.js.map +1 -0
  1006. package/dist/verify/cases.js +7 -3
  1007. package/dist/verify/cases.js.map +1 -1
  1008. package/dist/verify/index.d.ts.map +1 -1
  1009. package/dist/verify/index.js +11 -5
  1010. package/dist/verify/index.js.map +1 -1
  1011. package/package.json +10 -4
  1012. package/src/assurance/.generated/conformance-verdicts.ts +107 -40
  1013. package/src/assurance/capabilities.ts +11 -15
  1014. package/src/bounded-request.ts +66 -7
  1015. package/src/bridge/client/bridge-url.ts +5 -1
  1016. package/src/bridge/client/bridge.ts +19 -3
  1017. package/src/bridge/frame-output.ts +45 -0
  1018. package/src/bridge/protocol.ts +13 -0
  1019. package/src/bridge/server/in-process.ts +57 -17
  1020. package/src/bridge/server/peer.ts +11 -0
  1021. package/src/bridge/server/standalone.ts +29 -107
  1022. package/src/bridge/surface/arguments/sandbox.ts +2 -69
  1023. package/src/bridge/surface/arguments/seed.ts +78 -0
  1024. package/src/bridge/surface/context.ts +26 -37
  1025. package/src/bridge/surface/database-instance-catalog.ts +4 -32
  1026. package/src/bridge/surface/database-instance-project.ts +40 -0
  1027. package/src/bridge/surface/database-instance.ts +4 -4
  1028. package/src/bridge/surface/functions-runtime.ts +5 -5
  1029. package/src/bridge/surface/held-identity.ts +4 -4
  1030. package/src/bridge/surface/manifest.sandbox.generated.ts +137 -0
  1031. package/src/bridge/surface/method-types.ts +61 -7
  1032. package/src/bridge/surface/methods/ai_logic/clearScripts.ts +2 -1
  1033. package/src/bridge/surface/methods/ai_logic/script.ts +2 -1
  1034. package/src/bridge/surface/methods/ai_logic/scripts.ts +2 -1
  1035. package/src/bridge/surface/methods/ai_logic/status.ts +1 -0
  1036. package/src/bridge/surface/methods/assurance/attach.ts +1 -0
  1037. package/src/bridge/surface/methods/assurance/canIUse.ts +1 -0
  1038. package/src/bridge/surface/methods/assurance/define.ts +1 -0
  1039. package/src/bridge/surface/methods/assurance/export.ts +1 -0
  1040. package/src/bridge/surface/methods/assurance/inspect.ts +1 -0
  1041. package/src/bridge/surface/methods/assurance/map.ts +1 -0
  1042. package/src/bridge/surface/methods/assurance/minimize.ts +1 -0
  1043. package/src/bridge/surface/methods/assurance/propose.ts +1 -0
  1044. package/src/bridge/surface/methods/assurance/replaySession.ts +1 -0
  1045. package/src/bridge/surface/methods/assurance/run.ts +1 -0
  1046. package/src/bridge/surface/methods/assurance/start.ts +1 -0
  1047. package/src/bridge/surface/methods/assurance/testRulesHosted.ts +1 -0
  1048. package/src/bridge/surface/methods/assurance/verify.ts +1 -0
  1049. package/src/bridge/surface/methods/assurance/verifyCases.ts +1 -0
  1050. package/src/bridge/surface/methods/auth/actAsAdmin.ts +1 -0
  1051. package/src/bridge/surface/methods/auth/actAsAnonymous.ts +1 -0
  1052. package/src/bridge/surface/methods/auth/createCustomToken.ts +1 -0
  1053. package/src/bridge/surface/methods/auth/createUser.ts +2 -1
  1054. package/src/bridge/surface/methods/auth/deleteUser.ts +2 -1
  1055. package/src/bridge/surface/methods/auth/getUser.ts +2 -1
  1056. package/src/bridge/surface/methods/auth/getUserByEmail.ts +2 -1
  1057. package/src/bridge/surface/methods/auth/impersonate.ts +1 -0
  1058. package/src/bridge/surface/methods/auth/importUsers.ts +3 -2
  1059. package/src/bridge/surface/methods/auth/listUsers.ts +2 -1
  1060. package/src/bridge/surface/methods/auth/sessions.ts +1 -0
  1061. package/src/bridge/surface/methods/auth/setCustomUserClaims.ts +2 -1
  1062. package/src/bridge/surface/methods/auth/signInAnonymously.ts +1 -0
  1063. package/src/bridge/surface/methods/auth/signInWithCredential.ts +1 -0
  1064. package/src/bridge/surface/methods/auth/signInWithCustomToken.ts +1 -0
  1065. package/src/bridge/surface/methods/auth/signInWithEmailAndPassword.ts +1 -0
  1066. package/src/bridge/surface/methods/auth/signOut.ts +1 -0
  1067. package/src/bridge/surface/methods/auth/takeAuthMail.ts +1 -0
  1068. package/src/bridge/surface/methods/auth/updateUser.ts +2 -1
  1069. package/src/bridge/surface/methods/auth/useAppSession.ts +1 -0
  1070. package/src/bridge/surface/methods/auth/whoami.ts +1 -0
  1071. package/src/bridge/surface/methods/database/crawl.ts +1 -0
  1072. package/src/bridge/surface/methods/database/get.ts +1 -0
  1073. package/src/bridge/surface/methods/database/push.ts +1 -0
  1074. package/src/bridge/surface/methods/database/query.ts +1 -0
  1075. package/src/bridge/surface/methods/database/remove.ts +1 -0
  1076. package/src/bridge/surface/methods/database/set.ts +1 -0
  1077. package/src/bridge/surface/methods/database/update.ts +1 -0
  1078. package/src/bridge/surface/methods/firestore/addDoc.ts +2 -1
  1079. package/src/bridge/surface/methods/firestore/deleteDoc.ts +2 -1
  1080. package/src/bridge/surface/methods/firestore/discoverPaths.ts +1 -0
  1081. package/src/bridge/surface/methods/firestore/extractIndexes.ts +1 -0
  1082. package/src/bridge/surface/methods/firestore/findCollectionGroup.ts +1 -0
  1083. package/src/bridge/surface/methods/firestore/getAggregateFromServer.ts +1 -0
  1084. package/src/bridge/surface/methods/firestore/getCountFromServer.ts +1 -0
  1085. package/src/bridge/surface/methods/firestore/getDoc.ts +2 -1
  1086. package/src/bridge/surface/methods/firestore/getDocs.ts +2 -1
  1087. package/src/bridge/surface/methods/firestore/setDoc.ts +2 -1
  1088. package/src/bridge/surface/methods/firestore/updateDoc.ts +2 -1
  1089. package/src/bridge/surface/methods/firestore/writeBatch.ts +2 -1
  1090. package/src/bridge/surface/methods/firestore/writeIndexes.ts +1 -0
  1091. package/src/bridge/surface/methods/functions/executions.ts +2 -1
  1092. package/src/bridge/surface/methods/functions/fire.ts +7 -6
  1093. package/src/bridge/surface/methods/functions/listTriggers.ts +1 -0
  1094. package/src/bridge/surface/methods/messaging/deliveries.ts +1 -0
  1095. package/src/bridge/surface/methods/messaging/send.ts +2 -1
  1096. package/src/bridge/surface/methods/messaging/subscribeToTopic.ts +1 -0
  1097. package/src/bridge/surface/methods/messaging/tokens.ts +1 -0
  1098. package/src/bridge/surface/methods/messaging/unsubscribeFromTopic.ts +1 -0
  1099. package/src/bridge/surface/methods/registry.ts +2 -12
  1100. package/src/bridge/surface/methods/rules/explainDenial.ts +1 -0
  1101. package/src/bridge/surface/methods/rules/getStdlib.ts +1 -0
  1102. package/src/bridge/surface/methods/rules/lint.ts +1 -0
  1103. package/src/bridge/surface/methods/rules/listStdlib.ts +1 -0
  1104. package/src/bridge/surface/methods/rules/set.ts +1 -0
  1105. package/src/bridge/surface/methods/rules/simulate.ts +1 -0
  1106. package/src/bridge/surface/methods/sandbox/activity.ts +2 -1
  1107. package/src/bridge/surface/methods/sandbox/advanceClock.ts +1 -0
  1108. package/src/bridge/surface/methods/sandbox/apply.ts +1 -0
  1109. package/src/bridge/surface/methods/sandbox/checkpoint.ts +1 -0
  1110. package/src/bridge/surface/methods/sandbox/deleteCapture.ts +1 -1
  1111. package/src/bridge/surface/methods/sandbox/deleteCheckpoint.ts +1 -0
  1112. package/src/bridge/surface/methods/sandbox/diff.ts +1 -0
  1113. package/src/bridge/surface/methods/sandbox/discard.ts +1 -0
  1114. package/src/bridge/surface/methods/sandbox/events.ts +2 -1
  1115. package/src/bridge/surface/methods/sandbox/exportFixture.ts +1 -0
  1116. package/src/bridge/surface/methods/sandbox/fork.ts +1 -0
  1117. package/src/bridge/surface/methods/sandbox/inspect.ts +2 -1
  1118. package/src/bridge/surface/methods/sandbox/listBranches.ts +1 -0
  1119. package/src/bridge/surface/methods/sandbox/listCaptures.ts +1 -1
  1120. package/src/bridge/surface/methods/sandbox/listCheckpoints.ts +1 -0
  1121. package/src/bridge/surface/methods/sandbox/listeners.ts +1 -0
  1122. package/src/bridge/surface/methods/sandbox/openCapture.ts +1 -1
  1123. package/src/bridge/surface/methods/sandbox/promote.ts +1 -0
  1124. package/src/bridge/surface/methods/sandbox/renameCapture.ts +1 -1
  1125. package/src/bridge/surface/methods/sandbox/reset.ts +3 -2
  1126. package/src/bridge/surface/methods/sandbox/resetClock.ts +1 -0
  1127. package/src/bridge/surface/methods/sandbox/restore.ts +1 -0
  1128. package/src/bridge/surface/methods/sandbox/saveCapture.ts +1 -1
  1129. package/src/bridge/surface/methods/sandbox/seed.ts +3 -2
  1130. package/src/bridge/surface/methods/sandbox/seedFromFixture.ts +1 -0
  1131. package/src/bridge/surface/methods/sandbox/setClock.ts +1 -0
  1132. package/src/bridge/surface/methods/sandbox-registry.ts +24 -0
  1133. package/src/bridge/surface/methods/storage/deleteObject.ts +1 -0
  1134. package/src/bridge/surface/methods/storage/getBytes.ts +1 -0
  1135. package/src/bridge/surface/methods/storage/getDownloadURL.ts +1 -0
  1136. package/src/bridge/surface/methods/storage/getMetadata.ts +1 -0
  1137. package/src/bridge/surface/methods/storage/listAll.ts +1 -0
  1138. package/src/bridge/surface/methods/storage/provision.ts +1 -0
  1139. package/src/bridge/surface/methods/storage/setCrossServiceIam.ts +1 -0
  1140. package/src/bridge/surface/methods/storage/status.ts +1 -0
  1141. package/src/bridge/surface/methods/storage/updateMetadata.ts +1 -0
  1142. package/src/bridge/surface/methods/storage/uploadBytes.ts +1 -0
  1143. package/src/bridge/surface/request-instant.ts +2 -2
  1144. package/src/bridge/surface/rules-engines/database.ts +1 -2
  1145. package/src/bridge/surface/rules-engines/storage-request-resource.ts +275 -0
  1146. package/src/bridge/surface/rules-engines/storage.ts +54 -81
  1147. package/src/bridge/surface/sandbox-context.ts +49 -0
  1148. package/src/bridge/surface/service-handles.ts +13 -9
  1149. package/src/bridge/surface/sign-in.ts +3 -3
  1150. package/src/bridge/surface/storage-rules.ts +2 -14
  1151. package/src/bridge/surface/stored-identity.ts +3 -3
  1152. package/src/bridge/surface/types.ts +30 -8
  1153. package/src/cli/firebase-json.ts +45 -7
  1154. package/src/cli/firestore-indexes.ts +2 -1
  1155. package/src/cli/index.ts +46 -11
  1156. package/src/cli/public-dir-hint.ts +35 -0
  1157. package/src/cli/run.ts +35 -7
  1158. package/src/cli/sandbox-runner.ts +10 -2
  1159. package/src/cli/serve-diagnostics.ts +12 -1
  1160. package/src/cli/serve.ts +27 -26
  1161. package/src/cli/service-commands.test.ts +7 -0
  1162. package/src/cli/snapshot.ts +15 -6
  1163. package/src/cli/surface-method-runner.ts +1 -1
  1164. package/src/cli/verify.ts +11 -1
  1165. package/src/conformance/.generated/can-i-use-browser.ts +22 -3
  1166. package/src/conformance/.generated/can-i-use.ts +1 -1
  1167. package/src/conformance/.generated/conformance-docs.ts +1 -1
  1168. package/src/conformance/.generated/served-availability.ts +1 -1
  1169. package/src/discover/merge.ts +12 -3
  1170. package/src/functions/child-protocol.ts +59 -0
  1171. package/src/functions/child.ts +107 -0
  1172. package/src/{functions-rtdb → functions}/development-runtime.ts +13 -14
  1173. package/src/functions/endpoints.ts +80 -0
  1174. package/src/{functions-rtdb → functions}/project.ts +2 -2
  1175. package/src/functions/rtdb/child-runtime.ts +139 -0
  1176. package/src/{functions-rtdb → functions/rtdb}/discovery.ts +9 -43
  1177. package/src/{functions-rtdb → functions/rtdb}/remote-delivery.ts +1 -1
  1178. package/src/functions/spawn.ts +212 -0
  1179. package/src/functions/unsupported.ts +42 -0
  1180. package/src/google-endpoints.ts +74 -3
  1181. package/src/next/bridge-import-loader.ts +56 -0
  1182. package/src/next/bridge-imports.ts +108 -0
  1183. package/src/next/client-aliases.ts +14 -27
  1184. package/src/next/guard.ts +33 -11
  1185. package/src/next/turbopack-config.ts +26 -0
  1186. package/src/next/webpack-config.ts +26 -0
  1187. package/src/next/with-pyric.ts +26 -0
  1188. package/src/register/activation.ts +26 -0
  1189. package/src/register/app-bridge-admin-app-check.ts +3 -1
  1190. package/src/register/child-process-guard.ts +189 -0
  1191. package/src/register/client/bootstrap.ts +7 -1
  1192. package/src/register/connect-prototypes.ts +12 -0
  1193. package/src/register/hooks.ts +56 -3
  1194. package/src/register/index.ts +92 -20
  1195. package/src/register/mapping.ts +57 -3
  1196. package/src/register/net-guard.ts +149 -39
  1197. package/src/register/package-identity.ts +98 -0
  1198. package/src/register/swap-or-stop.ts +194 -0
  1199. package/src/register/worker-guard.ts +90 -0
  1200. package/src/remote/resolve-host.ts +14 -2
  1201. package/src/serve/ai-proxy.ts +36 -8
  1202. package/src/serve/app-ports.ts +119 -0
  1203. package/src/serve/bridge-mount.ts +36 -8
  1204. package/src/serve/bundler.ts +87 -29
  1205. package/src/serve/discovery.ts +244 -67
  1206. package/src/serve/entries/auth.ts +22 -1
  1207. package/src/serve/entries/firestore-surface.ts +1 -0
  1208. package/src/serve/entries/init-payload.ts +28 -5
  1209. package/src/serve/entries/moved-host.ts +28 -0
  1210. package/src/serve/entries/runtime-origin.ts +6 -0
  1211. package/src/serve/entries/unsupported/firestore.ts +0 -1
  1212. package/src/serve/entries/worker-runtime.ts +19 -6
  1213. package/src/serve/firebase-module-swap.ts +98 -15
  1214. package/src/serve/gemini-proxy.ts +2 -2
  1215. package/src/serve/hosted/runtime.ts +10 -2
  1216. package/src/serve/namespace.ts +41 -29
  1217. package/src/serve/repro/compare.ts +9 -1
  1218. package/src/serve/rules-fixture-check.ts +34 -9
  1219. package/src/serve/rules.ts +104 -20
  1220. package/src/serve/sandbox-session.ts +11 -3
  1221. package/src/serve/server.ts +29 -2
  1222. package/src/serve/vite-ai-config.ts +19 -1
  1223. package/src/serve/vite-functions-development.ts +3 -3
  1224. package/src/serve/vite-generation-bridge.ts +2 -2
  1225. package/src/serve/vite-generation-functions.ts +5 -5
  1226. package/src/serve/vite-generation-middleware.ts +38 -2
  1227. package/src/serve/vite-module-swap.ts +8 -0
  1228. package/src/serve/vite-page-runtime.ts +6 -0
  1229. package/src/serve/vite-rules-source.ts +2 -5
  1230. package/src/serve/vite-sandbox-generation.ts +5 -5
  1231. package/src/serve/worker/__tests__/auth-credential-sign-in.test.ts +343 -0
  1232. package/src/serve/worker/__tests__/auth-m2-parity.test.ts +45 -1
  1233. package/src/serve/worker/__tests__/staged-sign-in-results.test.ts +139 -0
  1234. package/src/serve/worker/client/auth.ts +97 -21
  1235. package/src/serve/worker/client/clock.ts +10 -12
  1236. package/src/serve/worker/client/firestore-reads.ts +70 -21
  1237. package/src/serve/worker/client/firestore-refs.ts +4 -14
  1238. package/src/serve/worker/client/rtdb-connection-lifecycle.ts +5 -0
  1239. package/src/serve/worker/client/rtdb-snapshots.ts +24 -2
  1240. package/src/serve/worker/client/rtdb-value-validation.ts +198 -0
  1241. package/src/serve/worker/client/rtdb-writes.ts +7 -0
  1242. package/src/serve/worker/client/snapshots.ts +15 -6
  1243. package/src/serve/worker/client/websocket-connection.ts +39 -3
  1244. package/src/serve/worker/host/auth-credential-sign-in.ts +97 -0
  1245. package/src/serve/worker/host/auth-reauthentication.ts +3 -3
  1246. package/src/serve/worker/host/rules.ts +53 -34
  1247. package/src/serve/worker/host/staged-sign-in-results.ts +53 -0
  1248. package/src/serve/worker/host/storage.ts +26 -11
  1249. package/src/serve/worker/host/subscriptions.ts +7 -4
  1250. package/src/serve/worker/host-auth.ts +33 -15
  1251. package/src/serve/worker/inbound-validation/operation-arguments.ts +27 -14
  1252. package/src/serve/worker/operation-persistence.ts +1 -0
  1253. package/src/serve/worker/protocol.ts +7 -1
  1254. package/src/serve/worker/rtdb-value-equality.ts +3 -1
  1255. package/src/serve/worker/serve-init.ts +3 -9
  1256. package/src/serve/worker-build-lock.ts +207 -0
  1257. package/src/serve/worker-bundle-cache.ts +90 -0
  1258. package/src/verify/cases.ts +6 -3
  1259. package/src/verify/index.ts +16 -4
  1260. package/dist/functions-rtdb/child.d.ts.map +0 -1
  1261. package/dist/functions-rtdb/child.js +0 -386
  1262. package/dist/functions-rtdb/child.js.map +0 -1
  1263. package/dist/functions-rtdb/delivery.d.ts.map +0 -1
  1264. package/dist/functions-rtdb/delivery.js.map +0 -1
  1265. package/dist/functions-rtdb/development-runtime.d.ts.map +0 -1
  1266. package/dist/functions-rtdb/development-runtime.js.map +0 -1
  1267. package/dist/functions-rtdb/discovery.d.ts.map +0 -1
  1268. package/dist/functions-rtdb/discovery.js.map +0 -1
  1269. package/dist/functions-rtdb/event.d.ts.map +0 -1
  1270. package/dist/functions-rtdb/event.js.map +0 -1
  1271. package/dist/functions-rtdb/events.d.ts.map +0 -1
  1272. package/dist/functions-rtdb/events.js.map +0 -1
  1273. package/dist/functions-rtdb/execution-log.d.ts.map +0 -1
  1274. package/dist/functions-rtdb/execution-log.js.map +0 -1
  1275. package/dist/functions-rtdb/execution.d.ts.map +0 -1
  1276. package/dist/functions-rtdb/execution.js.map +0 -1
  1277. package/dist/functions-rtdb/in-memory-delivery.d.ts.map +0 -1
  1278. package/dist/functions-rtdb/in-memory-delivery.js.map +0 -1
  1279. package/dist/functions-rtdb/module-loader.d.ts.map +0 -1
  1280. package/dist/functions-rtdb/module-loader.js.map +0 -1
  1281. package/dist/functions-rtdb/project.d.ts +0 -7
  1282. package/dist/functions-rtdb/project.d.ts.map +0 -1
  1283. package/dist/functions-rtdb/project.js.map +0 -1
  1284. package/dist/functions-rtdb/projection.d.ts.map +0 -1
  1285. package/dist/functions-rtdb/projection.js.map +0 -1
  1286. package/dist/functions-rtdb/reference-pattern.d.ts.map +0 -1
  1287. package/dist/functions-rtdb/reference-pattern.js.map +0 -1
  1288. package/dist/functions-rtdb/remote-delivery.d.ts.map +0 -1
  1289. package/dist/functions-rtdb/remote-delivery.js.map +0 -1
  1290. package/dist/serve/gemini-error-redaction.d.ts +0 -6
  1291. package/dist/serve/gemini-error-redaction.d.ts.map +0 -1
  1292. package/dist/serve/gemini-error-redaction.js +0 -61
  1293. package/dist/serve/gemini-error-redaction.js.map +0 -1
  1294. package/dist/serve/site-ui/_astro/app.C--T2qDK.js +0 -151
  1295. package/dist/serve/site-ui/_astro/app.DqyhRyrU.js +0 -1
  1296. package/dist/serve/site-ui/_astro/sandbox-controls.Bv6lfpIe.js +0 -1725
  1297. package/dist/serve/site-ui/_astro/writes.Bg0YEEA7.js +0 -1
  1298. package/src/functions-rtdb/child.ts +0 -512
  1299. package/src/serve/gemini-error-redaction.ts +0 -60
  1300. /package/dist/{functions-rtdb → functions}/events.d.ts +0 -0
  1301. /package/dist/{functions-rtdb → functions}/events.js +0 -0
  1302. /package/dist/{functions-rtdb → functions}/execution-log.d.ts +0 -0
  1303. /package/dist/{functions-rtdb → functions}/execution-log.js +0 -0
  1304. /package/dist/{functions-rtdb → functions}/module-loader.d.ts +0 -0
  1305. /package/dist/{functions-rtdb → functions}/module-loader.js +0 -0
  1306. /package/dist/{functions-rtdb → functions/rtdb}/delivery.d.ts +0 -0
  1307. /package/dist/{functions-rtdb → functions/rtdb}/delivery.js +0 -0
  1308. /package/dist/{functions-rtdb → functions/rtdb}/event.d.ts +0 -0
  1309. /package/dist/{functions-rtdb → functions/rtdb}/event.js +0 -0
  1310. /package/dist/{functions-rtdb → functions/rtdb}/execution.d.ts +0 -0
  1311. /package/dist/{functions-rtdb → functions/rtdb}/execution.js +0 -0
  1312. /package/dist/{functions-rtdb → functions/rtdb}/in-memory-delivery.d.ts +0 -0
  1313. /package/dist/{functions-rtdb → functions/rtdb}/in-memory-delivery.js +0 -0
  1314. /package/dist/{functions-rtdb → functions/rtdb}/projection.d.ts +0 -0
  1315. /package/dist/{functions-rtdb → functions/rtdb}/projection.js +0 -0
  1316. /package/dist/{functions-rtdb → functions/rtdb}/reference-pattern.d.ts +0 -0
  1317. /package/dist/{functions-rtdb → functions/rtdb}/reference-pattern.js +0 -0
  1318. /package/dist/{functions-rtdb → functions/rtdb}/remote-delivery.js +0 -0
  1319. /package/src/{functions-rtdb → functions}/events.ts +0 -0
  1320. /package/src/{functions-rtdb → functions}/execution-log.ts +0 -0
  1321. /package/src/{functions-rtdb → functions}/module-loader.ts +0 -0
  1322. /package/src/{functions-rtdb → functions/rtdb}/delivery.ts +0 -0
  1323. /package/src/{functions-rtdb → functions/rtdb}/event.ts +0 -0
  1324. /package/src/{functions-rtdb → functions/rtdb}/execution.ts +0 -0
  1325. /package/src/{functions-rtdb → functions/rtdb}/in-memory-delivery.ts +0 -0
  1326. /package/src/{functions-rtdb → functions/rtdb}/projection.ts +0 -0
  1327. /package/src/{functions-rtdb → functions/rtdb}/reference-pattern.ts +0 -0
@@ -0,0 +1,151 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/RulesCodeEditor.D-eQLCvu.js","_astro/sandbox-controls.DI8MTU3L.js","_astro/index.DBy5LfQW.js","_astro/seed.BvtbLu-q.js","_astro/writes.D8gcuovU.js","_astro/index.DNyk7q8W.js"])))=>i.map(i=>d[i]);
2
+ import{d as dw,r as jh,e as fw,M as to,g as hw,f as pw,h as mw,k as Al,N as Ol,l as yw,m as gw,n as bw,o as ww,p as pc,F as G,q as dt,t as Ln,u as De,v as Ch,w as vw,x as xw,y as Rn,z as vn,A as Rh,B as ps,C as Ee,D as Ws,E as Ms,G as Ls,H as zs,I as Pt,J as Ei,S as Nh,K as Yr,L as Ih,O as Hs,P as Ah,Q as _w,R as Sw,T as kw,U as Ew,V as Oh,W as Te,X as ji,Y as jw,Z as $h,_ as Cw,$ as Rw,a0 as Jo,a1 as it,a2 as Yo,a3 as Nw,a4 as Bt,a5 as Er,a6 as Iw,a7 as Aw,a8 as Ow,a9 as Qr,aa as Ph,ab as $w,ac as Pe,ad as Dh,ae as Pw,af as Dw,ag as Tw,ah as Mw,ai as Lw,aj as Th,ak as Uw,al as Bw,am as Fw,an as qw,ao as Vw,ap as Ww,aq as zw,ar as Hw,as as ms,at as Mh,au as $l,av as Lh,aw as Kw,ax as Gw,ay as Jw,az as Pl,aA as Yw,aB as Qw,aC as Xw,aD as Zw,aE as ev,aF as Uh,aG as tv,aH as nv,aI as rv,aJ as sv,aK as Bh,aL as Fh,aM as On,aN as Xr,aO as iv,aP as ov,i as av,j as c,aQ as cv,aR as lv,aS as uv,aT as dv,aU as fv,aV as hv,aW as pv,aX as qh,aY as mv,aZ as mc,a_ as yv,a$ as gv,b0 as bv,b1 as wv,b2 as cn,b3 as jr,b4 as vv,b5 as xv,b6 as Vh,b7 as Wh,b8 as Dl,b9 as _v,ba as Sv,bb as kv,bc as Ev,bd as jv,be as Cv,bf as Rv,bg as Nv,bh as Iv,bi as Av,bj as zh,bk as Ov,bl as rn,bm as Ft,bn as $n}from"./sandbox-controls.DI8MTU3L.js";import{r as y}from"./index.DBy5LfQW.js";import{a as $v,r as Pv,b as Cr,d as tt,T as Ks,c as St,t as nn,e as Zr,f as Hh,h as Tl,j as yc,k as Kh,l as gc,u as Qo,m as Dv,n as bc,o as Un,w as Gh,p as Tv,q as Mv,v as Lv,x as Uv,y as Bv,B as Fv,C as qv,z as Vv,A as Wv,D as Xo,E as zv,F as Hv,G as Kv,Q as Gv,H as pr,s as Gs,I as Jh,J as Ml,K as Zo,L as Jv,M as Yv,N as wc,O as vc,g as Js,i as Qv}from"./writes.D8gcuovU.js";import{r as Xv}from"./index.DNyk7q8W.js";function Zv(e,t){const n=e.toLowerCase();let r=null;for(const s of t){const i=ex(n,s.toLowerCase());(r===null||i<r.d)&&(r={key:s,d:i})}return r&&r.d<=Math.max(2,Math.floor(n.length/3))?r.key:null}function ex(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;const n=new Array(t.length+1).fill(0).map((s,i)=>i),r=new Array(t.length+1).fill(0);for(let s=0;s<e.length;s++){r[0]=s+1;for(let i=0;i<t.length;i++){const o=e[s]===t[i]?0:1;r[i+1]=Math.min(r[i]+1,n[i+1]+1,n[i]+o)}for(let i=0;i<=t.length;i++)n[i]=r[i]}return r[t.length]}const sn={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},tx=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],nx={serverTimestamp:{min:0,max:0},increment:{min:1,max:1},arrayUnion:{min:1,max:1/0},arrayRemove:{min:1,max:1/0},deleteField:{min:0,max:0}};function rx(e){return tx.includes(e)}class me extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class lt extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const sx={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},ix={true:"true",false:"false",null:"null"};function ox(e){if(e.length>sn.maxExpressionLength)throw new me(`expression exceeds ${sn.maxExpressionLength}-character cap (got ${e.length})`,X(sn.maxExpressionLength));const t=[];let n=0;for(;n<e.length;){const r=n,s=e[n];if(s===" "||s===" "||s==="\r"||s===`
3
+ `){n+=1;continue}if(s==='"'||s==="'"){const{token:o,next:a}=lx(e,n,s);if(t.push(o),n=a,n<=r)throw new me("lexer stalled on string",X(r));continue}if(s>="0"&&s<="9"){const{token:o,next:a}=cx(e,n);if(t.push(o),n=a,n<=r)throw new me("lexer stalled on number",X(r));continue}if(Ci(s)){const{token:o,next:a}=ax(e,n);t.push(o),n=a;continue}if(s==="$"){const{token:o,next:a}=Ll(e,n,"$","reference");t.push(o),n=a;continue}if(s==="@"){const{token:o,next:a}=Ll(e,n,"@","sentinel");t.push(o),n=a;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:X(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:X(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:X(n)}),n+=2):(t.push({kind:"lt",pos:X(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:X(n)}),n+=2):(t.push({kind:"gt",pos:X(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new me("unexpected '&' (did you mean '&&'?)",X(n));t.push({kind:"and",pos:X(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new me("unexpected '|' (did you mean '||'?)",X(n));t.push({kind:"or",pos:X(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:X(n)}),n+=1;continue}if(s==="=")throw new me("unexpected '=' (did you mean '=='?)",X(n));const i=sx[s];if(i){t.push({kind:i,pos:X(n)}),n+=1;continue}throw new me(`unexpected character ${JSON.stringify(s)}`,X(n))}return t.push({kind:"eof",pos:X(e.length)}),t}function X(e){return{offset:e,column:e+1}}function Ci(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function Yh(e){return Ci(e)||e>="0"&&e<="9"}function ax(e,t){let n=t+1;for(;n<e.length&&Yh(e[n]);)n+=1;const r=e.slice(t,n),s=ix[r];return s?{token:{kind:s,pos:X(t)},next:n}:{token:{kind:"identifier",pos:X(t),value:r},next:n}}function Ll(e,t,n,r){const s=t+1;if(s>=e.length||!Ci(e[s]))throw new me(`expected identifier after '${n}'`,X(t));let i=s+1;for(;i<e.length&&Yh(e[i]);)i+=1;const o=e.slice(s,i);return{token:{kind:r,pos:X(t),value:o},next:i}}function cx(e,t){let n=t;const r=e[n];if(n+=1,r==="0"){if(n<e.length&&e[n]>="0"&&e[n]<="9")throw new me("leading zeros are not allowed in number literals",X(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const a=e[n+1];if(a!==void 0&&a>="0"&&a<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(a!==void 0&&Ci(a)))throw new me("expected digit after '.' in number literal",X(n))}const i=e.slice(t,n),o=Number.parseFloat(i);if(!Number.isFinite(o))throw new me(`numeric literal '${i}' is not finite`,X(t));if(!s&&!Number.isSafeInteger(o))throw new me(`integer literal '${i}' exceeds safe integer range`,X(t));return{token:{kind:"number",pos:X(t),value:o},next:n}}function lx(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:X(t),value:s},next:r+1};if(i==="\\"){const o=e[r+1];if(o===void 0)throw new me("unterminated escape sequence in string literal",X(r));switch(o){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
4
+ `;break;case"t":s+=" ";break;default:throw new me(`invalid escape sequence '\\${o}' (only \\", \\', \\\\, \\n, \\t are allowed)`,X(r))}r+=2}else{if(i===`
5
+ `||i==="\r")throw new me("unterminated string literal (newline before closing quote)",X(t));s+=i,r+=1}if(s.length>sn.maxStringLiteralLength)throw new me(`string literal exceeds ${sn.maxStringLiteralLength}-character cap`,X(t))}throw new me("unterminated string literal",X(t))}function ux(e){const t=new dx(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),px(n),n}class dx{tokens;cursor=0;constructor(t){this.tokens=t}parseExpression(){return this.parseTernary()}parseTernary(){const t=this.parseLogicalOr();if(this.peek().kind!=="question")return t;const n=this.consume(),r=this.parseExpression();this.expect("colon","expected ':' in ternary");const s=this.parseExpression();return{kind:"ternary",cond:t,whenTrue:r,whenFalse:s,pos:n.pos}}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.peek().kind==="or";){const n=this.consume(),r=this.parseLogicalAnd();t={kind:"logical",op:"||",left:t,right:r,pos:n.pos}}return t}parseLogicalAnd(){let t=this.parseComparison();for(;this.peek().kind==="and";){const n=this.consume(),r=this.parseComparison();t={kind:"logical",op:"&&",left:t,right:r,pos:n.pos}}return t}parseComparison(){let t=this.parseSum();for(;;){const n=fx(this.peek().kind);if(!n)break;const r=this.consume(),s=this.parseSum();t={kind:"binary",op:n,left:t,right:s,pos:r.pos}}return t}parseSum(){let t=this.parseProduct();for(;;){const n=this.peek().kind;if(n!=="plus"&&n!=="minus")break;const r=this.consume(),s=this.parseProduct();t={kind:"binary",op:n==="plus"?"+":"-",left:t,right:s,pos:r.pos}}return t}parseProduct(){let t=this.parseUnary();for(;;){const n=this.peek().kind;if(n!=="star"&&n!=="slash"&&n!=="percent")break;const r=this.consume(),s=this.parseUnary();t={kind:"binary",op:n==="star"?"*":n==="slash"?"/":"%",left:t,right:s,pos:r.pos}}return t}parseUnary(){const t=this.peek().kind;if(t==="minus"||t==="bang"){const n=this.consume(),r=this.parseUnary();return{kind:"unary",op:t==="minus"?"-":"!",operand:r,pos:n.pos}}return this.parsePostfix()}parsePostfix(){let t=this.parsePrimary();for(;;){const n=this.peek().kind;if(n==="dot"){const r=this.consume(),s=this.expect("identifier","expected identifier after '.'");t={kind:"fieldAccess",target:t,field:s.value,pos:r.pos}}else if(n==="lbracket"){const r=this.consume(),s=this.parseExpression();this.expect("rbracket","expected ']'"),t={kind:"indexAccess",target:t,index:s,pos:r.pos}}else break}return t}parsePrimary(){const t=this.peek();switch(t.kind){case"number":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"string":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"true":return this.consume(),{kind:"literal",value:!0,pos:t.pos};case"false":return this.consume(),{kind:"literal",value:!1,pos:t.pos};case"null":return this.consume(),{kind:"literal",value:null,pos:t.pos};case"reference":return this.consume(),{kind:"reference",alias:t.value,pos:t.pos};case"sentinel":return this.parseSentinelCall();case"lparen":{this.consume();const n=this.parseExpression();return this.expect("rparen","expected ')'"),n}case"identifier":throw new lt(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new lt("unexpected end of expression",t.pos);default:throw new lt("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!rx(n))throw new lt(`unknown sentinel '@${n}' (allowed: serverTimestamp, increment, arrayUnion, arrayRemove, deleteField)`,t.pos);this.expect("lparen",`expected '(' after sentinel '@${n}'`);const r=[];if(this.peek().kind!=="rparen")for(r.push(this.parseExpression());this.peek().kind==="comma";)this.consume(),r.push(this.parseExpression());this.expect("rparen","expected ')' after sentinel arguments");const s=nx[n];if(r.length<s.min||r.length>s.max){const i=s.max===1/0?`at least ${s.min}`:s.min===s.max?`exactly ${s.min}`:`${s.min}..${s.max}`;throw new lt(`sentinel '@${n}' expects ${i} argument(s), got ${r.length}`,t.pos)}return{kind:"sentinel",name:n,args:r,pos:t.pos}}peek(){return this.tokens[this.cursor]}consume(){const t=this.tokens[this.cursor];return this.cursor+=1,t}expect(t,n){const r=this.peek();if(r.kind!==t)throw new lt(`${n} (got ${hx(r)})`,r.pos);return this.consume()}}function fx(e){switch(e){case"eq":return"==";case"neq":return"!=";case"lt":return"<";case"lte":return"<=";case"gt":return">";case"gte":return">=";default:return null}}function hx(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function px(e){t(e);function t(n){let r=0;switch(n.kind){case"literal":case"reference":r=0;break;case"unary":r=t(n.operand);break;case"binary":case"logical":r=Math.max(t(n.left),t(n.right));break;case"ternary":r=Math.max(t(n.cond),t(n.whenTrue),t(n.whenFalse));break;case"fieldAccess":r=t(n.target);break;case"indexAccess":r=Math.max(t(n.target),t(n.index));break;case"sentinel":r=n.args.length===0?0:Math.max(...n.args.map(t));break}const s=r+1;if(s>sn.maxAstDepth)throw new lt(`expression AST exceeds depth cap of ${sn.maxAstDepth}`,n.pos);return s}}class Fe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function es(e){if(typeof e!="object"||e===null)return!1;const t=e,n=t.__type,r=Object.keys(t);switch(n){case"serverTimestamp":case"deleteField":return r.length===1;case"increment":return r.length===2&&typeof t.value=="number";case"arrayUnion":case"arrayRemove":return r.length===2&&Array.isArray(t.values);default:return!1}}function Ye(e,t){return new Fe("type-mismatch",t,e.pos)}function Ve(e,t){switch(e.kind){case"literal":return e.value;case"reference":return mx(e,t);case"sentinel":return yx(e,t);case"unary":return gx(e,t);case"binary":return bx(e,t);case"logical":return vx(e,t);case"ternary":return xx(e,t);case"fieldAccess":return _x(e,t);case"indexAccess":return Sx(e,t)}}function mx(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new Fe("unknown-reference",`unknown alias '$${e.alias}' (not in reads). Hint: aliases are case-sensitive; sentinels use '@' not '$'.`,e.pos);return t.reads[e.alias]??null}function yx(e,t){const n=e.args.map(r=>{const s=Ve(r,t);if(es(s))throw new Fe("sentinel-misuse",`sentinel '@${s.__type}' cannot be a sentinel argument`,r.pos);return s});switch(e.name){case"serverTimestamp":return{__type:"serverTimestamp"};case"deleteField":return{__type:"deleteField"};case"increment":{const r=n[0];if(typeof r!="number")throw Ye(e,`'@increment' expects a numeric argument, got ${Ne(r)}`);return Ys(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function gx(e,t){const n=Ve(e.operand,t);if(ea(n,e),e.op==="-"){if(typeof n!="number")throw Ye(e,`unary '-' expects a number, got ${Ne(n)}`);const r=-n;return Ys(r,e),r}if(typeof n!="boolean")throw Ye(e,`unary '!' expects a boolean, got ${Ne(n)}`);return!n}function bx(e,t){const n=Ve(e.left,t),r=Ve(e.right,t);switch(ea(n,e),ea(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return Ys(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Ye(e,`'+' expects (number, number) or (string, string); got (${Ne(n)}, ${Ne(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Ye(e,`'${e.op}' expects (number, number); got (${Ne(n)}, ${Ne(r)})`);let s;switch(e.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return Ys(s,e),s}case"==":return Ul(e,n,r);case"!=":return!Ul(e,n,r);case"<":case"<=":case">":case">=":return wx(e,n,r)}}function Ul(e,t,n){if(t===null||n===null)return t===n;const r=typeof t;if(r!==typeof n)return!1;if(r==="number"||r==="string"||r==="boolean")return t===n;throw Ye(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function wx(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw Ye(e,`'${e.op}' expects matching number/number or string/string operands; got (${Ne(t)}, ${Ne(n)})`);switch(e.op){case"<":return t<n;case"<=":return t<=n;case">":return t>n;case">=":return t>=n;default:throw new Error("unreachable")}}function vx(e,t){const n=Ve(e.left,t);if(typeof n!="boolean")throw Ye(e,`'${e.op}' expects boolean operands; left is ${Ne(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=Ve(e.right,t);if(typeof r!="boolean")throw Ye(e,`'${e.op}' expects boolean operands; right is ${Ne(r)}`);return r}function xx(e,t){const n=Ve(e.cond,t);if(typeof n!="boolean")throw Ye(e,`ternary condition must be boolean, got ${Ne(n)}`);return Ve(n?e.whenTrue:e.whenFalse,t)}function _x(e,t){const n=Ve(e.target,t);if(n==null)throw new Fe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||es(n))throw Ye(e,`cannot access field '${e.field}' on ${Ne(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function Sx(e,t){const n=Ve(e.target,t);if(n==null)throw new Fe("null-access","cannot index null target",e.pos);const r=Ve(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new Fe("invalid-index",`array index must be a non-negative integer, got ${Ne(r)}`,e.pos);if(r<0)throw new Fe("invalid-index",`negative array index ${r} not supported (use length-based indexing in eval)`,e.pos);return r>=n.length?null:n[r]}if(typeof n=="object"&&!es(n)){if(typeof r!="string")throw new Fe("invalid-index",`object key must be a string, got ${Ne(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Ye(e,`cannot index into ${Ne(n)}`)}function ea(e,t){if(es(e))throw new Fe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function Ys(e,t){if(!Number.isFinite(e))throw new Fe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function Ne(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(es(e))return`sentinel '@${e.__type}'`;const t=Object.keys(e);if(t.length===0)return"object {}";const n=t.slice(0,3).join(", "),r=t.length>3?", …":"";return`object {${n}${r}}`}return typeof e}const Qh="$expr";class Qs extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function kx(e,t){return ta(e,t,"")}function ta(e,t,n){if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const i=new Array(e.length);for(let o=0;o<e.length;o+=1)i[o]=ta(e[o],t,n===""?String(o):`${n}.${o}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,Qh))return Ex(r,t,n);const s={};for(const i of Object.keys(r))s[i]=ta(r[i],t,n===""?i:`${n}.${i}`);return s}function Ex(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new Qs(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(a=>JSON.stringify(a)).join(", ")}]`,n);const s=e[Qh];if(typeof s!="string")throw new Qs(`'$expr' value at '${n||"<root>"}' must be a string, got ${Rx(s)}`,n);const i=Cx(s,n);return jx(i,t,n)}function jx(e,t,n){try{return Ve(e,t)}catch(r){if(r instanceof Fe){const s=new Fe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function Cx(e,t){try{return ux(ox(e))}catch(n){throw n instanceof me?Bl(n,me,t):n instanceof lt?Bl(n,lt,t):n}}function Bl(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function Rx(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Nx(e){const{resolveSandbox:t,resolveModulesFn:n}=e;return[{name:"firestore_simulator_create",description:'Seed the session\'s local Firestore environment with rules and optional initial documents. Resets any prior state. Refuses rules production would not load (a parse error, a service other than cloud.firestore, a compile limit) and keeps the rules and documents in force. Supports `rules_version = "2+modules"` — modules resolve in-process before seeding. Returns the lint result + document count for verification.',parameters:{type:"object",properties:{rules:{type:"string",description:"Firestore security rules source (version 2 or 2+modules)."},documents:{type:"object",description:'Initial documents keyed by full path, e.g. `{ "users/u1": { name: "alice" } }`.',additionalProperties:!0}},required:["rules"]},async execute(r){const{rules:s,documents:i}=r;let o=s;if(o.includes("'2+modules'")||o.includes('"2+modules"')){if(!n)return{ok:!1,summary:"Module resolve unavailable: this builder was not wired with `resolveModulesFn`. Use a package entry that wires module resolution, such as pyric/rules/internal/node, instead of importing the impl directly.",data:{code:"NO_MODULE_RESOLVER"}};const d=n(o);if(!d.success)return{ok:!1,summary:`Module resolve failed: ${d.error.message}`,data:d};o=d.data.resolved}const a=dw(o);if(a!==null)return{ok:!1,summary:`Firestore ${a.message}`,data:{code:"RULES_REFUSED",rejection:a}};const u=(await t()).seed({rules:o,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:u,documentCount:Object.keys(i??{}).length}}}},{name:"firestore_simulator_execute",description:"Execute a single write (create / update / delete) against the seeded sandbox. Rules evaluate against the in-memory state; allow → state mutates and the op is logged, deny → state unchanged and `debugMessages` explain the rule decision.",parameters:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string",description:"Document path, e.g. `users/u1`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }` where `token` is the custom-claims object."},data:{type:"object",description:"Document data. Required for create / update.",additionalProperties:!0}},required:["method","path","auth"]},async execute(r){const{method:s,path:i,auth:o,data:a}=r,u=(await t()).execute({method:s,path:i,auth:o,data:a});return{ok:u.allowed,summary:u.allowed?`${s} on ${i} allowed`:`${s} on ${i} denied`,data:{allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_read",description:"Read a document (`get`) or list a collection (`list`) from the seeded sandbox. Default uses admin access (bypasses rules). Set `evaluateRules: true` with an `auth` context to test read access control through the rules engine.",parameters:{type:"object",properties:{path:{type:"string",description:"Doc path for `get`, collection path for `list`."},method:{type:"string",enum:["get","list"],description:"Default `get`."},auth:{description:"Auth context. Required when `evaluateRules` is true."},evaluateRules:{type:"boolean",description:"Evaluate read rules against `auth`. Default false (admin read)."}},required:["path"]},async execute(r){const{path:s,method:i,auth:o,evaluateRules:a}=r,l=await t();if(a){const u=l.execute({method:i??"get",path:s,auth:o??null});return{ok:u.allowed,summary:u.allowed?`${i??"get"} on ${s} allowed`:`${i??"get"} on ${s} denied`,data:{allowed:u.allowed,document:u.data,debugMessages:u.debugMessages}}}return i==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:l.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:l.getDocument(s)}}}},{name:"firestore_simulator_batch",description:"Execute multiple writes atomically. All operations must pass rules — if any denies, none apply. Rules evaluate each op against pre-batch state (no cross-visibility within the batch).",parameters:{type:"object",properties:{operations:{type:"array",items:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]}},auth:{description:"Auth context for every op. `null` for unauthenticated."}},required:["operations","auth"]},async execute(r){const{operations:s,auth:i}=r,a=(await t()).batch(s,i);return{ok:a.allowed,summary:a.allowed?`Batch of ${s.length} op(s) committed`:`Batch of ${s.length} op(s) rejected by rules. To SEED data, use the admin data tool firestore_batch_write; to test rules, pass an auth the rules permit.`,data:{allowed:a.allowed,results:a.results}}}},{name:"firestore_create_with_auto_id",description:"Create a document at `<collection>/<auto-id>` with a Firestore-compatible 20-char alphanumeric id (mirrors the live SDK `addDoc()` flow). Rules evaluate as for an explicit-id `create`. Returns the minted path so the caller can re-read the doc without a side channel.",parameters:{type:"object",properties:{collection:{type:"string",description:"Collection path under which to mint the new document, e.g. `users` or `users/u1/posts`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }`."},data:{type:"object",description:"Document data.",additionalProperties:!0}},required:["collection","auth","data"]},async execute(r){const{collection:s,auth:i,data:o}=r,a=await t(),{path:l,result:u}=a.createWithAutoId(s,o,i);return{ok:u.allowed,summary:u.allowed?`Created ${l}`:`Create at ${l} denied by rules (as ${i?i.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:l,allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_undo",description:"Undo the last allowed write. Restores state to immediately before that op. Returns the undone event, or a `{ undone: false }` outcome when no retained write remains.",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).undo();return s?{ok:!0,summary:`Undid ${s.method} on ${s.path}`,data:{undone:!0,event:{method:s.method,path:s.path}}}:{ok:!0,summary:"Nothing to undo",data:{undone:!1}}}},{name:"firestore_simulator_redo",description:"Re-apply the most recently undone write. Pairs with `firestore_simulator_undo`. Returns the re-applied event, or `{ redone: false }` when the undo stack is empty (no recent undo to redo).",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${s.event?.method??"op"} on ${s.event?.path??"?"}`:"Redo restored a denied event (no state change)",data:{redone:!0,allowed:s.allowed,event:s.event?{method:s.event.method,path:s.event.path}:null,debugMessages:s.debugMessages}}:{ok:!0,summary:"Nothing to redo",data:{redone:!1}}}},{name:"firestore_simulator_events",description:'Return retained events — allowed and denied — with timestamps, auth, debug messages, and an omitted count when the bounded log was trimmed. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){const r=await t(),{omittedCount:s}=r.getEventRetention();return{ok:!0,summary:s>0?`Event log (${s} omitted)`:"Event log",data:{omittedCount:s,events:r.getEvents().map(o=>({id:o.id,method:o.method,path:o.path,allowed:o.allowed,auth:o.auth,debugMessages:o.debugMessages}))}}}},{name:"firestore_simulator_transaction",description:'Run a declarative transaction. Reads are captured server-side and referenced from write data via `{ "$expr": "..." }` wrappers — agents never see the read values, eliminating the "round-trip the doc through context" cost. Expression DSL: arithmetic (+ - * / %), comparison, &&/||/?:, $alias.field references, string literals in either "double" or \'single\' quotes, and @sentinel(...) calls (@increment, @serverTimestamp, @arrayUnion, @arrayRemove, @deleteField). Reads are omitted from the response by default; set `includeReads: true` when debugging a denial.',parameters:{type:"object",properties:{auth:{description:"Auth context for rule eval. `null` for unauthenticated."},readOnly:{type:"boolean",description:"Hint that the transaction is read-only. v1: writes are still committed; `readOnlyViolation: true` surfaces on the response if any was queued."},includeReads:{type:"boolean",description:"Default false. When true, the response includes the captured read data + per-write debugMessages."},reads:{type:"object",description:"Reads keyed by alias. Aliases referenced from write expressions as `$alias` (e.g. `$src.balance`).",additionalProperties:{type:"string"}},writes:{type:"array",minItems:1,items:{type:"object",properties:{method:{type:"string",enum:["create","update","set","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]},description:"Write operations to apply atomically."}},required:["reads","writes","auth"]},async execute(r){const{auth:s,readOnly:i,includeReads:o,reads:a,writes:l}=r;for(let h=0;h<l.length;h+=1){const f=l[h];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${h}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${h}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=o===!0;try{const h=u.transaction(p=>{const m={};for(const[g,b]of Object.entries(a)){const x=p.get(b).data();m[g]=x===void 0?null:x}for(let g=0;g<l.length;g+=1){const b=l[g];if(b.method==="delete"){p.delete(b.path);continue}const w=kx(b.data,{reads:m});if(w===null||typeof w!="object"||Array.isArray(w))throw new Qs(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const x=w;switch(b.method){case"create":p.create(b.path,x);break;case"update":p.update(b.path,x);break;case"set":p.set(b.path,x);break}}},{auth:s,readOnly:i}),f={allowed:h.allowed,writes:h.writes.map(p=>{const m={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(m.error={code:p.error.code,message:p.error.message}),d&&(m.debugMessages=p.debugMessages),m})};return h.error&&(f.error={code:h.error.code,message:h.error.message}),h.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=h.reads.map(p=>({path:p.path,data:p.data}))),{ok:h.allowed,summary:h.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(h){if(h instanceof Qs||h instanceof me||h instanceof lt||h instanceof Fe)return{ok:!1,summary:`Transaction failed: ${h.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:h.message}}};throw h}}}]}function Ix(e){return Nx({resolveSandbox:e.resolveSandbox,resolveModulesFn:jh})}const Ax=new Set([".read",".write",".validate",".indexOn"]),Ox=new Set([".read",".write",".validate"]),xc=/[.#$/[\]]/,$x="Invalid rule expression. Expected 'true', 'false', or an expression string.",Px="Invalid indexOn expression. Must be either a string or an array of strings",Fl=`String can't contain ".", "#", "$", "/", "[", or "]"`,ql="Expected '{'.",Vl=e=>`Invalid key: ${e}. Index must be either .value or declared on a valid path`;function Dx(e,t){const n=Array.isArray(e)?e:[e];for(const r of n){if(typeof r!="string"||r===".value")continue;const s=r.split("/");s.some(i=>i.includes("."))?t(Vl(r),"error"):s.some(i=>xc.test(i))&&t(Vl(r),"warning")}}function Xh(e,t){const n=[],r=(i,o,a="error")=>{n.push({path:e,code:i,message:o,severity:a})},s=[];for(const[i,o]of Object.entries(t)){if(Ox.has(i)){typeof o!="string"&&typeof o!="boolean"&&r("RULE_NOT_EXPRESSION",$x,typeof o=="number"||typeof o=="object"&&o!==null?"error":"warning");continue}if(i===".indexOn"){const u=h=>typeof h=="string";u(o)||Array.isArray(o)&&o.every(u)?Dx(o,(h,f)=>r("INVALID_KEY",h,f)):r("INDEX_ON_SHAPE",Px,typeof o=="number"?"error":"warning");continue}const a=typeof o=="object"&&o!==null&&!Array.isArray(o);if(i.startsWith(".")){a?r("INVALID_KEY",Fl):r("EXPECTED_OBJECT",ql);continue}i.startsWith("$")&&s.push(i);const l=i.startsWith("$")?i.slice(1):i;xc.test(l)?r("INVALID_KEY",Fl,l.includes("#")?"error":"warning"):a||r("EXPECTED_OBJECT",ql)}return s.length>1&&r("MULTIPLE_WILDCARDS",`Cannot have multiple default rules ('${s[0]}' and '${s[1]}').`),n}const oe=e=>e;function Ge(e){if(e===null)return"null";if(typeof e=="string"){if(/[\u0000-\u001f\u007f]/.test(e))throw new Error(`lit: ${JSON.stringify(e)} holds a newline or another control character, which RTDB rules literals here cannot carry.`);return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`RTDB rules have no literal for ${e}.`);return String(e)}if(typeof e=="boolean")return e?"true":"false";let t=typeof e;throw e===void 0?t="undefined":Array.isArray(e)&&(t="array"),new Error(`RTDB rules have no literal for ${t}.`)}function Zh(e,t){if(typeof t!="string"||t.length===0||xc.test(t))throw new Error(`${e}: '${String(t)}' is not a field name; RTDB keys cannot be empty or contain . # $ / [ ].`);return t}function Tx(e,t){let n=0,r=null,s=!1,i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(r){a==="\\"?o++:a===r&&(r=null);continue}if(s){a==="\\"?o++:i?a==="]"&&(i=!1):a==="["?i=!0:a==="/"&&(s=!1);continue}if(a==="'"||a==='"')r=a;else if(a==="/"&&/\(\s*$/.test(e.slice(0,o)))s=!0;else if(a==="("||a==="[")n++;else if(a===")"||a==="]")n--;else if(n===0&&t.some(l=>e.startsWith(l,o)))return!0}return!1}const ep=(e,t)=>Tx(e,t)?`(${e})`:e,tp=e=>e.trim().length>0;function Nn(...e){const t=e.filter(tp);if(t.length===0)throw new Error("all: pass at least one condition; an empty all() would allow everything.");return t.length===1?t[0]:oe(t.map(n=>ep(n,["||","?"])).join(" && "))}function Wl(...e){const t=e.filter(tp);if(t.length===0)throw new Error("any: pass at least one condition; an empty any() would deny everything.");return t.length===1?t[0]:oe(t.map(n=>ep(n,["&&","?"])).join(" || "))}const Mx=`RtdbExpr {
6
+ Expr = Ternary
7
+
8
+ Ternary
9
+ = LogicalOr "?" Ternary ":" Ternary -- ternary
10
+ | LogicalOr
11
+
12
+ // \`||\` and \`&&\` match as flat chains, not left recursion, so a semantics
13
+ // folds a chain of any length in a loop instead of descending once per
14
+ // term. Production deploys a 2,000-term \`||\` chain (r51).
15
+ LogicalOr
16
+ = LogicalAnd ("||" LogicalAnd)+ -- or
17
+ | LogicalAnd
18
+
19
+ LogicalAnd
20
+ = Equality ("&&" Equality)+ -- and
21
+ | Equality
22
+
23
+ Equality
24
+ = Equality "===" Comparison -- strictEq
25
+ | Equality "!==" Comparison -- strictNeq
26
+ | Equality "==" Comparison -- looseEq
27
+ | Equality "!=" Comparison -- looseNeq
28
+ | Comparison
29
+
30
+ Comparison
31
+ = Comparison ">=" Additive -- gte
32
+ | Comparison "<=" Additive -- lte
33
+ | Comparison ">" Additive -- gt
34
+ | Comparison "<" Additive -- lt
35
+ | Additive
36
+
37
+ Additive
38
+ = Additive "+" Multiplicative -- add
39
+ | Additive "-" Multiplicative -- sub
40
+ | Multiplicative
41
+
42
+ Multiplicative
43
+ = Multiplicative "*" UnaryExpr -- mul
44
+ | Multiplicative "/" UnaryExpr -- div
45
+ | Multiplicative "%" UnaryExpr -- mod
46
+ | UnaryExpr
47
+
48
+ UnaryExpr
49
+ = "!" UnaryExpr -- not
50
+ | "-" UnaryExpr -- neg
51
+ | CallExpr
52
+
53
+ CallExpr
54
+ = CallExpr "." ident "(" ListOf<Expr, ","> ")" -- methodCall
55
+ | CallExpr "." ident -- memberAccess
56
+ | CallExpr "[" Expr "]" -- indexAccess
57
+ | Primary
58
+
59
+ Primary
60
+ = "(" Expr ")" -- paren
61
+ | Array
62
+ | literal
63
+ | ident
64
+
65
+ Array = "[" ListOf<Expr, ","> "]"
66
+
67
+ literal
68
+ = number
69
+ | string
70
+ | regex
71
+ | bool
72
+ | null
73
+
74
+ number
75
+ = digit+ "." digit+ exponent? -- float
76
+ | digit+ exponent -- exp
77
+ | digit+ -- int
78
+
79
+ exponent = ("e" | "E") ("+" | "-")? digit+
80
+
81
+ string
82
+ = "\\"" doubleStringChar* "\\"" -- double
83
+ | "'" singleStringChar* "'" -- single
84
+
85
+ doubleStringChar
86
+ = "\\\\" any -- escape
87
+ | ~"\\"" any -- char
88
+
89
+ singleStringChar
90
+ = "\\\\" any -- escape
91
+ | ~"'" any -- char
92
+
93
+ regex = "/" regexBody "/" regexFlags
94
+
95
+ regexBody = regexChar+
96
+
97
+ regexChar
98
+ = "\\\\" any -- escape
99
+ | regexClass -- class
100
+ | ~("/" | "\\n" | "[") any -- char
101
+
102
+ regexClass = "[" regexClassChar* "]"
103
+
104
+ regexClassChar
105
+ = "\\\\" any -- escape
106
+ | ~("]" | "\\n") any -- char
107
+
108
+ regexFlags = alnum*
109
+
110
+ bool
111
+ = "true" ~identChar -- true
112
+ | "false" ~identChar -- false
113
+
114
+ null = "null" ~identChar
115
+
116
+ ident = "$"? identStart identChar*
117
+
118
+ identStart = letter | "_"
119
+
120
+ identChar = alnum | "_" | "$"
121
+ }
122
+ `;let zl;function np(){return zl??=hw(Mx),zl}const ts="The expression chains more terms than the rules parser reads.",rp=128*1024;function Lx(e){return`The expression is ${e} characters long: the rules parser reads at most ${rp}, a limit of this parser, not of production.`}function ns(e){const t=e.trim();if(t.length>rp)return{ok:!1,message:Lx(t.length)};const n=fw(t,{comments:!1,regexLiterals:!0,multilineStrings:!0}).find(r=>r.depth>to);if(n!==void 0)return{ok:!1,message:`Brackets nest more than ${to} levels deep at offset ${n.open}: the rules parser reads at most ${to}, a limit of this parser, not of production.`};try{const r=np().match(t);return r.failed()?{ok:!1,message:r.message??"Parse failed"}:{ok:!0,match:r}}catch(r){if(r instanceof RangeError)return{ok:!1,message:ts};throw r}}function rs(){return np().createSemantics()}const Xs="unterminated string literal",Ux=/^[0-9a-fA-F]{2}$/,Bx=/^[0-9a-fA-F]{4}$/,Fx={b:"\b",f:"\f",n:`
123
+ `,r:"\r",t:" ",v:"\v",0:"\0","\\":"\\","'":"'",'"':'"',"/":"/"};function Rr(e){const t=sp(e);return t.includes(`
124
+ `)||t.includes("\r")}function qx(e){let t=0;const n=e.length;let r=!0;for(;t<n;){const s=e[t];if(s===" "||s===" "||s===`
125
+ `||s==="\r"){t++;continue}if(s==='"'||s==="'"){const i=s;for(t++;t<n;){const o=e[t];if(o===`
126
+ `||o==="\r")return!0;if(o==="\\"){t+=2;continue}if(o===i){t++;break}t++}r=!1;continue}if(s==="/"&&r){t=pw(e,t),r=!1;continue}r=Vx(s),t++}return!1}function Nr(e){const t=sp(e);let n="",r=0;const s=t.length;for(;r<s;){const i=t[r];if(i!=="\\"){n+=i,r++;continue}if(r+1>=s){n+="\\";break}const o=t[r+1],a=Fx[o];if(a!==void 0){n+=a,r+=2;continue}if(o==="x"&&r+3<s){const l=t.slice(r+2,r+4);if(Ux.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=4;continue}}if(o==="u"&&r+5<s){const l=t.slice(r+2,r+6);if(Bx.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=6;continue}}n+=o,r+=2}return n}function sp(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==='"'&&n==='"'||t==="'"&&n==="'")return e.slice(1,-1)}return e}function Vx(e){return"(!,&|?:;=[<>+-*%".includes(e)}function dn(e,t){return e==="matches"?"matches() expects 1 regular expression literal argument.":t===0?`${e}() expects no arguments.`:t===1?`${e}() expects 1 argument.`:`${e}() expects two arguments.`}function ip(e){return`${e}() expects a string argument.`}function na(e){return`Argument ${e} of replace() must be a string.`}const op="hasChildren() expects only a single argument (containing an array of child names).",ap="hasChildren() expects an array of child names.",cp="hasChildren() expects an array of strings.";function Zs(e,t){switch(e){case"==":case"===":return t==="left"?"Invalid == expression: left operand is not a number, boolean, string, null.":"Invalid == expression: right operand is not a number, boolean, string, or null.";case"!=":case"!==":return`Invalid != expression: ${t} operand is not a number, boolean, string, or null.`;case"+":return`Invalid + expression: ${t} operand is not a number or string.`;case"-":case"*":case"/":case"%":return`Invalid ${e} expression: ${t} operand is not a number.`;default:return`Invalid ${e} expression: ${t} operand must be a number or string.`}}function Hl(e){return`Unknown variable '${e}'.`}const lp="matches() expects a regular expression literal argument.",up="regular expressions do not support flags other than i";function _c(e){return e===""||e==="i"}const dp="Illegal regular expression, ";class ei extends SyntaxError{}const Wx={kind:"char",test:()=>!1},zx={kind:"char",test:()=>!0},Hx="?*+{",Kl="0123456789",Gl=e=>e>="0"&&e<="9",Jl=e=>/^[A-Za-z0-9_]$/.test(e),Yl=e=>e.length===1&&`
127
+ \v\f\r`.includes(e),Kx={d:Gl,D:e=>!Gl(e),w:Jl,W:e=>!Jl(e),s:Yl,S:e=>!Yl(e)};class Gx{text;ignoreCase;pos=0;depth=0;constructor(t,n){this.text=t,this.ignoreCase=n}parse(){if(!this.more())return{kind:"empty"};const t=this.union();this.more()&&this.fail("end-of-string expected");const n=mw(t);return n!==null&&this.refuse(n),t}union(){const t=[this.concat()];for(;this.match("|");)t.push(this.concat());return ra(t,0,t.length)}concat(){const t=[this.repeat()];for(;this.more()&&!this.peek(")|");)t.push(this.repeat());return t.length===1?t[0]:{kind:"seq",items:t}}repeat(){let t=this.characterSet(),n=0;for(;this.peek(Hx);)n++,this.depth+n>Al&&this.refuse(Ol),this.match("?")?t={kind:"rep",body:t,min:0,max:1}:this.match("*")?t={kind:"rep",body:t,min:0,max:1/0}:this.match("+")?t={kind:"rep",body:t,min:1,max:1/0}:t=this.counted(t);return t}counted(t){this.pos++;const n=this.integer();let r=n;return this.match(",")&&(r=this.peek(Kl)?this.integer():1/0),this.match("}")||this.fail(`expected '}' at position ${this.pos}`),n>r?Wx:{kind:"rep",body:t,min:n,max:r}}integer(){const t=this.pos;for(;this.peek(Kl);)this.pos++;t===this.pos&&this.fail(`integer expected at position ${this.pos}`);const n=this.text.slice(t,this.pos),r=Number(n);return r>yw&&this.refuse(gw(n)),r}characterSet(){if(!this.match("["))return this.simple();const t=this.match("^"),n=[this.setMember()];for(;this.more()&&!this.peek("]");)n.push(this.setMember());this.match("]")||this.fail(`expected ']' at position ${this.pos}`);const r=n.map(i=>this.memberTest(i)),s=i=>r.some(o=>o(i));return t?{kind:"char",test:i=>!s(i)}:{kind:"char",test:s}}setMember(){const t=this.charExp();if(t.kind==="class"||!this.match("-"))return t;const n={kind:"char",ch:"-"};if(this.peek("]"))return{kind:"class",test:this.unionTest([t,n])};const r=this.charExp();return r.kind==="class"?{kind:"class",test:this.unionTest([t,n,r])}:{kind:"range",from:t.ch,to:r.ch}}memberTest(t){return t.kind==="range"?this.rangeTest(t.from,t.to):this.unionTest([t])}unionTest(t){const n=t.map(r=>r.kind==="class"?r.test:this.literal(r.ch));return r=>n.some(s=>s(r))}simple(){if(this.match("."))return zx;if(this.match("("))return this.group();const t=this.charExp();return{kind:"char",test:t.kind==="class"?t.test:this.literal(t.ch)}}group(){if(this.match(")"))return{kind:"empty"};this.depth++,this.depth>Al&&this.refuse(Ol);const t=this.union();return this.depth--,this.match(")")||this.fail(`expected ')' at position ${this.pos}`),t}charExp(){const t=this.match("\\"),n=this.next(),r=t?Kx[n]:void 0;return r?{kind:"class",test:r}:{kind:"char",ch:n}}literal(t){if(!this.ignoreCase)return r=>r===t;const n=ys(t);return r=>n.includes(r)}rangeTest(t,n){const r=Yx(t,n);if(!this.ignoreCase)return r;const s=n.charCodeAt(0)-t.charCodeAt(0);if(s<0)return r;if(s>Jx){const o=a=>l=>r(l)&&ys(l).includes(a);return a=>r(a)||ys(a).some(o(a))}const i=new Set;for(let o=t.charCodeAt(0);o<=n.charCodeAt(0);o++)for(const a of ys(String.fromCharCode(o)))i.add(a);return o=>i.has(o)}next(){return this.more()||this.fail("unexpected end-of-string"),this.text[this.pos++]}more(){return this.pos<this.text.length}peek(t){return this.more()&&t.includes(this.text[this.pos])}match(t){return this.text[this.pos]!==t?!1:(this.pos++,!0)}fail(t){throw new ei(`${dp}${t}`)}refuse(t){throw new ei(t)}}const Jx=4096;function ys(e){const t=[e];for(const n of[e.toUpperCase(),e.toLowerCase()])n.length===1&&!t.includes(n)&&t.push(n);return t}function Yx(e,t){return n=>n.length===1&&n>=e&&n<=t}function ra(e,t,n){if(n-t===1)return e[t];const r=t+Math.floor((n-t)/2);return{kind:"alt",left:ra(e,t,r),right:ra(e,r,n)}}const Qx=`${dp}unescaped ^, ^ can only appear at the end of regular expressions`;class fp{source;flags;node;matcher;constructor(t,n,r){this.source=t,this.flags=n,this.node=r}test(t){return this.matcher??=ww(this.node),this.matcher(t.split(""))}}function hp(e){try{return pp(e,!1),null}catch(t){if(t instanceof ei)return t.message;throw t}}const Xx=1e6,no=new Map;let ro=0;function Zx(e,t){const n=`${t}/${e}`,r=no.get(n);if(r)return r;const s=pp(e,t.includes("i")),i=new fp(e,t,s),o=bw(s);return ro+o>Xx&&(no.clear(),ro=0),no.set(n,i),ro+=o,i}function pp(e,t){return new Gx(e_(e),t).parse()}function e_(e){const t=e.startsWith("^");let n=t?e.slice(1):e;const r=t_(n);if(r&&(n=n.slice(0,-1)),n_(n))throw new ei(Qx);return`${t?"":".*"}${n}${r?"":".*"}`}function t_(e){if(!e.endsWith("$"))return!1;let t=0;for(let n=e.length-2;n>=0&&e[n]==="\\";n--)t++;return t%2===0}function n_(e){let t=0;for(;t<e.length;){const n=e[t];if(n==="\\")t+=2;else if(n==="[")t=r_(e,t);else{if(n==="^"||n==="$")return!0;t++}}return!1}function r_(e,t){let n=t+1;e[n]==="^"&&n++;let r=!0;for(;n<e.length;){const s=e[n];if(s==="]"&&!r)return n+1;n+=s==="\\"?2:1,r=!1}return n}const s_=new Set(["__proto__","prototype","constructor"]);function Ql(e,t){return s_.has(t)?null:typeof e=="string"?t==="length"?e.length:null:e===null||typeof e!="object"||!Object.hasOwn(e,t)?null:e[t]??null}function Sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mr(e){if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=mr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(!Sc(e))return e??null;if(Object.hasOwn(e,".value"))return mr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;const s=mr(r);s!==null&&Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return Object.keys(t).length===0?null:t}function i_(e){if(!Sc(e)||mr(e)===null)return null;const t=e[".priority"];return typeof t=="number"||typeof t=="string"?t:null}class Ut{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return mr(this._value)}exists(){return this.val()!==null}hasChild(t){return this.child(t).exists()}hasChildren(t){return t!==void 0?t.every(n=>this.hasChild(n)):Sc(this.val())}isString(){return typeof this.val()=="string"}isNumber(){return typeof this.val()=="number"}isBoolean(){return typeof this.val()=="boolean"}child(t){const n=t.split("/").filter(o=>o.length>0);if(n.length===0)return this;let r=this._value;for(const o of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,o)?r[o]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new Ut(r,i,this._root)}parent(){if(this._path==="/")throw new ne("Cannot call parent() on root.");const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new Ut(this._root,"/"):new Ut(this._root,"/").child(t.join("/"))}getPriority(){return i_(this._value)}}class o_{value;constructor(t){this.value=t}matches(t){return t.test(this.value)}contains(t){return this.value.includes(t)}beginsWith(t){return this.value.startsWith(t)}endsWith(t){return this.value.endsWith(t)}replace(t,n){return t===""?this.value:this.value.split(t).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}class ne extends Error{constructor(t){super(t),this.name="RtdbRuleRuntimeError"}}const Xl=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),a_=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase"]);function Qn(e,t){if(t.length!==1)throw new ne(dn(e,1));const[n]=t;if(typeof n!="string")throw new ne(ip(e));return n}function c_(e){if(e.length===0)return;if(e.length>1)throw new ne(op);const[t]=e;if(!Array.isArray(t))throw new ne(ap);if(!t.every(n=>typeof n=="string"))throw new ne(cp);return t}function l_(e){if(e.length!==1)throw new ne(dn("matches",1));const[t]=e;if(!(t instanceof fp))throw new ne(lp);return t}function u_(e){if(e.length!==2)throw new ne(dn("replace",2));const[t,n]=e;if(typeof t!="string")throw new ne(na(1));if(typeof n!="string")throw new ne(na(2));return[t,n]}const d_=new Set(["==","===","!=","!=="]),f_=new Set(["-","*","/","%"]),h_=new Set(["<","<=",">",">="]);function Zl(e,t){return t instanceof Ut||typeof t=="function"?!0:d_.has(e)?!1:f_.has(e)?typeof t!="number":typeof t!="number"&&typeof t!="string"}function Ue(e,t,n,r){const s=t.eval(r);if(Zl(e,s))throw new ne(Zs(e,"left"));const i=n.eval(r);if(Zl(e,i)||h_.has(e)&&typeof s!=typeof i)throw new ne(Zs(e,"right"));return[s,i]}function p_(e){return e===null?"null":Array.isArray(e)?"array":typeof e}let so;function m_(){if(so)return so;const e=rs();return e.addOperation("eval(ctx)",{Expr(t){return t.eval(this.args.ctx)},Ternary_ternary(t,n,r,s,i){const o=t.eval(this.args.ctx);if(typeof o!="boolean")throw new ne("condition of ? must be boolean.");return o?r.eval(this.args.ctx):i.eval(this.args.ctx)},Ternary(t){return t.eval(this.args.ctx)},LogicalOr_or(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ne("Left operand of || must be boolean.");if(s)return!0;for(const i of r.children){const o=i.eval(this.args.ctx);if(typeof o!="boolean")throw new ne("Right operand of || must be boolean.");if(o)return!0}return!1},LogicalOr(t){return t.eval(this.args.ctx)},LogicalAnd_and(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ne("Left operand of && must be boolean.");if(!s)return!1;for(const i of r.children){const o=i.eval(this.args.ctx);if(typeof o!="boolean")throw new ne("Right operand of && must be boolean.");if(!o)return!1}return!0},LogicalAnd(t){return t.eval(this.args.ctx)},Equality_strictEq(t,n,r){const[s,i]=Ue("===",t,r,this.args.ctx);return s===i},Equality_strictNeq(t,n,r){const[s,i]=Ue("!==",t,r,this.args.ctx);return s!==i},Equality_looseEq(t,n,r){const[s,i]=Ue("==",t,r,this.args.ctx);return s===i},Equality_looseNeq(t,n,r){const[s,i]=Ue("!=",t,r,this.args.ctx);return s!==i},Equality(t){return t.eval(this.args.ctx)},Comparison_gte(t,n,r){const[s,i]=Ue(">=",t,r,this.args.ctx);return s>=i},Comparison_lte(t,n,r){const[s,i]=Ue("<=",t,r,this.args.ctx);return s<=i},Comparison_gt(t,n,r){const[s,i]=Ue(">",t,r,this.args.ctx);return s>i},Comparison_lt(t,n,r){const[s,i]=Ue("<",t,r,this.args.ctx);return s<i},Comparison(t){return t.eval(this.args.ctx)},Additive_add(t,n,r){const[s,i]=Ue("+",t,r,this.args.ctx);return s+i},Additive_sub(t,n,r){const[s,i]=Ue("-",t,r,this.args.ctx);return s-i},Additive(t){return t.eval(this.args.ctx)},Multiplicative_mul(t,n,r){const[s,i]=Ue("*",t,r,this.args.ctx);return s*i},Multiplicative_div(t,n,r){const[s,i]=Ue("/",t,r,this.args.ctx);return i===0?Number.NaN:s/i},Multiplicative_mod(t,n,r){const[s,i]=Ue("%",t,r,this.args.ctx);return s%i},Multiplicative(t){return t.eval(this.args.ctx)},UnaryExpr_not(t,n){const r=n.eval(this.args.ctx);return typeof r=="boolean"?!r:!1},UnaryExpr_neg(t,n){const r=n.eval(this.args.ctx);if(typeof r!="number")throw new ne("Invalid unary - expression: operand is not a number.");return-r},UnaryExpr(t){return t.eval(this.args.ctx)},CallExpr_methodCall(t,n,r,s,i,o){const a=t.eval(this.args.ctx),l=r.sourceString,u=i.asIteration().children.map(h=>h.eval(this.args.ctx));if(a instanceof Ut)switch(l){case"val":return a.val();case"exists":return a.exists();case"hasChild":return a.hasChild(Qn(l,u));case"hasChildren":return a.hasChildren(c_(u));case"isString":return a.isString();case"isNumber":return a.isNumber();case"isBoolean":return a.isBoolean();case"child":return a.child(Qn(l,u));case"parent":return a.parent();case"getPriority":return a.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof a=="string"){const h=new o_(a);switch(l){case"matches":return h.matches(l_(u));case"contains":return h.contains(Qn(l,u));case"beginsWith":return h.beginsWith(Qn(l,u));case"endsWith":return h.endsWith(Qn(l,u));case"replace":return h.replace(...u_(u));case"toLowerCase":return h.toLowerCase();case"toUpperCase":return h.toUpperCase();default:throw Xl.has(l)?new ne(`Method '${l}' is not defined on a string.`):new Error(`Unknown string method: ${l}`)}}throw(Xl.has(l)||a_.has(l))&&a!==void 0?new ne(`Method '${l}' is not defined on ${p_(a)}.`):new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval(this.args.ctx),i=r.sourceString;if(i==="length"){if(typeof s=="string")return s.length;throw new ne("No such method/property 'length'.")}return s==null?null:Ql(s,i)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(this.args.ctx),o=r.eval(this.args.ctx);if(typeof o!="string"&&typeof o!="number")throw new ne("Invalid property access.");return i==null?null:Ql(i,String(o))},CallExpr(t){return t.eval(this.args.ctx)},Primary_paren(t,n,r){return n.eval(this.args.ctx)},Primary(t){return t.eval(this.args.ctx)},Array(t,n,r){return n.asIteration().children.map(s=>s.eval(this.args.ctx))},literal(t){return t.eval(this.args.ctx)},number_float(t,n,r,s){return parseFloat(this.sourceString)},number_exp(t,n){return parseFloat(this.sourceString)},number_int(t){return parseInt(this.sourceString,10)},number(t){return t.eval(this.args.ctx)},string_double(t,n,r){if(Rr(this.sourceString))throw new SyntaxError(Xs);return Nr(this.sourceString)},string_single(t,n,r){if(Rr(this.sourceString))throw new SyntaxError(Xs);return Nr(this.sourceString)},string(t){return t.eval(this.args.ctx)},regex(t,n,r,s){if(!_c(s.sourceString))throw new ne(up);return Zx(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval(this.args.ctx)},null(t){return null},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$"){const o=s?.pathVariableBindings;if(o!==void 0){if(i in o)return o[i];if(i.slice(1)in o)return o[i.slice(1)]}return}switch(i){case"auth":return s?.auth??null;case"data":return s?.data;case"newData":return s?.newData;case"root":return s?.root;case"now":return s?.now;case"query":return s?.query??null;default:return}}}),so=e,e}function mp(e){const t=ns(e);if(!t.ok)throw new Error(t.message);return m_()(t.match)}function Us(e,t){return mp(e).eval(t)}const eu=new WeakMap;function y_(e,t){let n=eu.get(e);return n===void 0&&(n=mp(e.raw),eu.set(e,n)),n.eval(t)}let io;const g_=/^\$[A-Za-z_]\w*$/,b_=/^(?:auth|data|newData|root|query)(?:\.|\[)/;function w_(e){return e==="now"||g_.test(e)||b_.test(e)}function v_(e){if(e.isLiteral())try{const t=Us(e.sourceString,{});return typeof t=="string"?t:void 0}catch(t){if(t instanceof ne)return;throw t}}function gt(e){const[t,,n]=e.children;if(!(!t.isLiteral()||!n.isLiteral()))try{const r=Us(t.sourceString,{}),s=Us(n.sourceString,{});return typeof r=="number"&&!Number.isFinite(r)||typeof s=="number"&&!Number.isFinite(s)?void 0:Us(e.sourceString,{})===!0}catch(r){if(r instanceof ne)return;throw r}}function Nt(e,t,n){const r=e.args.ctx;t.lint(r),n.lint(r);const s=gt(e);if(s!==void 0){r.constantComparisons.push({source:e.sourceString,value:s});return}const i=t.isLiteral(),o=n.isLiteral();if(i===o)return;let a=n;i&&(a=t);const l=v_(a);l!==void 0&&w_(l)&&r.warnings.push({code:"QUOTED_REFERENCE",message:`Comparison ${e.sourceString} quotes '${l}' as a string literal; it compares against the literal text '${l}' rather than evaluating ${l}.`})}function x_(){if(io)return io;const e=rs();return e.addOperation("lint(ctx)",{_nonterminal(...t){t.forEach(n=>n.lint(this.args.ctx))},_iter(...t){t.forEach(n=>n.lint(this.args.ctx))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx;t.lint(a),i.asIteration().children.forEach(l=>l.lint(a)),r.sourceString==="child"&&t.isDataSnapshot()&&(a.hasDataChildAccess=!0)},CallExpr_memberAccess(t,n,r){t.lint(this.args.ctx)},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;i==="data"&&(s.hasData=!0),i==="newData"&&(s.hasNewData=!0)},Equality_strictEq(t,n,r){Nt(this,t,r)},Equality_strictNeq(t,n,r){Nt(this,t,r)},Comparison_gte(t,n,r){Nt(this,t,r)},Comparison_lte(t,n,r){Nt(this,t,r)},Comparison_gt(t,n,r){Nt(this,t,r)},Comparison_lt(t,n,r){Nt(this,t,r)},Equality_looseEq(t,n,r){Nt(this,t,r)},Equality_looseNeq(t,n,r){Nt(this,t,r)}}),e.addOperation("isDataSnapshot",{_nonterminal(...t){return t.length===1?t[0].isDataSnapshot():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isDataSnapshot()},ident(t,n,r){return this.sourceString==="data"},CallExpr_methodCall(t,n,r,s,i,o){const a=r.sourceString;return a==="parent"||a==="child"?t.isDataSnapshot():!1}}),e.addOperation("isNumberLiteral",{_nonterminal(...t){return t.length===1?t[0].isNumberLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isNumberLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},number(t){return Number.isFinite(Number(this.sourceString))}}),e.addOperation("isLiteral",{_nonterminal(...t){return t.length===1?t[0].isLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},literal(t){return t.ctorName==="regex"?!1:t.ctorName==="number"?Number.isFinite(Number(t.sourceString)):!0}}),e.addOperation("literalBoolean",{_nonterminal(...t){return t.length===1?t[0].literalBoolean():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalBoolean()},bool_true(t){return!0},bool_false(t){return!1},Equality_strictEq(t,n,r){return gt(this)},Equality_strictNeq(t,n,r){return gt(this)},Comparison_gte(t,n,r){return gt(this)},Comparison_lte(t,n,r){return gt(this)},Comparison_gt(t,n,r){return gt(this)},Comparison_lt(t,n,r){return gt(this)},Equality_looseEq(t,n,r){return gt(this)},Equality_looseNeq(t,n,r){return gt(this)}}),io=e,e}function __(e,t="read"){const n=ns(e);if(!n.ok)return[];const{match:r}=n,s={warnings:[],hasData:!1,hasNewData:!1,hasDataChildAccess:!1,constantComparisons:[]};try{const i=x_()(r);i.lint(s);const o=t==="validate"?void 0:i.literalBoolean();if(o===!0)s.warnings.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"});else if(o===!1)s.warnings.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"});else for(const{source:a,value:l}of s.constantComparisons)s.warnings.push({code:"CONSTANT_COMPARISON",message:`Comparison ${a} is always ${l}.`})}catch(i){if(i instanceof RangeError)return[{code:"PARSE_ERROR",message:ts}];if(i instanceof SyntaxError)return[{code:"PARSE_ERROR",message:i.message}];throw i}return t==="write"&&s.hasData&&!s.hasNewData&&!s.hasDataChildAccess&&s.warnings.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),s.warnings}function S_(e,t){if(typeof t!="string"||t.length===0)throw new Error(`${e}: child path cannot be empty.`);for(const n of t.split("/"))Zh(e,n);return t}const k_=()=>oe("newData.hasChildren()"),E_=e=>oe(`newData.hasChild(${Ge(S_("hasChild",e))})`);let oo;function j_(){if(oo)return oo;const e=rs();return e.addOperation("identifiers",{_nonterminal(...t){return t.flatMap(n=>n.identifiers())},_iter(...t){return t.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(t,n,r,s,i,o){return[...t.identifiers(),...i.asIteration().children.flatMap(a=>a.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),oo=e,e}const C_="Rule expressions may not contain assignments.";function R_(e){const t=e.replace(/'(?:\\.|[^'\\])*'?|"(?:\\.|[^"\\])*"?|\/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[a-zA-Z]*/g,'""');return/(^|[^=!<>])=(?!=)/.test(t)}function N_(e){if(qx(e))return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Xs}],warnings:[],referencedIdentifiers:[]};const t=ns(e);if(!t.ok)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:R_(e)?C_:t.message}],warnings:[],referencedIdentifiers:[]};let n;try{n=j_()(t.match).identifiers()}catch(s){if(s instanceof RangeError)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ts}],warnings:[],referencedIdentifiers:[]};throw s}const r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function I_(e){return e==="rtdb"?"database":"firestore"}function Xn(e){return e.kind==="doc"?e.path:{collection:e.collection,query:e.query}}function A_(e){return e.path!==void 0?e.path:{collection:"",query:e.query}}function tu(e){const t=e.query;return t===void 0?{}:{query:t}}function O_(e){const t=pc(e),n="owners"in e&&Array.isArray(e.owners)?e.owners:void 0,r={actor:t.source,authLens:t.authLens,owners:n};return e.kind==="listener_attach"?{phase:"attach",listenerId:e.listenerId,service:"firestore",target:Xn(e.target),...r,...tu(e.target)}:e.kind==="listener_detach"?{phase:"detach",listenerId:e.listenerId,service:"firestore",target:Xn(e.target),...r}:e.kind==="listener_errored"?{phase:"errored",listenerId:e.listenerId,service:"firestore",target:Xn(e.target),...r}:e.kind==="snapshot_delivery"?{phase:"delivery",listenerId:e.listenerId,service:"firestore",target:Xn(e.target),...r}:e.kind==="snapshot_suppressed"?{phase:"suppressed",listenerId:e.listenerId,service:"firestore",target:Xn(e.target),...r}:e.kind==="listener"?{phase:e.phase,listenerId:e.listenerId,service:I_(e.service),target:A_(e.target),...r,...tu(e.target)}:null}function kc(e){const t=$_();for(const n of e)t.append(n);return t.snapshot()}function $_(){const e=new Map;return{append:n=>{const r=O_(n);if(r===null)return;if(r.phase==="attach"){const d={id:r.listenerId,service:r.service,target:r.target,actor:r.actor,authLens:r.authLens,attachedAt:n.at,deliveryCount:0,suppressedCount:0};r.owners!==void 0&&(d.owners=[...r.owners]),r.query!==void 0&&(d.query=r.query);const p=n.activity?.listenerId;typeof p=="string"&&(d.clientListenerId=p),e.set(r.listenerId,d);return}const o=e.get(r.listenerId);if(o===void 0)return;if(r.phase==="delivery"){o.deliveryCount+=1,o.lastDeliveryAt=n.at,r.owners!==void 0&&(o.owners=P_(o.owners,r.owners));return}if(r.phase==="suppressed"){o.suppressedCount+=1;return}e.delete(r.listenerId)},snapshot:()=>Object.freeze([...e.values()].map(n=>Object.freeze({...n}))),clear:()=>e.clear()}}function P_(e,t){const n=t.filter(s=>s.kind==="regions");return n.length===0?[...e??[]]:[...(e??[]).filter(s=>s.kind!=="regions"),...n]}function D_(e,t){return typeof e=="string"?e.startsWith(t):e.collection.startsWith(t)}const Ec=Symbol("pyric/auth/target"),T_=Symbol("pyric.user.internal");function Z(e,t){return new G(e,`Firebase: ${t} (${e}).`)}const yp={PASSWORD:"password"},ao={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Ri{providerId;signInMethod;constructor(t,n){this.providerId=t,this.signInMethod=n}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(t){const n=typeof t=="string"?M_(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===yp.PASSWORD){const i=typeof n.email=="string"?n.email:"",o=typeof n.password=="string"?n.password:"";return new L_(i,o,s)}return new Ri(r,s)}}function M_(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class L_ extends Ri{email;secret;constructor(t,n,r=ao.EMAIL_PASSWORD){super(yp.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===ao.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===ao.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Ni extends Ri{idToken;accessToken;secret;constructor(t,n,r={}){super(t,n),this.idToken=r.idToken,this.accessToken=r.accessToken,this.secret=r.secret}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,idToken:this.idToken,accessToken:this.accessToken,secret:this.secret}}}function jc(e,t){return t?new Ni(e,e):null}class xn{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=xn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return jc(xn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Ni(xn.PROVIDER_ID,xn.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class _n{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=_n.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return jc(_n.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Ni(_n.PROVIDER_ID,_n.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class Sn{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=Sn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return jc(Sn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Ni(Sn.PROVIDER_ID,Sn.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const Cc=[xn.PROVIDER_ID,"apple.com",_n.PROVIDER_ID,Sn.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];new Set(Cc);function Rc(e,t=!1){const n=e[Ec];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class U_{mockResults=new Map;resolver=null;redirectResult=null;setMockResult(t,n){this.mockResults.set(t,n)}consumeMockResult(t){const n=this.mockResults.get(t);return n&&this.mockResults.delete(t),n}setResolver(t){this.resolver=t}getResolver(){return this.resolver}setRedirectResult(t){this.redirectResult=t}takeRedirectResult(){const t=this.redirectResult;return this.redirectResult=null,t}actionCodes=new Map;nextCodeSerial=1;outbox=[];mailResolver=null;mintActionCode(t){const n=`sandbox-oob-${this.nextCodeSerial++}`;return this.actionCodes.set(n,t),n}stageActionCode(t,n){this.actionCodes.set(t,n)}peekActionCode(t){return this.actionCodes.get(t)}consumeActionCode(t){const n=this.actionCodes.get(t);return n&&this.actionCodes.delete(t),n}setMailResolver(t){this.mailResolver=t}deliverMail(t){if(this.outbox.push(t),this.mailResolver)try{this.mailResolver.deliver(t)}catch{}}takeMail(t){const n=t===void 0?this.outbox.length>0?0:-1:this.outbox.findIndex(r=>r.email.toLowerCase()===t.toLowerCase());return n<0?null:this.outbox.splice(n,1)[0]??null}listMail(){return[...this.outbox]}}function B_(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Yt(e){if(typeof e!="string"||e.length===0)throw Z("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw Z("auth/invalid-email","Error")}function Zn(e){if(typeof e!="string"||e.length<6)throw Z("auth/weak-password","Password should be at least 6 characters")}function gp(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1}}}const F_=2166136261,q_=2654435769,V_=16777619;function nu(e,t){let n=t;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,V_);return n>>>0}function ru(e){return e.toString(16).padStart(8,"0")}function W_(e){const t=new TextEncoder().encode(e),n=new TextEncoder().encode([...e].reverse().join("")),r=nu(t,F_),s=nu(n,q_);return ru(r)+ru(s)}function z_(e){const t=Number.parseInt(e.slice(0,8),16),n=Number.parseInt(e.slice(8,16),16),r=t%360,s=40+n%80,i=(r+s)%360,o=60+t%16,a=45+n%16;return{hueStart:r,hueEnd:i,saturation:o,lightness:a}}function su(e){const n=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)[Symbol.iterator]().next();if(!n.done)return n.value.segment}function H_(e){const t=e.displayName?.trim();if(t){const r=su(t);if(r)return r.toUpperCase()}const n=e.email?.split("@")[0]?.trim();if(n){const r=su(n);if(r)return r.toUpperCase()}}function K_(e){return encodeURIComponent(e).replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}function G_(e){const t=W_(e.uid),{hueStart:n,hueEnd:r,saturation:s,lightness:i}=z_(t),o=`g${t}`,a=H_(e),l=e.pending===!0,u=a===void 0?"":`<text x="64" y="64" font-family="system-ui, -apple-system, sans-serif" font-size="56" fill="#fff" fill-opacity="${l?"0.55":"0.9"}" text-anchor="middle" dominant-baseline="central">${a}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><defs><linearGradient id="${o}" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="hsl(${n},${s}%,${i}%)"/><stop offset="100%" stop-color="hsl(${r},${s}%,${i}%)"/></linearGradient></defs><rect width="128" height="128" fill="url(#${o})"/>${u}${l?'<circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.25" stroke-width="6"/><circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.95" stroke-width="6" stroke-linecap="round" stroke-dasharray="44 308"><animateTransform attributeName="transform" type="rotate" from="0 64 64" to="360 64 64" dur="1s" repeatCount="indefinite"/></circle>':""}</svg>`}function J_(e){return`data:image/svg+xml,${K_(G_(e))}`}const Y_=e=>J_(e),bp="(default)";function wp(e){return`${e}-default-rtdb`}function vp(e,t){return t!==void 0&&t.length>0&&(e===t||e===wp(t))}function xp(e){const t=Q_(e,"Invalid Firebase Database URL");if(t.path!=="/")throw ti("Database URL must point to the root of a Firebase Database (not including a child path).");return t.instance}function Q_(e,t){const n=eS(e);if(n.domain==="firebase.com")throw ti(`${n.host} is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`);const r=n.namespace;if((!r||r==="undefined")&&n.domain!=="localhost")throw ti("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");const s=n.host.toLowerCase(),i=n.pathSegments.length===0?"/":`/${n.pathSegments.join("/")}`;if(s.length===0||!oS(r)&&s.split(":")[0]!=="localhost"||!aS(i))throw new Error(`${t} failed: url argument must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);const o=r!==n.subdomain?`?ns=${r}`:"";return{instance:{name:r,url:`${n.secure?"https://":"http://"}${s}/${o}`},host:s,path:i}}function Nc(e){if(!rS.test(e))throw ti("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");return xp(`${e}.firebaseio.com`)}function X_(e){if(e===void 0)return;const t=e.trim();if(!(t===""||t.toLowerCase()==="default"))return/^[^./:?#]+$/.test(t)?Nc(t):xp(e)}function sa(e,t){return e===void 0?t??bp:e.name}function Z_(e){const t=new Map;return{defaultKey:sa(void 0,e.defaultName),keyOf:r=>sa(r,e.defaultName),getOrCreate(r){let s=t.get(r);return s===void 0&&(s=e.create(r),t.set(r,s)),s},get:r=>t.get(r),delete:r=>t.delete(r),entries:()=>t.entries()}}function eS(e){let t=e,n="",r="",s="",i="",o=[],a=!0,l="https",u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),n=t.substring(0,Math.min(d,h)),d<h&&(o=tS(t.substring(d,h)));const f=nS(t.substring(Math.min(t.length,h)));u=n.indexOf(":"),u>=0?a=l==="https"||l==="wss":u=n.length;const p=n.slice(0,u);if(p.toLowerCase()==="localhost")r="localhost";else if(p.split(".").length<=2)r=p;else{const m=n.indexOf(".");s=n.substring(0,m).toLowerCase(),r=n.substring(m+1),i=s}return Object.prototype.hasOwnProperty.call(f,"ns")&&(i=f.ns),{host:n,domain:r,subdomain:s,secure:a,pathSegments:o,namespace:i}}function tS(e){const t=[];for(const n of e.split("/")){if(n.length===0)continue;let r=n;try{r=decodeURIComponent(n.replace(/\+/g," "))}catch{}t.push(r)}return t}function nS(e){const t={};e.charAt(0)==="?"&&(e=e.substring(1));for(const n of e.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2&&(t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]))}return t}const rS=/^[A-Za-z0-9][A-Za-z0-9-]*$/,sS=/[[\].#$/\u0000-\u001F\u007F]/,iS=/[[\].#$\u0000-\u001F\u007F]/;function oS(e){return e.length!==0&&!sS.test(e)}function aS(e){const t=e.replace(/^\/*\.info(\/|$)/,"/");return t.length!==0&&!iS.test(t)}function ti(e){return new Error(`FIREBASE FATAL ERROR: ${e} `)}const cS=new Set(["__proto__","prototype","constructor"]);function q(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(cS.has(n))throw new Error(`Invalid RTDB path segment '${n}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a path.`);return t}function Q(e){return e.length===0?"/":"/"+e.join("/")}function Tt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Tt(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Tt(r);return t}function ia(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function on(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,i)=>on(s,t[i]));if(!ia(e)||!ia(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&on(e[s],t[s]))}class lS{root={};snapshot(){return Tt(this.root)}restore(t){this.root=Tt(t)}read(t){const n=q(t);if(n.length>0&&n[0]===".info")return n.length===1?{connected:!0,serverTimeOffset:0}:n[1]==="connected"?!0:n[1]==="serverTimeOffset"?0:null;let s=this.root;for(const i of n){if(s===null||typeof s!="object"||Array.isArray(s))return null;const o=s;if(!Object.hasOwn(o,i))return null;s=o[i]}return ia(s)&&Object.keys(s).length===0?null:Tt(s)}write(t,n){const r=q(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Tt(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let a=0;a<r.length-1;a++){const l=r[a],u=Object.hasOwn(i,l)?i[l]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[l]=d,i=d}else i=u}const o=r[r.length-1];return n===null?(delete i[o],this.trim(r)):i[o]=Tt(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,o])=>({path:Q(q(i)),value:o}));for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){const a=r[i].path,l=r[o].path;if(a===l)throw new Error(`multi-path update: duplicate path '${a}'.`);const u=a==="/"?"/":a+"/",d=l==="/"?"/":l+"/";if(a!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${a}'.`);if(l!=="/"&&a.startsWith(d))throw new Error(`multi-path update: '${a}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:o}of r){const a=this.write(i,o);s.push({path:i,prior:a})}return s}shallowUpdate(t,n){const r=[],s=q(t);for(const[i,o]of Object.entries(n)){const a=[...s,...q(i)],l=Q(a),u=this.write(l,o);r.push({path:l,prior:u})}return r}trim(t){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=t.length-1;n>=1;n--){const r=t.slice(0,n),s=t[n-1];let i=this.root;for(let a=0;a<r.length-1;a++){const l=i[r[a]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const o=i[s];if(o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.keys(o).length===0){delete i[s];continue}return}}}const uS="12.13.0";function oa(e){return e.split("/").find(t=>t.length>0)===".info"}function dS(e,t){if(oa(t))throw new Error(`${e} failed = Can't modify data under /.info/`)}function fS(){const e=new Error("INVALID_PARAMETERS: Invalid token in path");return e.code="INVALID_PARAMETERS",e}const hS=/[[\].#$/\u0000-\u001F\u007F]/;function pS(e,t=q){for(const r of Object.keys(e)){const s=t(r);s.forEach((i,o)=>{if(!(i===".priority"&&o===s.length-1)&&(i.length===0||hS.test(i)))throw new Error(`update failed: values argument contains an invalid key (${i}) in path /${s.join("/")}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)})}const n=Object.keys(e).map(r=>`/${t(r).join("/")}`);for(let r=0;r<n.length;r++)for(let s=r+1;s<n.length;s++){const i=n[r],o=n[s],[a,l]=i.length<=o.length?[i,o]:[o,i];if(a===l||a==="/"||l.startsWith(`${a}/`))throw new Error(`update failed: values argument contains a path ${a} that is ancestor of another path ${l}`)}}function mS(e,t){const n=typeof e=="string",r=n?e.replace(/^\/*\.info(\/|$)/,"/"):"",s=n&&e.length===0,i=/[.#$[\]\u0000-\u001F\u007F]/.test(r);if(!n||s||i)throw new Error(`child failed: path argument was an invalid path = "${e}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)}const yS=/[\[\].#$/\u0000-\u001F\u007F]/;function gS(e){return e.length!==0&&!yS.test(e)}function bS(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function wS(e){return e.length===0?"":`in property '${e.join(".")}'`}function Ir(e,t){return`${e} failed: ${t} argument `}const vS="transaction failed: Data returned ";function _p(e,t,n=Ir("set","value")){Sp(e,q(t),n)}function Sp(e,t,n){const r=wS(t);if(e===void 0)throw new Error(`${n}contains undefined ${r}`);if(typeof e=="function")throw new Error(`${n}contains a function ${r} with contents = ${String(e)}`);if(bS(e))throw new Error(`${n}contains ${String(e)} ${r}`);if(e===null||typeof e!="object")return;let s=!1,i=!1;for(const[o,a]of Object.entries(e)){if(o===".value")s=!0;else if(o!==".priority"&&o!==".sv"&&(i=!0,!gS(o)))throw new Error(`${n} contains an invalid key (${o}) ${r}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);Sp(a,[...t,o],n)}if(s&&i)throw new Error(`${n} contains ".value" child ${r} in addition to actual children.`)}function Zt(e,t,n=Ir("set","value")){return _p(e,t,n),yr(e)}function yr(e){if(e==null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=yr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(Object.hasOwn(e,".value"))return yr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;if(n===".sv"){t[n]=r;continue}const s=yr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function xS(e){const t=[],n=(r,s)=>{if(r===null||typeof r!="object")return;const i=!Array.isArray(r);if(i&&Object.hasOwn(r,".priority")){const o=r[".priority"],a=typeof o=="object"&&o!==null&&".sv"in o;if(o!==null&&typeof o!="string"&&typeof o!="number"&&!a)throw new Error(`Firebase Database (${uS}) INTERNAL ASSERT FAILED: Invalid priority type found: ${typeof o}`);a||t.push({segments:s,priority:o})}if(i&&Object.hasOwn(r,".value")){n(r[".value"],s);return}for(const[o,a]of Object.entries(r))o.startsWith(".")||n(a,[...s,o])};return n(e,[]),t}function en(e,t){const n=xS(e),r=n.find(s=>s.segments.length===0);return{priority:r?r.priority:t,inline:r!==void 0,nested:n.filter(s=>s.segments.length>0)}}function iu(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,".priority":t}:{".value":e,".priority":t}}function ft(e,t){const n=t.filter(s=>s.priority!==null);if(n.length===0||e===null)return e;let r=structuredClone(e);for(const{segments:s,priority:i}of n){if(s.length===0){r=iu(r,i);continue}let o=r;for(const u of s.slice(0,-1))o=typeof o=="object"&&o!==null&&!Object.hasOwn(o,".value")?o[u]:void 0;const a=s[s.length-1];if(typeof o!="object"||o===null||!Object.hasOwn(o,a))continue;const l=o;l[a]!==null&&(l[a]=iu(l[a],i))}return r}function _S(e,t=null){const n=en(e,t),r=yr(e);return ft(r,[{segments:[],priority:n.priority},...n.nested])}function aa(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>aa(n));const t={};for(const[n,r]of Object.entries(e))t[n]=aa(r);return kS(t)??t}const SS=/^(0|[1-9]\d*)$/;function kS(e){const t=Object.keys(e);if(t.length===0)return null;let n=0;for(const s of t){if(!SS.test(s))return null;n=Math.max(n,Number(s))}if(n>=2*t.length)return null;const r=[];for(const s of t)r[Number(s)]=e[s];return r}function kp(e){return"/"+e.split("/").filter(Boolean).join("/")}function ou(e,t){return new Error(`Index not defined, add ".indexOn": "${t}", for path "${kp(e)}", to the rules`)}function ES(e){return e.limit===null&&e.bounds.length===0}function jS(e,t){return`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "${t}" at ${kp(e)} to your security rules for better performance.`}function CS(e){console.warn(`[${new Date().toISOString()}] @firebase/database:`,`FIREBASE WARNING: ${e} `)}function RS(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class NS{version=0;activeVersions=[];mutations=[];get entries(){return this.mutations}get currentVersion(){return this.version}begin(){const t=this.version;return this.activeVersions.push(t),t}mark(t="/"){this.version+=1,this.activeVersions.length>0&&this.mutations.push({version:this.version,paths:(Array.isArray(t)?t:[t]).map(n=>Q(q(n)))})}conflictsSince(t,n){const r=Q(q(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>RS(r,i)))}release(t){const n=this.activeVersions.lastIndexOf(t);if(n>=0&&this.activeVersions.splice(n,1),this.activeVersions.length===0){this.mutations.length=0;return}const r=Math.min(...this.activeVersions),s=this.mutations.findIndex(i=>i.version>r);s<0?this.mutations.length=0:s>0&&this.mutations.splice(0,s)}}function Ze(e){return e==="unsupported"?"unsupported":"deny"}function Pn(e){const t={engine:"rtdb",matchedPath:e.matchedPath,matchedRule:e.matchedRule,pathVariableBindings:e.pathVariableBindings,reason:e.reason,errorCode:e.errorCode};return e.trace!==void 0&&(t.rtdbTrace=e.trace),t}function $e(e,t,n,r,s={}){const i={method:n,path:ht(r)};return s.data!==void 0&&(i.data=structuredClone(s.data)),s.query!==void 0&&(i.query=structuredClone(s.query)),{...Object.fromEntries(Object.entries(Pn(e)).filter(([,a])=>a!==void 0)),engine:"rtdb",auth:t===null?null:structuredClone(t),reasons:[...e.reasons],request:i}}function ht(e){return Q(q(e))}class IS{sandbox;nextId=0;instanceField;constructor(t,n){this.sandbox=t,this.instanceField=n===void 0?{}:{instance:n}}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(t){return this.nextId+=1,`rtdb-${t}-${this.nextId.toString(36)}`}mutation(t,n,r,s={}){if(this.sandbox)try{dt(this.sandbox,Ln({at:De(this.sandbox).now(),service:"rtdb",...this.instanceField,op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,o={}){if(this.sandbox)try{let a;i&&(a=Pn(i));let l="user";o.origin&&(l=o.origin);let u=o.at;u===void 0&&(u=De(this.sandbox).now()),dt(this.sandbox,Ch({service:"rtdb",...this.instanceField,method:n,path:ht(r),auth:t,result:s,origin:l,durationMs:o.durationMs,reasons:i?.reasons,rules:a,request:o.request,resourceBefore:o.resourceBefore,resourceAfter:o.resourceAfter,groupId:o.groupId,groupKind:o.groupKind,triggeredBy:o.triggeredBy,detail:o.detail,at:u}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{dt(this.sandbox,vw({at:De(this.sandbox).now(),service:"rtdb",...this.instanceField,method:n,path:ht(r),auth:t,data:s.data,priorState:s.priorState,nextState:s.nextState,groupId:s.groupId,groupKind:s.groupKind,replay:s.replay,detail:s.detail}),{service:"rtdb"})}catch{}}listener(t,n,r,s={}){if(this.sandbox)try{let i="value";s.event&&(i=s.event),dt(this.sandbox,xw({at:De(this.sandbox).now(),service:"rtdb",...this.instanceField,phase:t,listenerId:n.id,target:{kind:i,path:ht(n.path),...s.query===void 0?{}:{query:s.query}},auth:r,result:s.result,size:s.size,sample:s.sample,reason:s.reason,error:s.error,triggeredBy:s.triggeredBy,detail:s.detail,reasons:s.reasons,rules:s.rules,owners:s.owners}),{service:"rtdb"})}catch{}}}class AS{values=new Map;get(t){return this.values.get(Q(q(t)))??null}forChild(t){const n=q(t);return r=>this.get(Q([...n,r]))}atOrBelow(t){const n=Q(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of this.values)(i===n||i.startsWith(r))&&(s[i]=o);return s}clear(){this.values.clear()}clearAtOrBelow(t){const n=Q(q(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n,r){if(this.clearAtOrBelow(t),n!==null){this.values.set(Q(q(t)),n);return}r&&this.pruneMissingAncestors(t,r)}set(t,n){const r=Q(q(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=Q(q(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t,n){for(const r of t)this.clearAtOrBelow(r.path),r.value===null&&n&&this.pruneMissingAncestors(r.path,n)}pruneMissingAncestors(t,n){const r=q(t);for(let s=r.length-1;s>=0;s-=1){const i=Q(r.slice(0,s));if(n(i))break;this.values.delete(i)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(Q(q(n)),r)}}function Mt(e){if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("priority must be a valid Firebase priority (string, finite number, or null)")}const Bn=(...e)=>new Set(["Error",...e]),Ar=Bn("Boolean"),OS=Bn("Boolean","Number","String","Null","NullableSnapshot","Value","Auth","QueryValue","Mixed"),$S=Bn("Number","String","Value","Auth","QueryValue","Mixed"),PS=Bn("Number","String","Value","Auth","QueryValue","Mixed"),Ep=Bn("Number","Value","Auth","QueryValue","Mixed"),Ic=Bn("String","Value","Auth","Mixed"),au=new Set(["String","Value","Auth"]),cu=new Set(["Snapshot","NullableSnapshot","Null"]);function DS(e,t){return e===t?e:cu.has(e)&&cu.has(t)?"NullableSnapshot":au.has(e)||au.has(t)?"Value":"Mixed"}function ue(e,t){return{code:e,message:t}}function TS(e){switch(e){case"==":case"===":case"!=":case"!==":return OS;case"<":case"<=":case">":case">=":case"+":return $S;default:return Ep}}function MS(e,t,n){return e!=="+"&&e!=="-"&&e!=="*"&&e!=="/"&&e!=="%"?"Boolean":t==="Error"||n==="Error"?"Error":e!=="+"?"Number":t==="String"||n==="String"?"String":t==="Number"&&n==="Number"?"Number":"Value"}const pt=e=>ue("INVALID_ARGUMENT",e);function bt(e){return{returns:e,check:(t,n)=>n.length===0?null:pt(dn(t,0))}}function gr(e){return{returns:e,check(t,n){return n.length!==1?pt(dn(t,1)):Ic.has(n[0].type)?null:pt(ip(t))}}}const LS={returns:"Boolean",check(e,t){if(t.length===0)return null;if(t.length>1)return pt(op);const n=t[0];return n.type==="Error"?null:n.type!=="Array"?pt(ap):(n.elements??[]).every(r=>Ic.has(r))?null:pt(cp)}},US={returns:"String",check(e,t){if(t.length!==2)return pt(dn(e,2));const n=t.findIndex(r=>!Ic.has(r.type));return n===-1?null:pt(na(n===0?1:2))}},BS={returns:"Boolean",check(e,t){if(t.length!==1)return pt(dn(e,1));const n=t[0].type;return n==="Regex"||n==="Error"?null:pt(lp)}},FS=new Map([["val",bt("Value")],["exists",bt("Boolean")],["isString",bt("Boolean")],["isNumber",bt("Boolean")],["isBoolean",bt("Boolean")],["parent",bt("Snapshot")],["getPriority",bt("Value")],["child",gr("Snapshot")],["hasChild",gr("Boolean")],["hasChildren",LS]]),lu=new Map([["contains",gr("Boolean")],["beginsWith",gr("Boolean")],["endsWith",gr("Boolean")],["replace",US],["toLowerCase",bt("String")],["toUpperCase",bt("String")],["matches",BS]]),qS=new Map([["orderByKey","Boolean"],["orderByValue","Boolean"],["orderByPriority","Boolean"],["orderByChild","QueryValue"],["startAt","QueryValue"],["endAt","QueryValue"],["equalTo","QueryValue"],["limitToFirst","QueryValue"],["limitToLast","QueryValue"]]),VS="Invalid property access: target is not an object.";function jp(e,t){const n=()=>({kind:"error",error:ue("NO_SUCH_MEMBER",`No such method/property '${t}'.`)});switch(e){case"Error":return{kind:"error",error:null};case"Snapshot":case"NullableSnapshot":{const r=FS.get(t);return r?{kind:"method",method:r}:n()}case"String":case"Value":{const r=lu.get(t);return r?{kind:"method",method:r}:t==="length"?{kind:"property",type:"Number"}:n()}case"Auth":{const r=lu.get(t);return r?{kind:"method",method:r}:{kind:"property",type:"Auth"}}case"Query":{const r=qS.get(t);return r?{kind:"property",type:r}:n()}default:return{kind:"error",error:ue("NOT_AN_OBJECT",VS)}}}const WS=new Map([["auth","Auth"],["data","Snapshot"],["newData","Snapshot"],["root","Snapshot"],["now","Number"],["query","Query"]]),wt={type:"Error"},Ce=e=>({type:e});function he(e,t){return e.errors.push(t),wt}function Re(e,t){return t.type!=="Array"?t.type:(he(e,ue("UNEXPECTED_ARRAY","Unexpected array literal.")),"Error")}function ke(e,t){return e.typeOf(t)}function Be(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,ke(e,r)),o=Re(r,ke(n,r)),a=TS(s);return a.has(i)?a.has(o)?Ce(MS(s,i,o)):he(r,ue("INVALID_OPERAND",Zs(s,"right"))):he(r,ue("INVALID_OPERAND",Zs(s,"left")))}function uu(e,t,n){const r=this.args.ctx;let s=Re(r,ke(e,r));return n.children.forEach((i,o)=>{const a=t.children[o].sourceString,l=Re(r,ke(i,r));Ar.has(s)?Ar.has(l)?s=s==="Error"||l==="Error"?"Error":"Boolean":s=he(r,ue("INVALID_OPERAND",`Right operand of ${a} must be boolean.`)).type:s=he(r,ue("INVALID_OPERAND",`Left operand of ${a} must be boolean.`)).type}),Ce(s)}function du(e,t,n){const r=jp(Re(e,t),n);return r.kind==="error"?r.error?he(e,r.error):wt:Ce(r.kind==="method"?"SnapshotMethod":r.type)}let co;function zS(){if(co)return co;const e=rs();return e.addOperation("literalString",{_nonterminal(...t){return t.length===1?t[0].literalString():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalString()},string(t){return Nr(this.sourceString)}}),e.addOperation("typeOf(ctx)",{_nonterminal(...t){return t.length===1?ke(t[0],this.args.ctx):wt},_iter(){return wt},_terminal(){return wt},Ternary_ternary(t,n,r,s,i){const o=this.args.ctx,a=Re(o,ke(t,o)),l=Re(o,ke(r,o)),u=Re(o,ke(i,o));return Ar.has(a)?l==="Error"||u==="Error"?wt:Ce(DS(l,u)):he(o,ue("INVALID_OPERAND","condition of ? must be boolean."))},LogicalAnd_and:uu,LogicalOr_or:uu,Equality_strictEq:Be,Equality_strictNeq:Be,Comparison_gte:Be,Comparison_lte:Be,Comparison_gt:Be,Comparison_lt:Be,Equality_looseEq:Be,Equality_looseNeq:Be,Additive_add:Be,Additive_sub:Be,Multiplicative_mul:Be,Multiplicative_div:Be,Multiplicative_mod:Be,UnaryExpr_not(t,n){const r=this.args.ctx,s=Re(r,ke(n,r));return Ar.has(s)?Ce(s==="Error"?"Error":"Boolean"):he(r,ue("INVALID_OPERAND","! only operates on booleans."))},UnaryExpr_neg(t,n){const r=this.args.ctx,s=Re(r,ke(n,r));return Ep.has(s)?Ce(s==="Error"?"Error":"Number"):he(r,ue("INVALID_OPERAND","- only operates on numbers."))},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx,l=Re(a,ke(t,a)),u=i.asIteration().children.map(m=>ke(m,a)),d=r.sourceString,h=jp(l,d);if(h.kind==="error")return h.error?he(a,h.error):wt;if(h.kind==="property")return he(a,ue("NOT_A_FUNCTION","Type error: Function call on target that is not a function."));const f=u.map(m=>d==="hasChildren"?m:Ce(Re(a,m)));if(f.some(m=>m.type==="Error"))return wt;const p=h.method.check(d,f);return p?he(a,p):Ce(h.method.returns)},CallExpr_memberAccess(t,n,r){const s=this.args.ctx;return du(s,ke(t,s),r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=this.args.ctx,o=ke(t,i),a=r.literalString();if(a!==void 0)return du(i,o,a);const l=Re(i,o),u=Re(i,ke(r,i));return l==="Error"||u==="Error"?wt:l==="Auth"?PS.has(u)?Ce("Auth"):he(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access on 'auth' object.")):he(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access."))},Primary_paren(t,n,r){return ke(n,this.args.ctx)},Array(t,n,r){const s=this.args.ctx;return{type:"Array",elements:n.asIteration().children.map(a=>Re(s,ke(a,s)))}},number(t){return Ce("Number")},string(t){return Rr(this.sourceString)?he(this.args.ctx,ue("PARSE_ERROR",Xs)):Ce("String")},regex(t,n,r,s){const i=hp(n.sourceString);return i!==null?he(this.args.ctx,ue("INVALID_REGEX",i)):_c(s.sourceString)?Ce("Regex"):he(this.args.ctx,ue("INVALID_REGEX",up))},bool(t){return Ce("Boolean")},null(t){return Ce("Null")},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$")return s.pathVars.has(i.slice(1))?Ce("String"):he(s,ue("UNKNOWN_IDENTIFIER",Hl(i)));if(i==="newData"&&s.context==="read")return he(s,ue("NEWDATA_IN_READ","newData is invalid in .read expressions."));const o=WS.get(i);return o?Ce(o):he(s,ue("UNKNOWN_IDENTIFIER",Hl(i)))}}),co=e,e}function HS(e,t,n=[]){const r=ns(e);if(!r.ok)return[];const{match:s}=r,i={errors:[],context:t,pathVars:new Set(n.map(a=>a.startsWith("$")?a.slice(1):a))};let o;try{o=Re(i,zS()(s).typeOf(i))}catch(a){if(a instanceof RangeError)return[ue("PARSE_ERROR",ts)];throw a}return Ar.has(o)||he(i,ue("NOT_BOOLEAN","Expression must evaluate to a boolean.")),i.errors}const KS=/[.#$\[\]\u0000-\u001f\u007f]/,GS="Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).",JS="Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.",YS="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.",QS="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().";function XS(e){const t=String(e);if(t==="$key"||t==="$priority"||t==="$value"){const n=t==="$key"?"orderByKey":t==="$priority"?"orderByPriority":"orderByValue";throw new Error(`orderByChild: "${t}" is invalid. Use ${n}() instead.`)}if(typeof e!="string"||e.length===0||KS.test(e))throw new Error(`orderByChild failed: path argument was an invalid path = "${t}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)}function ZS(e){return e!==null&&typeof e=="object"&&Object.keys(e).length===1&&typeof e[".sv"]=="string"}function ek(e,t="/"){if(e.orderBy?.kind==="child"&&e.orderBy.path.split("/").filter(Boolean).length===0)throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");for(const n of e.bounds){const r=n.value;switch(_p(r,t,Ir(n.kind,"value")),e.orderBy?.kind??"priority"){case"key":if(typeof r!="string")throw new Error(YS);if(n.key!==void 0)throw new Error(QS);break;case"priority":if(r!==null&&typeof r!="string"&&!(typeof r=="number"&&Number.isFinite(r))&&!ZS(r))throw new Error(GS);break;case"child":case"value":if(r!==null&&typeof r=="object")throw new Error(JS);break}}}function Or(e){try{return e(),null}catch(t){return t instanceof Error?t.message:String(t)}}const Cp=Rn({orderByChild:Ee().nullable().optional(),orderByKey:Pt().nullable().optional(),orderByValue:Pt().nullable().optional(),orderByPriority:Pt().nullable().optional(),equalTo:Ms([Ee(),vn(),Pt(),Ls()]).optional(),limitToFirst:vn().nullable().optional(),limitToLast:vn().nullable().optional(),startAt:Ms([Ee(),vn(),Pt(),Ls()]).optional(),endAt:Ms([Ee(),vn(),Pt(),Ls()]).optional()});function tk(e){return e.orderByChild!=null?{kind:"child",path:e.orderByChild}:e.orderByKey===!0?{kind:"key"}:e.orderByValue===!0?{kind:"value"}:e.orderByPriority===!0?{kind:"priority"}:null}function nk(e){return[["startAt",e.startAt],["endAt",e.endAt],["equalTo",e.equalTo]].flatMap(([n,r])=>r==null?[]:[{kind:n,value:r}])}function Rp(e){const t=Cp.strict().safeParse(e);if(!t.success)return`query is not a Realtime Database query: ${t.error.issues.map(o=>o.message).join("; ")}`;const n=t.data,r=n.orderByChild,s=r==null?null:Or(()=>XS(r));if(s!==null)return s;if(n.orderByChild!=null&&n.orderByChild.split("/").filter(Boolean).length===0)return"orderByChild: cannot pass in empty path. Use orderByValue() instead.";if([n.orderByChild!=null,n.orderByKey===!0,n.orderByValue===!0,n.orderByPriority===!0].filter(Boolean).length>1)return"query names more than one of orderByChild, orderByKey and orderByValue.";if(n.equalTo!==void 0&&n.startAt!==void 0)return"equalTo: Starting point was already set (by another call to startAt, startAfter, or equalTo).";if(n.equalTo!==void 0&&n.endAt!==void 0)return"equalTo: Ending point was already set (by another call to endAt, endBefore, or equalTo).";if(n.limitToFirst!=null&&n.limitToLast!=null)return"query names both limitToFirst and limitToLast.";for(const[o,a]of[["limitToFirst",n.limitToFirst],["limitToLast",n.limitToLast]])if(a!=null&&(!Number.isInteger(a)||a<=0))return`query.${o} must be a positive integer.`;return Or(()=>ek({orderBy:tk(n),bounds:nk(n),limit:null}))}const rk=Rn({operation:zs(["read","write","validate"]),path:Ee().min(1).startsWith("/"),auth:Ms([Rn({uid:Ee(),tenant:Ee().optional(),token:Ws(ps()).optional()}),Ls()]),mockData:Ws(ps()),newData:ps().optional(),updates:Rh(Rn({path:Ee().min(1).startsWith("/"),value:ps()})).optional(),query:Cp.optional(),now:vn().optional()});zs(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);const sk=Rn({path:Ee(),kind:zs(["read","write","validate"]),conditionText:Ee(),verdict:zs(["ALLOW","DENY","ERROR","UNSUPPORTED"]),message:Ee().optional(),pathVariableBindings:Ws(Ee()),instance:Ee().optional()});Rn({allowed:Pt(),unsupported:Pt().optional(),matchedPath:Ee(),matchedRule:Ee(),reason:Ee(),pathVariableBindings:Ws(Ee()),trace:Rh(sk)});const ik=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce","sub","firebase"];function fu(e){const t=ik.filter(r=>Object.prototype.hasOwnProperty.call(e,r));if(t.length===0)return;const n=t.length>1?`Developer claims "${t.join('", "')}" are reserved and cannot be specified.`:`Developer claim "${t[0]}" is reserved and cannot be specified.`;throw new G("auth/reserved-claim",n)}function ok(e){return{...e}}function ak(e){return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoUrl:e.photoUrl,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerIds:e.providerUserInfo.map(t=>t.providerId)}}const ck=new Set(["password","phone","anonymous"]);function Np(e,t,n,r){const s={},i={user_id:e},o={};if(t!==null){t.displayName!==null&&(s.name=t.displayName),t.photoUrl!==null&&(s.picture=t.photoUrl),t.isAnonymous&&(i.provider_id="anonymous"),t.email!==null&&(i.email=t.email,i.email_verified=t.emailVerified,o.email=[t.email]),t.phoneNumber!==null&&(i.phone_number=t.phoneNumber,o.phone=[t.phoneNumber]);for(const a of t.providerIds)ck.has(a)||(o[a]=[t.uid])}return{...s,...n,...i,firebase:{identities:o,sign_in_provider:r}}}function hu(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function lk(e,t,n=Date.now()){const r=Math.floor(n/1e3),s=Np(e,null,t,null),i=hu(t.firebase)??{},o=s.firebase,a=hu(i.identities)??o.identities,l={...i,identities:a};return{sub:e,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:r,iat:r,exp:r+3600,...s,...t,user_id:t.user_id??s.user_id,firebase:l}}function uk(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function dk(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function fk(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,".value")?e[".value"]:e}function ut(e,t,n){const r=fk(n);if(uk(e))return t;if(dk(e)){const o=e[".sv"].increment;return(typeof r=="number"?r:0)+o}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((o,a)=>ut(o,t,Array.isArray(r)?r[a]:void 0));let s;r!==null&&typeof r=="object"&&!Array.isArray(r)&&(s=r);const i={};for(const[o,a]of Object.entries(e)){const l=o===".value"?r:s?.[o];i[o]=ut(a,t,l)}return i}function ca(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ip(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function hk(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object"||!Object.hasOwn(n,r))return;n=n[r]}return n}function Ap(e,t,n,r){if(n===void 0)return null;const s=ut(n,r,hk(e,t));return _S(s)}const pu="\0__proto__";function ni(e,t,n){if(Array.isArray(e))return e.map(s=>ni(s,t,n));if(!ca(e))return e;const r={};for(const[s,i]of Object.entries(e))Ip(r,s===t?n:s,ni(i,t,n));return r}function pk(e,t,n,r){const s=ni(n,"__proto__",pu);return ni(Ap(e,t,s,r),pu,"__proto__")}function mk(e,t,n,r,s,i){if(!s||s.length===0)return la(e,n,Ap(e,t,r,i));let o=e;for(const a of s){const l=a.path.split("/").filter(Boolean);o=la(o,l,pk(e,a.path,a.value,i))}return o}function la(e,t,n){if(t.length===0)return n??null;const[r,...s]=t;if(!r)return e??null;const i=ca(e)&&Object.hasOwn(e,".value"),o=i?e[".value"]:e,a=ca(o);let l=null;a&&Object.hasOwn(o,r)&&(l=o[r]);const u=la(l,s,n);if(u==null){if(!a)return e??null;const h={...o};return delete h[r],Object.keys(h).some(p=>p!==".priority")?(i&&Object.hasOwn(e,".priority")&&(h[".priority"]=e[".priority"]),h):null}const d=a?{...o}:{};return Ip(d,r,u),i&&a&&Object.hasOwn(e,".priority")&&(d[".priority"]=e[".priority"]),d}function Op(e,t){try{const n=y_(e,t);return typeof n!="boolean"?{holds:!1,runtimeError:"Expression must evaluate to a boolean."}:{holds:n}}catch(n){if(n instanceof ne)return{holds:!1,runtimeError:n.message};throw n}}function ri(e,t,n,r,s){const i={path:e.path,kind:t,conditionText:n.raw,verdict:"UNSUPPORTED",pathVariableBindings:{...r}};if(s===void 0){const o=n.parsed.errors.map(a=>a.message).join("; ");i.message=o===""?"The simulator cannot evaluate this expression":`The simulator cannot evaluate this expression: ${o}`}else s.runtimeError!==void 0?(i.verdict="ERROR",i.message=s.runtimeError):i.verdict=s.holds?"ALLOW":"DENY";return i}function yk(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function gk(e,t){const n=Ei(e),r=lk(e.uid,n?.token??{},t),s={uid:e.uid,token:r},i=r.firebase,a=(typeof i=="object"&&i!==null?i:{}).sign_in_provider;return typeof a=="string"&&(s.provider=a),s}function mu(e,t,n,r,s,i,o,a){let l=null;const u=new Set;if(a&&a.length>0)for(const m of a)u.add(m.path.split("/").filter(Boolean).join("/"));else u.add(o.filter(Boolean).join("/"));const d=Array.from(u).map(m=>m.split("/").filter(Boolean));function h(m,g,b,w,x){if(b.exists()){const S=m.validate;if(S)if(!S.parsed.valid)i.push(ri(m,"validate",S,w,void 0)),l||(l={node:m,rule:S,bindings:w,unsupported:!0});else{const k=Op(S,s(g,b,w));if(i.push(ri(m,"validate",S,w,k)),!k.holds)return{node:m,rule:S,bindings:w,runtimeError:k.runtimeError}}}const _=d.some(S=>S.length<=x.length&&S.every((k,R)=>k===x[R]))?yk(b):f(x);for(const S of _){const k=Pp(m,S);if(k===void 0)continue;const R=k.variable===void 0?w:{...w,[k.variable]:S},O=h(k.child,g.child(S),b.child(S),R,[...x,S]);if(O)return O}return null}function f(m){const g=new Set;for(const b of d)b.length>m.length&&m.every((x,v)=>x===b[v])&&g.add(b[m.length]);return g}return h(e,t,n,r,[])??l}function $p(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;const i=Pp(e,t[0]);if(i===void 0)return s;const o=i.variable===void 0?{...n}:{...n,[i.variable]:t[0]};return s.push(...$p(i.child,t.slice(1),o,r+1)),s}function bk(e){const t=e.path.split("/").filter(Boolean);return t[t.length-1]}function Pp(e,t){let n;for(const r of e.children){const s=bk(r);if(s===void 0)continue;if(s===t)return{child:r};s.startsWith("$")&&n===void 0&&(n={child:r,variable:s})}return n}function yu(e,t){let n="Validation rule evaluated to false";return e.unsupported?n=`Validation rule at '${e.node.path}' contains an expression the simulator cannot evaluate: ${e.rule.raw}. It was not evaluated; production may reject this write.`:e.runtimeError!==void 0&&(n=`Validation rule at '${e.node.path}' failed at evaluation: ${e.runtimeError}`),{success:!0,data:{allowed:!1,unsupported:e.unsupported===!0,matchedPath:e.node.path,matchedRule:e.rule.raw,reason:n,pathVariableBindings:e.bindings,trace:t}}}function wk(e,t){const n=e==="read"?t:void 0,r=n?.equalTo??null;return{orderByChild:n?.orderByChild??null,orderByKey:n?.orderByKey===!0,orderByValue:n?.orderByValue===!0,orderByPriority:n?.orderByPriority===!0,equalTo:r,limitToFirst:n?.limitToFirst??null,limitToLast:n?.limitToLast??null,startAt:n?.startAt??r,endAt:n?.endAt??r}}class vk{execute(t,n){const r=rk.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const s=r.data.query===void 0?null:Rp(r.data.query);if(s!==null)return{success:!1,error:{code:"INVALID_INPUT",message:s,recoverable:!0}};const{operation:i,path:o,auth:a,mockData:l,newData:u,updates:d,query:h}=r.data,f=r.data.now??Date.now(),p=[];try{const m=o.split("/").filter(Boolean),g=t,b=$p(g,m,{}),w=new Ut(l,"/");let x=l;i!=="read"&&(x=mk(l,o,m,u,d,f));const v=new Ut(x,"/");let _=null;a&&(_=gk(a,f));const S=wk(i,h),k=($,C,N)=>{const I={...N};return{auth:_,data:$,newData:C,root:w,now:f,pathVariableBindings:I,query:S}};if(i==="validate"){const $=mu(g,w,v,{},k,p,m,d);if($)return yu($,p);const C=p[p.length-1],N=[...b].reverse().find(I=>I.node.validate!==void 0);return!C&&!N?{success:!1,error:{code:"NO_MATCHING_RULE",message:`No 'validate' rule found for path '${o}'`,recoverable:!0}}:{success:!0,data:{allowed:!0,matchedPath:C?.path??N.node.path,matchedRule:C?.conditionText??N.node.validate.raw,reason:"Validation rules evaluated to true",pathVariableBindings:C?.pathVariableBindings??N.pathVariableBindings,trace:p}}}let R;const O=new Map;for(const $ of b){const C=$.node[i];if(!C)continue;if(!C.parsed.valid){p.push(ri($.node,i,C,$.pathVariableBindings,void 0)),R||(R=$);continue}const N=m.slice(0,$.depth).join("/"),I=w.child(N),M=v.child(N),T=Op(C,k(I,M,$.pathVariableBindings));if(p.push(ri($.node,i,C,$.pathVariableBindings,T)),T.runtimeError!==void 0&&O.set($,T.runtimeError),T.holds){if(i==="write"){const F=mu(g,w,v,{},k,p,m,d);if(F)return yu(F,p)}return{success:!0,data:{allowed:!0,matchedPath:$.node.path,matchedRule:C.raw,reason:"Rule expression evaluated to true",pathVariableBindings:$.pathVariableBindings,trace:p}}}}if(R){const $=R.node[i];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:R.node.path,matchedRule:$.raw,reason:`'${i}' rule at '${R.node.path}' contains an expression the simulator cannot evaluate: ${$.raw} — not evaluated; production may reject or allow this ${i}.`,pathVariableBindings:R.pathVariableBindings,trace:p}}}const P=[...b].reverse().find($=>$.node[i]!==void 0);if(P===void 0)return{success:!0,data:{allowed:!1,matchedPath:"",matchedRule:"",reason:`No '${i}' rule on '${o}' or its ancestors grants access; denied by default`,pathVariableBindings:b[b.length-1].pathVariableBindings,trace:p}};const A=P.node[i],E=O.get(P),j=E===void 0?"evaluated to false":`failed at evaluation: ${E}`;return{success:!0,data:{allowed:!1,matchedPath:P.node.path,matchedRule:A.raw,reason:`No '${i}' rule grants access; the deepest, at '${P.node.path}', ${j}`,pathVariableBindings:P.pathVariableBindings,trace:p}}}catch(m){return{success:!1,error:{code:"EVALUATION_ERROR",message:m instanceof Error?m.message:String(m),recoverable:!1}}}}}function Dp(e,t,n=[]){try{const r=N_(e),s=r.valid?HS(e,t,n):r.errors,i=r.valid?__(e,t):[];return{raw:e,parsed:{...r,valid:r.valid&&s.length===0,errors:s,warnings:i}}}catch(r){if(!(r instanceof RangeError))throw r;return{raw:e,parsed:{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ts}],warnings:[],referencedIdentifiers:[]}}}}function Tp(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[o,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[o];if(l!==void 0)if(typeof l=="boolean"||typeof l=="string"||l===null)r[a]=Dp(String(l),a,n);else{const u=JSON.stringify(l)??String(l);r[a]={raw:u,parsed:{raw:u,valid:!1,errors:[],warnings:[],referencedIdentifiers:[]}}}}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);const i=Xh(t,e);i.length>0&&(r.structure=i);for(const[o,a]of Object.entries(e)){if(o.startsWith(".")||Ax.has(o)||typeof a!="object"||a===null||Array.isArray(a))continue;const l=t==="/"?`/${o}`:`${t}/${o}`,u=o.startsWith("$")?[...n,o]:[...n];r.children.push(Tp(a,l,u))}return r}function Ac(e){if(!e||typeof e!="object")throw new Error("Invalid rules JSON: expected an object");const t=e;if(!("rules"in t))throw new Error('Invalid rules JSON: missing top-level "rules" key');if(typeof t.rules!="object"||t.rules===null||Array.isArray(t.rules))throw new Error('Invalid rules JSON: "rules" must be an object');return Tp(t.rules,"/",[])}function lo(e){return e==="true"?!0:e==="false"?!1:e}function Mp(e){const t={};e.read&&(t[".read"]=lo(e.read.raw)),e.write&&(t[".write"]=lo(e.write.raw)),e.validate&&(t[".validate"]=lo(e.validate.raw)),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const n of e.children){const r=n.path.split("/").filter(Boolean);t[r[r.length-1]]=Mp(n)}return t}function xk(e){if(!e||typeof e!="object"||!("path"in e))throw new Error("Invalid compiled rules: expected a rules node with a 'path' property");return{rules:Mp(e)}}function Oc(e,t){return new vk().execute(e,t)}function _k(e,t){let n=[e];for(const r of t){const s=[];for(const i of n)for(const o of i.children){const a=o.path.split("/").filter(Boolean),l=a[a.length-1];l&&(l===r||l.startsWith("$"))&&s.push(o)}if(n=s,n.length===0)break}return n}function Lp(e,t,n){return _k(e,t).filter(r=>r.indexOn?.some(s=>s===n||s.split("/").filter(Boolean).join("/")===n))}function Sk(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:null}function kk(e){return e.kind==="value"?".value":e.path.split("/").filter(Boolean).join("/")}function Ek(e){const t={orderByKey:e.orderBy?.kind==="key",orderByValue:e.orderBy?.kind==="value",orderByPriority:e.orderBy?.kind==="priority"};e.orderBy?.kind==="child"&&(t.orderByChild=e.orderBy.path);for(const n of e.bounds){const r=Sk(n.value);n.kind==="equalTo"?t.equalTo=r:n.kind==="startAt"||n.kind==="startAfter"?t.startAt=r:(n.kind==="endAt"||n.kind==="endBefore")&&(t.endAt=r)}return e.limit?.kind==="limitToFirst"?t.limitToFirst=e.limit.n:e.limit?.kind==="limitToLast"&&(t.limitToLast=e.limit.n),t}function Ke(e){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",$c(t,e)}function $c(e,t){return Object.assign(e,{denialContext:t})}class jk{clock;compiled=null;defaultPolicy="deny";constructor(t=new Nh){this.clock=t}setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=Ac(t)}hasRules(){return this.compiled!==null}missingQueryIndex(t,n){if(this.compiled===null||n.orderBy===null||n.orderBy.kind==="key"||n.orderBy.kind==="priority")return null;const r=kk(n.orderBy);return Lp(this.compiled,t.split("/").filter(Boolean),r).length>0?null:r}check(t,n,r){return this.evaluate(t,n,r).check}evaluate(t,n,r){if(t==="read"){if(n==="/.info"||n===".info")return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith("/.info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith(".info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]}}if(this.compiled===null)return this.defaultPolicy==="deny"?{check:"no-rule",reasons:["No RTDB rules loaded; default deny."],errorCode:"NO_MATCHING_RULE",errorMessage:"No RTDB rules loaded; default deny."}:{check:"allow",reasons:["No RTDB rules loaded; default allow."]};let i=null;r.auth!==null&&(i={uid:r.auth.uid,token:r.auth.token??{}},r.auth.tenant!==void 0&&(i.tenant=r.auth.tenant));let o=r.query;o===void 0&&r.querySpec!==void 0&&(o=Ek(r.querySpec));const a=Oc(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates,query:o,now:r.now??this.clock.now()});return a.success?a.data.unsupported?{check:"unsupported",reasons:[`${a.data.matchedPath} ${t} UNSUPPORTED: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings,trace:a.data.trace}:{check:a.data.allowed?"allow":"deny",reasons:[`${a.data.matchedPath} ${t} ${a.data.allowed?"ALLOW":"DENY"}: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings,trace:a.data.trace}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class Ck{tree=new lS;rules;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new AS;mutations=new NS;events;writeSubscribers=new Set;resetGeneration=0;clock;constructor(t,n){this.events=new IS(t,n),this.clock=t?De(t):new Nh,this.rules=new jk(this.clock)}rulesSnapshot(){const t=[...this.priorities.entries()].map(([n,r])=>({segments:q(n),priority:r}));return ft(this.tree.snapshot(),t)}prioritiesBelow(t){const n=q(t),r=[];for(const[s,i]of this.priorities.entries()){const o=q(s);o.length>n.length&&n.every((l,u)=>o[u]===l)&&r.push({segments:o.slice(n.length),priority:i})}return r}unspecifiedIndexWarning(t,n){if(ES(n))return null;const r=this.rules.missingQueryIndex(t,n);return r===null?null:jS(t,r)}warnOnUnspecifiedIndex(t,n){if(n===void 0||Yr.isSilenced())return;const r=this.unspecifiedIndexWarning(t,n);r!==null&&CS(r)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Up(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const i=gu(e),o=gu(t);return i!==o?i-o:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===!0?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function gu(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const Rk=/^-?(0*)\d{1,10}$/,Nk=-2147483648,Ik=2147483647;function bu(e){if(Rk.test(e)){const n=Number(e);if(n>=Nk&&n<=Ik)return n}return null}function si(e,t){if(e===t)return 0;const r=bu(e),s=bu(t),i=r!==null,o=s!==null;if(i){if(o){const l=r-s;return l===0?e.length-t.length:l}return-1}else if(o)return 1;return e<t?-1:1}function $r(e,t,n,r=null){const s=e??{kind:"priority"};switch(s.kind){case"key":return t;case"value":return n;case"priority":return r;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const o=s.path.split("/").filter(l=>l.length>0);let a=n;for(const l of o){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function an(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let i=Object.entries(e).map(([u,d])=>({key:u,value:d,priority:n(u)}));const o=t.orderBy?.kind==="key";i.sort((u,d)=>{if(o)return si(u.key,d.key);const h=$r(t.orderBy,u.key,u.value,u.priority),f=$r(t.orderBy,d.key,d.value,d.priority),p=Up(h,f);return p!==0?p:si(u.key,d.key)});for(const u of t.bounds)i=i.filter(d=>Ak(u,d,t.orderBy));const a=t.limit;if(a!==null){const u=a.n;if(a.kind==="limitToFirst")i=i.slice(0,u);else{if(u>=i.length)return i;i=i.slice(i.length-u)}}return i}function Ak(e,t,n){const r=n?.kind==="key";let s;if(r)s=si(t.key,String(e.value));else{const u=$r(n,t.key,t.value,t.priority);s=Up(u,e.value)}const i=u=>si(t.key,u),o=s>0,a=s<0,l=s!==0;switch(e.kind){case"startAt":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0||i(u)>=0}case"startAfter":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0?!1:i(u)>0}case"endAt":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0||i(u)<=0}case"endBefore":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0?!1:i(u)<0}case"equalTo":{if(l)return!1;const u=e.key;return u===void 0||i(u)===0}}}function wu(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Ok(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&on(n.value,s.value)})}function Pc(e,t){const n=new Error(`permission_denied at ${Q(q(e))}: Client doesn't have permission to access the desired data.`);return n.code="PERMISSION_DENIED",$c(n,t)}class $k{state;constructor(t){this.state=t}onValue(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:s});if(u.check!=="allow"){let d;s&&(d={query:s}),this.state.events.operation(t,"listen",n,Ze(u.check),u,{at:l,durationMs:this.state.clock.now()-l,request:d,origin:"listener"});const h=Pn(u),f=$e(u,t,"listen",n,d);if(this.state.events.listener("errored",{id:this.state.events.nextListenerId(),path:n},t,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:h}),i)return o&&o(),queueMicrotask(()=>{i(Pc(n,f))}),()=>{};throw Ke(f)}return this.state.warnOnUnspecifiedIndex(n,s),this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:u,at:l},i,o,a)}adminOnValue(t,n,r){return this.state.warnOnUnspecifiedIndex(t,r),this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l){const u=this.state.events.nextListenerId(),d=Ih(l?.owner,l?.owners);this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:this.state.clock.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const h={id:u,auth:t,cb:r,path:n,query:s,cancelCallback:o,onCanceled:a,admin:i.origin==="admin",owners:d};if(this.state.valueListeners.add(h),this.state.events.listener("attach",h,t,{event:"value",result:"allow",detail:s?{query:s}:void 0,...s?{query:s}:{},owners:d}),s){const f=an(this.state.tree.read(n),s,this.state.priorities.forChild(n));h.lastWindow=f,this.deliverInitial(h,{val:wu(f),exists:f.length>0,key:this.key(n),rows:f},{initial:!0,query:!0})}else{const f=this.snapshot(n);h.lastValue=f.val,h.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(h,f,{initial:!0})}return()=>{this.state.valueListeners.delete(h),this.state.events.listener("detach",h,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>Q(q(r)));for(const r of this.state.valueListeners){const s=Q(q(r.path));if(!n.some(a=>Pk(s,a)))continue;if(r.query){const a=an(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Ok(r.lastWindow??[],a)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=a,this.deliver(r,{val:wu(a),exists:a.length>0,key:this.key(r.path),rows:a},{query:!0});continue}const i=this.snapshot(r.path),o=this.state.priorities.stateAtOrBelow(r.path);if(on(r.lastValue??null,i.val)&&r.lastPriorityState===o){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=o,this.deliver(r,i,{})}}off(t,n){const r=Q(q(t));for(const s of[...this.state.valueListeners])Q(q(s.path))===r&&(n!==void 0&&s.cb!==n||(this.state.valueListeners.delete(s),this.state.events.listener("detach",s,s.auth,{event:"value"})))}count(){return this.state.valueListeners.size}snapshot(t){const n=this.state.tree.read(t);return{val:n,exists:n!==null,key:this.key(t)}}key(t){const n=q(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){let s,i=!1;const o=Hs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:ua(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}deliverInitial(t,n,r){let s,i=!1;const o=Hs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});if(!i){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:ua(o)});return}this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}function ua(e){if(e!==void 0)return[e]}function Pk(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function vu(e,t){const n=Q(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of Object.entries(e))(i===n||i.startsWith(r))&&(s[i]=o);return s}function er(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function gs(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}class Dk{state;constructor(t){this.state=t}onChild(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:i});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,Ze(d.check),d,{at:l,durationMs:this.state.clock.now()-l,origin:"listener",detail:{event:n},request:i?{query:i}:void 0});const h=Pn(d),f=$e(d,t,"listen",r);if(this.state.events.listener("errored",{id:u,path:r},t,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:d.reasons},reasons:d.reasons,rules:h}),o)return a&&a(),queueMicrotask(()=>{o(Pc(r,f))}),()=>{};throw Ke(f)}return this.state.warnOnUnspecifiedIndex(r,i),this.attach(u,t,n,r,s,i,{origin:"listener",result:"allow",evaluation:d,at:l},o,a)}adminOnChild(t,n,r,s){return this.state.warnOnUnspecifiedIndex(n,s),this.attach(this.state.events.nextListenerId(),null,t,n,r,s,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l,u){const d=Ih();this.state.events.operation(n,"listen",s,a.result,a.evaluation,{at:a.at,durationMs:this.state.clock.now()-a.at,request:o?{query:o}:void 0,origin:a.origin,detail:{event:r}});const h={id:t,auth:n,event:r,path:s,cb:i,spec:o,cancelCallback:l,onCanceled:u,admin:a.origin==="admin"};if(this.state.childListeners.add(h),this.state.events.listener("attach",h,n,{event:r,result:"allow",detail:o?{query:o}:void 0,...o?{query:o}:{},owners:d}),o){const f=an(this.state.tree.read(s),o,this.state.priorities.forChild(s));if(h.lastWindow=f,h.lastPriorities=this.state.priorities.atOrBelow(s),r==="child_added")for(const{key:p,value:m}of f)this.deliver(h,{key:p,val:m,previousChildName:er(f,p)},{initial:!0,query:!0})}else if(r==="child_added")for(const{key:f,val:p}of this.directChildren(s)){const m=this.directChildren(s);this.deliver(h,{key:f,val:p,previousChildName:gs(m,f)},{initial:!0})}return()=>{this.state.childListeners.delete(h),this.state.events.listener("detach",h,n,{event:r})}}off(t,n,r){const s=Q(q(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||Q(q(i.path))===s&&(r!==void 0&&i.cb!==r||(this.state.childListeners.delete(i),this.state.events.listener("detach",i,i.auth,{event:i.event})))}snapshotParents(){const t=new Map;for(const n of this.state.childListeners){const r=Q(q(n.path));t.has(r)||t.set(r,{children:this.childStates(r),priorities:this.state.priorities.atOrBelow(r)})}return t}fanOut(t){if(this.state.childListeners.size===0)return;const n=new Map;for(const r of this.state.childListeners){if(r.spec){this.fanOutQuery(r);continue}const s=Q(q(r.path)),i=n.get(s)??[];i.push(r),n.set(s,i)}for(const[r,s]of n){const i=t.get(r),o=i?.children??new Map,a=i?.priorities??{},l=this.childStates(r),u=[...l].map(([f,{val:p}])=>({key:f,val:p})),d=[...o].map(([f,{val:p}])=>({key:f,val:p})),h={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,{val:p,priority:m}]of l){const g=o.get(f);if(g===void 0){h.child_added.push({key:f,val:p,previousChildName:gs(u,f)});continue}const b=gs(u,f);on(g.val,p)||h.child_changed.push({key:f,val:p,previousChildName:b}),g.priority!==m&&h.child_moved.push({key:f,val:p,previousChildName:b})}for(const[f,{val:p}]of o)l.has(f)||h.child_removed.push({key:f,val:p,previousChildName:gs(d,f),priorities:vu(a,Q([...q(r),f]))});for(const f of s)for(const p of h[f.event])this.deliver(f,p,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:an(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}childStates(t){const n=this.state.priorities.forChild(t);return new Map(this.directChildren(t).map(({key:r,val:s})=>[r,{val:s,priority:n(r)}]))}fanOutQuery(t){const n=t.lastWindow??[],r=an(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=r;const s=t.lastPriorities??{};t.lastPriorities=this.state.priorities.atOrBelow(t.path);const i=new Map(n.map(l=>[l.key,l.value])),o=new Map(r.map(l=>[l.key,l.value])),a=[];if(t.event==="child_added")for(const l of r)i.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:er(r,l.key)});else if(t.event==="child_changed")for(const l of r)i.has(l.key)&&!on(i.get(l.key),l.value)&&a.push({key:l.key,val:l.value,previousChildName:er(r,l.key)});else if(t.event==="child_removed")for(const l of n)o.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:er(n,l.key),priorities:vu(s,Q([...q(t.path),l.key]))});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=new Map(n.map(u=>[u.key,u]));for(const u of r){const d=l.get(u.key);if(!d)continue;const h=$r(t.spec.orderBy,d.key,d.value,d.priority),f=$r(t.spec.orderBy,u.key,u.value,u.priority);on(h,f)||a.push({key:u.key,val:u.value,previousChildName:er(r,u.key)})}}for(const l of a)this.deliver(t,l,{query:!0})}deliver(t,n,r){let s,i=!1;const o=Hs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:{key:n.key,val:n.val,previousChildName:n.previousChildName},detail:r,owners:ua(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}class Tk{state;children;publish;constructor(t,n,r){this.state=t,this.children=n,this.publish=r}adminSet(t,n){Mt(n);const r=this.state.tree.read(t);if(r===null)return;const s=this.state.clock.now(),i=this.state.priorities.get(t);this.state.events.operation(null,"setPriority",t,"not-applicable",void 0,{at:s,origin:"admin",request:{data:n},resourceBefore:{data:r,exists:!0},resourceAfter:{data:r,exists:!0},detail:{admin:!0,priority:n,priorPriority:i}});const o=this.children.snapshotParents();this.state.priorities.set(t,n),this.publish([t],o),this.state.events.commit(null,"setPriority",t,{data:n,priorState:i,nextState:n,replay:{requestTime:s},detail:{admin:!0,priority:n,priorPriority:i}}),this.state.notifyWrite()}validate(t,n,r){Mt(r);const s=this.evaluation(t,n,r);if(s.check!=="allow")throw Ke($e(s,t,"setPriority",n,{data:r}))}evaluation(t,n,r){const s=this.state.tree.read(n);return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:ft(s,[{segments:[],priority:r},...this.state.prioritiesBelow(n)])})}set(t,n,r){Mt(r);const s=this.state.tree.read(n),i=this.state.clock.now(),o=this.evaluation(t,n,r),a=this.state.priorities.get(n),l={at:i,durationMs:this.state.clock.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:a}};if(o.check!=="allow")throw this.state.events.operation(t,"setPriority",n,Ze(o.check),o,l),Ke($e(o,t,"setPriority",n,{data:r}));if(this.state.events.operation(t,"setPriority",n,"allow",o,l),this.state.events.commit(t,"setPriority",n,{data:r,priorState:a,nextState:s===null?null:r,replay:{requestTime:i},detail:{priority:r,priorPriority:a}}),s===null)return;const u=this.children.snapshotParents(),d=a!==r;this.state.priorities.set(n,r),this.publish([n],u),d&&this.state.events.mutation(t,"setPriority",ht(n),{before:a,after:r,detail:{priorityMetadata:!0}}),this.state.notifyWrite()}}function xu(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function dr(e,t,n,r,s=!1){const i=q(t);for(let a=0;a<i.length;a++){const l=Q(i.slice(0,a)),u=e.tree.read(l);if(u!==null&&typeof u!="object"){const d=e.priorities.get(l);return{overwrittenAncestor:{path:l,state:ft(u,[{segments:[],priority:d}])}}}}const o=e.prioritiesBelow(t);return o.length>0?{priorExport:ft(n,[{segments:[],priority:r},...o])}:s&&r!==null?{priorPriority:r}:{}}const Mk=/\broot\b/,Lk=/\bdata\b/,Uk=/\bparent\b/;function Bk(e,t){return e===t||e==="/"||t==="/"?!0:t.startsWith(`${e}/`)||e.startsWith(`${t}/`)}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fk(e,t){if(!t.startsWith(".")&&Object.hasOwn(e,t)&&_u(e[t]))return e[t];for(const[n,r]of Object.entries(e))if(n.startsWith("$")&&_u(r))return r}function qk(e,t,n){return typeof e!="string"?!1:Mk.test(e)?!0:Lk.test(e)?Uk.test(e)||e.includes("[")?!0:n.some(r=>Bk(t,r)):!1}function Su(e,t,n){const r=q(t);let s=e;for(let i=0;i<=r.length&&s!==void 0;i++){const o=Q(r.slice(0,i));if(qk(s[".read"],o,n))return!0;i<r.length&&(s=Fk(s,r[i]))}return!1}class Dc{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new Tk(t,r,(s,i)=>this.changed(s,i))}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t)){this.state.tree.write(n,Zt(ut(r,this.state.clock.now()),n==="/"?"":n));const{priority:s,nested:i}=en(r,null);this.state.priorities.replace(n,this.state.tree.read(n)===null?null:s),this.storeNestedPriorities(n,i)}this.state.mutations.mark("/"),this.cancelDeniedListeners(["/"]),this.state.notifyWrite()}setRules(t){t===null?this.state.activeRules=null:this.state.activeRules=structuredClone(t),this.state.rules.setRules(t),this.cancelDeniedListeners(),this.state.notifyWrite()}setDefaultPolicy(t){this.state.rules.setDefaultPolicy(t),this.cancelDeniedListeners(),this.state.notifyWrite()}getActiveRules(){const t=this.state.activeRules===null;let n=null;return t||(n=structuredClone(this.state.activeRules)),n}snapshotState(){return this.state.tree.snapshot()}adminGet(t){const n=this.state.tree.read(t);return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=this.state.rules.missingQueryIndex(t,n);if(r!==null)throw this.state.events.operation(null,"get",t,"error",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},detail:{failure:"missing-index"}}),ou(t,r);const s=an(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},resourceBefore:{data:xu(s),exists:s.length>0}}),s}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){const i=this.state.clock.now(),o=this.state.tree.read(t),a=Zt(ut(n,i,o),t==="/"?"":t),l=en(n,r);r=l.priority,s||=l.inline,Mt(r);const u=a===null?"remove":"set";this.state.events.operation(null,u,t,"not-applicable",void 0,{at:i,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:o,exists:o!==null},resourceAfter:{data:a,exists:a!==null}});const d=this.children.snapshotParents(),h=this.state.priorities.get(t),f=dr(this.state,t,o,h);this.state.tree.write(t,a),this.state.priorities.replace(t,a===null?null:r,g=>this.state.tree.read(g)!==null),this.storeNestedPriorities(t,l.nested),this.changed([t],d);const p=this.state.tree.read(t),m=s||h!==null;this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:o,nextState:p,replay:{requestTime:i},detail:{admin:!0,...m?{priority:r,priorPriority:h}:{},...f}}),this.state.notifyWrite()}adminUpdate(t,n){const r=this.state.clock.now(),s=this.state.tree.read(t),i=this.state.priorities.get(t),o=dr(this.state,t,s,i,!0),a=this.resolvePatch(t,n,r),l=this.patchPriorities(t,n),u=Object.keys(n).some(p=>p.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{at:r,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:u?{admin:!0,multiPath:!0,paths:Object.keys(a)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const d=this.children.snapshotParents();u?this.state.tree.multiUpdate(a):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(a).map(([p,m])=>[q(p).at(-1),m])));const h=p=>this.state.tree.read(p)!==null;this.state.priorities.applyUpdate(Object.entries(a).map(([p,m])=>({path:p,value:m})),h),this.storePatchPriorities(l),this.changed(Object.keys(a),d);const f=u?{admin:!0,multiPath:!0,paths:Object.keys(a),...o}:{admin:!0,multiPath:!1,keys:Object.keys(n),...o};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:f}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=this.state.clock.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,Ze(i.check),i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),Ke($e(i,t,"get",n));return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=this.state.clock.now(),i=this.readEvaluation(t,n,r);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,Ze(i.check),i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r}}),Ke($e(i,t,"get",n,{query:r}));const o=this.state.rules.missingQueryIndex(n,r);if(o!==null)throw this.state.events.operation(t,"get",n,"error",void 0,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},detail:{failure:"missing-index"}}),ou(n,o);const a=an(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},resourceBefore:{data:xu(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){Mt(s),this.setInternal(t,n,r,"set",s,!0)}remove(t,n){this.setInternal(t,n,null,"remove",null,!1)}setPriority(t,n,r){this.priorityWrites.set(t,n,r)}validatePriority(t,n,r){this.priorityWrites.validate(t,n,r)}validateRead(t,n,r){const s=this.readEvaluation(t,n,r);if(s.check!=="allow")throw Ke($e(s,t,"get",n,r?{query:r}:{}))}validateSet(t,n,r,s=null){const{evaluation:i,resolved:o}=this.setCheck(t,n,r,s);if(i.check!=="allow")throw Ke($e(i,t,"onDisconnect",n,{data:o}))}validateUpdate(t,n,r){const s=this.updateCheck(t,n,r);if(s!==null)throw Ke($e(s.evaluation,t,"onDisconnect",s.path,{data:s.value}))}registerDisconnect(t,n){const r=this.state.clock.now(),s=`onDisconnect.${n.kind}`,i=n.kind==="set"?n.value:n.kind==="update"?n.values:null,o=n.kind==="set"&&n.priority!==null?{priority:n.priority}:void 0;let a,l=null;if(n.kind==="update"){if(Object.keys(n.values).length===0)return;const d=this.updateEvaluations(t,n.path,n.values),h=d.find(f=>f.evaluation.check!=="allow");a=(h??d.at(-1)).evaluation,h!==void 0&&(l={path:h.update.path,data:h.update.value})}else{const d=n.kind==="set"?n.value:null,h=this.setCheck(t,n.path,d,n.kind==="set"?n.priority:null);a=h.evaluation,a.check!=="allow"&&(l={path:n.path,data:h.resolved})}const u={at:r,durationMs:this.state.clock.now()-r,request:{data:i,resourceData:i},detail:o};if(l!==null)throw this.state.events.operation(t,s,n.path,Ze(a.check),a,u),Ke($e(a,t,"onDisconnect",l.path,{data:l.data}));this.state.events.operation(t,s,n.path,"allow",a,u)}setCheck(t,n,r,s){const i=this.state.clock.now(),o=Zt(ut(r,i,this.state.tree.read(n)),n==="/"?"":n),a=en(r,s);Mt(a.priority);const l=ft(o,[{segments:[],priority:a.priority},...a.nested]);return{evaluation:this.writeEvaluation(t,n,l,i),resolved:o}}updateCheck(t,n,r){if(Object.keys(r).length===0)return null;for(const{update:s,evaluation:i}of this.updateEvaluations(t,n,r))if(i.check!=="allow")return{evaluation:i,path:s.path,value:s.value};return null}updateEvaluations(t,n,r){const s=this.state.clock.now(),i=this.state.rulesSnapshot(),o=this.patchPriorities(n,r),a=Object.entries(r).map(([l,u])=>{const d=Q([...q(n),...q(l)]),h=Zt(ut(u,s,this.state.tree.read(d)),d,Ir("update","values"));return{path:d,value:ft(h,o.get(d)??[])}});return a.map(l=>({update:l,evaluation:this.state.rules.evaluate("write",l.path,{auth:t,mockData:i,newData:l.value,updates:a,now:s})}))}update(t,n,r){if(Object.keys(r).length===0)return;const s=this.state.clock.now(),i=this.resolvePatch(n,r,s),o=this.patchPriorities(n,r),a=Object.keys(r).some(v=>v.includes("/")),l=this.state.rulesSnapshot(),u=Object.entries(i).map(([v,_])=>({path:v,value:_})),d=u.map(v=>({path:v.path,value:ft(v.value,o.get(v.path)??[])})),h=Object.fromEntries(Object.entries(i).map(([v,_])=>[q(v).at(-1),_])),f=this.state.events.nextGroupId("update"),p=[];for(const[v,_]of u.entries()){const S=this.state.clock.now(),k=this.state.tree.read(_.path),R=this.state.rules.evaluate("write",_.path,{auth:t,mockData:l,newData:d[v].value,updates:d,now:s}),O={at:S,durationMs:this.state.clock.now()-S,origin:"batch",request:{data:_.value,resourceData:_.value},resourceBefore:{data:k,exists:k!==null},resourceAfter:{data:_.value,exists:_.value!==null},groupId:f,groupKind:"batch",detail:a?{multiPath:!0,rootPath:ht(n)}:{multiPath:!1,rootPath:ht(n),key:q(_.path).at(-1)}};if(R.check!=="allow"){const P={...O,detail:{...O.detail,patch:r}};throw this.state.events.operation(t,"update",_.path,Ze(R.check),R,P),Ke($e(R,t,"update",_.path,{data:_.value}))}p.push(()=>this.state.events.operation(t,"update",_.path,"allow",R,O))}for(const v of p)v();const m=this.state.tree.read(n),g=this.state.priorities.get(n),b=dr(this.state,n,m,g,!0),w=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,h),this.state.priorities.applyUpdate(u,v=>this.state.tree.read(v)!==null),this.storePatchPriorities(o),this.changed(Object.keys(i),w);const x=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:x,groupId:f,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i),...b}:{multiPath:!1,keys:Object.keys(h),...b}}),this.state.events.mutation(t,"update",ht(n),{after:a?i:h,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(h)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,o){const a=this.state.clock.now(),l=Zt(ut(r,a,this.state.tree.read(n)),n==="/"?"":n),u=en(r,i);i=u.priority,o||=u.inline,Mt(i);const d=this.state.tree.read(n),h=this.state.priorities.get(n),f=this.state.clock.now(),p=ft(l,[{segments:[],priority:i},...u.nested]),m=this.writeEvaluation(t,n,p,a),g={at:f,durationMs:this.state.clock.now()-f,request:{data:r,resourceData:r},resourceBefore:{data:d,exists:d!==null},resourceAfter:{data:l,exists:l!==null}};if(m.check!=="allow"){const k=o?{...g,detail:{priority:i}}:g;throw this.state.events.operation(t,s,n,Ze(m.check),m,k),Ke($e(m,t,s,n,{data:r}))}this.state.events.operation(t,s,n,"allow",m,g);const b=this.children.snapshotParents(),w=dr(this.state,n,d,h);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i,k=>this.state.tree.read(k)!==null),this.storeNestedPriorities(n,u.nested),this.changed([n],b);const x=this.state.tree.read(n),v=x===null?"remove":s,S={...o||h!==null?{priority:i,priorPriority:h}:{},...w};this.state.events.commit(t,v,n,{data:r,priorState:d,nextState:x,replay:{requestTime:a},detail:Object.keys(S).length>0?S:void 0}),this.state.events.mutation(t,v,ht(n),{before:d,after:x}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const o=Q([...q(t),...q(s)]);return[o,Zt(ut(i,r,this.state.tree.read(o)),o,Ir("update","values"))]}))}changed(t,n){this.state.mutations.mark(t),this.cancelDeniedListeners(t),this.values.fanOut(t),this.children.fanOut(n)}cancelDeniedListeners(t){if(this.state.valueListeners.size===0&&this.state.childListeners.size===0)return;let n,r;if(t!==void 0){if(this.state.activeRules===null)return;const l=t.map(d=>Q(q(d)));if(l.length===0)return;const u=this.state.activeRules.rules;n=[...this.state.valueListeners].filter(d=>!d.admin&&Su(u,d.path,l)),r=[...this.state.childListeners].filter(d=>!d.admin&&Su(u,d.path,l))}else n=[...this.state.valueListeners].filter(l=>!l.admin),r=[...this.state.childListeners].filter(l=>!l.admin);if(n.length===0&&r.length===0)return;const s=this.state.rulesSnapshot(),i=[],o=new Map;for(const l of n){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.query});if(u.check==="allow")continue;this.state.valueListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,Ze(u.check),u,{origin:"listener",request:l.query?{query:l.query}:void 0,detail:{revoked:!0}});const d=Pn(u);this.state.events.listener("errored",l,l.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,$e(u,l.auth,"listen",l.path)),i.push(l)}const a=[];for(const l of r){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.spec});if(u.check==="allow")continue;this.state.childListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,Ze(u.check),u,{origin:"listener",request:l.spec?{query:l.spec}:void 0,detail:{event:l.event,revoked:!0}});const d=Pn(u);this.state.events.listener("errored",l,l.auth,{event:l.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,$e(u,l.auth,"listen",l.path)),a.push(l)}for(const l of[...i,...a]){try{l.onCanceled&&l.onCanceled()}catch{}try{l.cancelCallback&&l.cancelCallback(Pc(l.path,o.get(l)))}catch{}}}readEvaluation(t,n,r){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:r})}writeEvaluation(t,n,r,s){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:r,now:s})}storeNestedPriorities(t,n){for(const{segments:r,priority:s}of n){const i=Q([...q(t),...r]);this.state.priorities.set(i,this.state.tree.read(i)===null?null:s)}}patchPriorities(t,n){const r=new Map;for(const[s,i]of Object.entries(n)){const{priority:o,inline:a,nested:l}=en(i,null),u=Q([...q(t),...q(s)]);r.set(u,a?[{segments:[],priority:o},...l]:l)}return r}storePatchPriorities(t){for(const[n,r]of t){const s=r.find(i=>i.segments.length===0);s&&this.state.priorities.set(n,this.state.tree.read(n)===null?null:s.priority),this.storeNestedPriorities(n,r.filter(i=>i.segments.length>0))}}}function Vk(e){const t=e!==null;let n=!1;if(t){const r=typeof e=="object",s=Array.isArray(e);r&&(s||(n=!0))}if(n){const r=e,i=r[".pyricRtdbPersistence"]===1,o="data"in r;let a=!1;i&&o&&(a=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let h=!1;if(u&&d){const p=typeof l=="object",m=Array.isArray(l);p&&(m||(h=!0))}let f=!1;if(a&&h&&(f=!0),f){const p={},m=Object.entries(l);for(const[S,k]of m){const R=typeof k=="string",O=typeof k=="number";let P=!1;O&&Number.isFinite(k)&&(P=!0);let A=!1;R&&(A=!0),P&&(A=!0),A&&(p[S]=k)}const g=r.data;let b=null;g!==void 0&&g!==null&&(b=g);const x=r.rules;let v=null;if(x!==void 0&&x!==null){const k=typeof x=="object",R=Array.isArray(x);let O=!1;if(k&&(R||(O=!0)),O){const P=x;if("rules"in P){const E=P.rules;if(E!==null&&E!==void 0){const C=typeof E=="object",N=Array.isArray(E);let I=!1;C&&(N||(I=!0)),I&&(v={rules:E})}}}}return{data:b,priorities:p,rules:v}}}return{data:e,priorities:{},rules:null}}class Wk{state;values;children;writes;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.writes=new Dc(t,n,r)}exportTree(){return this.state.tree.snapshot()}exportState(){const t=this.state.activeRules!==null,n={".pyricRtdbPersistence":1,data:this.state.tree.snapshot(),priorities:Object.fromEntries(this.state.priorities.entries())};return t&&(n.rules=structuredClone(this.state.activeRules)),n}restore(t){const n=this.children.snapshotParents(),r=Vk(t);let s={};r.data!==null&&r.data!==void 0&&(s=r.data),r.rules!==null?(this.state.rules.setRules(r.rules),this.state.activeRules=structuredClone(r.rules)):(this.state.rules.setRules(null),this.state.activeRules=null),this.state.tree.restore(s),this.state.priorities.restore(r.priorities),this.state.mutations.mark("/"),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(t=!1){this.state.resetGeneration+=1;const n=this.children.snapshotParents();this.state.tree.restore({}),this.state.priorities.restore({}),this.state.mutations.mark("/"),t||(this.state.rules.setRules(null),this.state.activeRules=null),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const ku="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let Eu=0;const Qt=new Array(12).fill(0);function zk(e=Date.now()){const t=e===Eu;Eu=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=ku.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(t){let i;for(i=11;i>=0&&Qt[i]===63;i--)Qt[i]=0;if(i<0)for(let o=0;o<12;o++)Qt[o]=Math.floor(Math.random()*64);else Qt[i]=(Qt[i]??0)+1}else for(let i=0;i<12;i++)Qt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ku.charAt(Qt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function Hk(e){return $c(new Error("permission_denied"),e)}class Kk{state;children;writes;constructor(t,n,r,s=new Dc(t,n,r)){this.state=t,this.children=r,this.writes=s}run(t,n,r,s){const i=s?.applyLocally!==!1,o=s?.admin===!0,a=q(n),l=a.length===0?null:a[a.length-1];let u=null,d=null,h,f=0,p=!1;do{f+=1;const E=this.state.mutations.begin();u=this.state.tree.read(n),d=o||this.canRead(t,n)?u:null;const j=d===null?null:aa(Tt(d));let $=!1;try{h=r(j),$=this.state.mutations.conflictsSince(E,n)}finally{this.state.mutations.release(E)}if(!$||h===void 0){p=!0;break}}while(f<25);if(!p)throw new Error("maxretry");const m=this.state.events.nextGroupId("transaction");if(h===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:o?"admin":"transaction",groupId:m,groupKind:"transaction",resourceBefore:{data:d,exists:d!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:d,key:l};const g=this.state.clock.now(),b=Zt(ut(h,g,u),n==="/"?"":n,vS),w=this.state.priorities.get(n),x=en(h,w);Mt(x.priority);const v=b===null?null:x.priority,_=this.state.clock.now();let S;if(!o){const E=ft(b,[{segments:[],priority:v},...x.nested]);if(S=this.state.rules.evaluate("write",n,{auth:t,mockData:this.state.rulesSnapshot(),newData:E,now:g}),S.check!=="allow")throw this.state.events.operation(t,"transaction",n,Ze(S.check),S,{at:_,durationMs:this.state.clock.now()-_,origin:"transaction",request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction",detail:v!==null?{priority:v}:void 0}),Hk($e(S,t,"transaction",n,{data:h}))}const k=E=>this.state.tree.read(E)!==null,R=dr(this.state,n,u,w,!0),O=o?"not-applicable":"allow",P=o?"admin":"transaction";this.state.events.operation(t,"transaction",n,O,S,{at:_,durationMs:this.state.clock.now()-_,origin:P,request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"});const A=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.writes.changed([n],A),this.finishEvents(t,n,h,u,b,m,g,i,o,R),this.state.notifyWrite(),{committed:!0,val:b,key:l}}storeNestedPriorities(t,n,r){for(const{segments:s,priority:i}of n){const o=Q([...t,...s]);this.state.priorities.set(o,r(o)?i:null)}}canRead(t,n){return this.state.rules.evaluate("read",n,{auth:t,mockData:this.state.rulesSnapshot(),now:this.state.clock.now()}).check==="allow"}finishEvents(t,n,r,s,i,o,a,l,u,d){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:o,groupKind:"transaction",replay:{requestTime:a},detail:{...u?{admin:!0}:{},committed:!0,applyLocally:l,...d}}),this.state.events.mutation(t,"transaction",ht(n),{before:s,after:i,detail:{committed:!0}})}}function je(e,t){const n=t===void 0?[e]:Object.keys(t).map(r=>`${e}/${r}`);if(oa(e)||n.some(oa))throw fS()}class Gk{state;values;children;writes;transactions;persistence;constructor(t,n){this.state=new Ck(t,n),this.values=new $k(this.state),this.children=new Dk(this.state),this.writes=new Dc(this.state,this.values,this.children),this.transactions=new Kk(this.state,this.values,this.children,this.writes),this.persistence=new Wk(this.state,this.values,this.children)}get connectionResetGeneration(){return this.state.resetGeneration}get transactionMutationHistory(){return this.state.mutations.entries}invalidateConnectionQueues(){this.state.resetGeneration+=1}getPriority(t){return this.state.priorities.get(t)}setData(t){this.writes.setData(t)}setRules(t){this.writes.setRules(t)}setDefaultPolicy(t){this.writes.setDefaultPolicy(t)}getActiveRules(){return this.writes.getActiveRules()}snapshotState(){return this.writes.snapshotState()}adminGet(t){return this.writes.adminGet(t)}adminGetQuery(t,n){return this.writes.adminGetQuery(t,n)}adminSet(t,n){je(t),this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){je(t),this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){je(t,n),this.writes.adminUpdate(t,n)}adminRemove(t){je(t),this.writes.adminRemove(t)}adminSetPriority(t,n){je(t),this.writes.adminSetPriority(t,n)}get(t,n){return this.writes.get(t,n)}getQuery(t,n,r){return this.writes.getQuery(t,n,r)}unspecifiedIndexWarning(t,n){return this.state.unspecifiedIndexWarning(t,n)}set(t,n,r){je(n),this.writes.set(t,n,r)}setWithPriority(t,n,r,s){je(n),this.writes.setWithPriority(t,n,r,s)}update(t,n,r){je(n,r),this.writes.update(t,n,r)}remove(t,n){je(n),this.writes.remove(t,n)}setPriority(t,n,r){je(n),this.writes.setPriority(t,n,r)}validateRead(t,n,r){this.writes.validateRead(t,n,r)}validatePriority(t,n,r){je(n),this.writes.validatePriority(t,n,r)}registerDisconnect(t,n){n.kind==="update"?je(n.path,n.values):je(n.path),this.writes.registerDisconnect(t,n)}validateSet(t,n,r,s=null){je(n),this.writes.validateSet(t,n,r,s)}validateUpdate(t,n,r){je(n,r),this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,o,a){return this.values.onValue(t,n,r,s,i,o,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return je(n),this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,o,a){return this.children.onChild(t,n,r,s,i,o,a)}adminOnChild(t,n,r,s){return this.children.adminOnChild(t,n,r,s)}off(t,n,r){(n===void 0||n==="value")&&this.values.off(t,r),n!=="value"&&this.children.off(t,n,r)}exportTree(){return this.persistence.exportTree()}exportPersistenceState(){return this.persistence.exportState()}restoreTree(t){this.persistence.restore(t)}resetTree(t=!1){this.persistence.reset(t)}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return zk(this.state.clock.now())}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const ju=new WeakMap,Cu=new WeakMap;function Jk(e,t){const n=Yk(e);return n.getOrCreate(n.keyOf(t))}function Yk(e){const t=ju.get(e);if(t)return t;const n=new Set,r=()=>{for(const i of n)try{i()}catch{}},s=Z_({create:i=>{const o=i===s.defaultKey?void 0:i,a=new Gk(e,o);return a.subscribeWrites(r),a}});return ju.set(e,s),e.onEvent(i=>{if(i.kind==="session_boundary"&&i.phase==="reset")for(const[,o]of s.entries())o.invalidateConnectionQueues(),Cu.has(e)||o.setRules(null)}),e.registerPersistableService("rtdb",{snapshot:()=>{const i=s.getOrCreate(s.defaultKey).exportPersistenceState(),o={};for(const[a,l]of s.entries())a!==s.defaultKey&&(o[a]=l.exportPersistenceState());return Object.keys(o).length>0&&i!==null&&typeof i=="object"&&!Array.isArray(i)?{...i,instances:o}:i},restore:i=>{if(!i||typeof i!="object")return;s.getOrCreate(s.defaultKey).restoreTree(i);const o=i;if(o.instances&&typeof o.instances=="object")for(const[a,l]of Object.entries(o.instances))s.getOrCreate(a).restoreTree(l)},subscribe:i=>(n.add(i),()=>{n.delete(i)}),reset:()=>{for(const[,i]of s.entries())i.resetTree(Cu.has(e))}}),s}const Bp="type.googleapis.com/google.rpc.BadRequest",Fp="type.googleapis.com/google.firebase.fcm.v1.FcmError";function ss(e,t){return{"@type":Bp,fieldViolations:[{field:e,description:t}]}}function fn(e){return{"@type":Fp,errorCode:e}}function Fn(e,t){return{status:400,error:{code:400,message:e,status:"INVALID_ARGUMENT",details:t}}}function Ru(){const e="Recipient of the message is not set.";return Fn(e,[ss("message",e),fn("INVALID_ARGUMENT")])}function Qk(){const e="Exactly one of token, topic or condition is required.";return Fn(e,[ss("message",e),fn("INVALID_ARGUMENT")])}function Xk(){const e="The registration token is not a valid FCM registration token";return Fn(e,[fn("INVALID_ARGUMENT"),ss("message.token",e)])}function qp(){const e="Topic name contains invalid characters.";return Fn(e,[ss("message",e),fn("INVALID_ARGUMENT")])}function Zk(){return{status:400,error:{code:400,message:"Request contains an invalid argument.",status:"INVALID_ARGUMENT"}}}function eE(){return Fn("Message is too large. The maximum is 4K (4096 bytes).",[{"@type":Bp},fn("INVALID_ARGUMENT")])}function tE(){const e="TTL must be a non-negative integer.";return Fn(e,[ss("message.webpush.headers.TTL",e),fn("INVALID_ARGUMENT")])}function nE(){return{status:404,error:{code:404,message:"Requested entity was not found.",status:"NOT_FOUND",details:[fn("UNREGISTERED")]}}}function rE(e){return e.error.details?.find(n=>n["@type"]===Fp)?.errorCode}class Xe extends Error{envelope;errorCode;constructor(t){super(t.error.message),this.name="BrokerSendError",this.envelope=t,this.errorCode=rE(t)}}const sE=/^[a-zA-Z0-9-_.~%]+$/,Ii=/^[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$/,iE=4506,Nu=new TextEncoder;function oE(e){if(e===void 0)return 0;let t=0;for(const[n,r]of Object.entries(e))t+=Nu.encode(n).length+Nu.encode(String(r)).length;return t}function Tc(e){return e.startsWith("/topics/")?e.slice(8):e}function Ai(e){const t=Tc(e);return t.length>0&&sE.test(t)}function aE(e){const t=e;let n=0;const r=[];function s(){for(;n<t.length&&/\s/.test(t[n]);)n++}function i(l){return s(),t.startsWith(l,n)?(n+=l.length,!0):!1}function o(){if(s(),i("!"))return o();if(i("("))return a()?i(")"):!1;if(s(),t[n]!=="'")return!1;n++;const l=n;for(;n<t.length&&t[n]!=="'";)n++;if(n>=t.length)return!1;const u=t.slice(l,n);return n++,!i("in")||!i("topics")||!Ai(u)?!1:(r.push(u),!0)}function a(){if(!o())return!1;for(;;){if(s(),i("&&")||i("||")){if(!o())return!1;continue}return!0}}return!a()||(s(),n!==t.length)?null:{topics:r}}function cE(e){if(typeof e!="object"||e===null)throw new Xe(Ru());const t=[];if(typeof e.token=="string"&&t.push({kind:"token",token:e.token}),typeof e.topic=="string"&&t.push({kind:"topic",topic:Tc(e.topic)}),typeof e.condition=="string"&&t.push({kind:"condition",condition:e.condition,topics:[]}),t.length===0)throw new Xe(Ru());if(t.length>1)throw new Xe(Qk());const n=t[0];if(n.kind==="token"&&!Ii.test(n.token))throw new Xe(Xk());if(n.kind==="topic"&&!Ai(n.topic))throw new Xe(qp());if(n.kind==="condition"){const s=aE(n.condition);if(s===null)throw new Xe(Zk());n.topics=s.topics}const r=e.webpush?.headers?.TTL;if(r!==void 0&&!/^\d+$/.test(String(r)))throw new Xe(tE());if(oE(e.data)>iE)throw new Xe(eE());return n}function Vp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lE(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&Ii.test(n),i=Vp(r);if(!(s&&i))return!1;const a=typeof r.registrationId=="string"&&r.registrationId.length>0,l=typeof r.recipientId=="string"&&r.recipientId.length>0,u=r.state==="active"||r.state==="unregistered";return a&&l&&u}function uE(e){return typeof e=="string"&&Ii.test(e)}function dE(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&Ai(n),i=Array.isArray(r)&&r.every(uE);return s&&i}function fE(e){if(!Vp(e))return!1;const t=e.version===1,n=Array.isArray(e.tokens)&&e.tokens.every(lE),r=Array.isArray(e.topics)&&e.topics.every(dE);return t&&n&&r}function hE(e){return/[.!?]$/.test(e)?e:`${e}.`}function Wp(e,t){return e===null||!e.startsWith("/")||e.startsWith("//")||t==null||!/^https?:\/\//.test(t)?e:new URL(e,t).href}function zp(){const e=globalThis.location?.origin;return typeof e=="string"&&/^https?:\/\//.test(e)?e:null}const pE="database.rules.json";function Iu(e,t){const n=e.lastIndexOf("."),r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=n>r+1?e.slice(n):"";if(s===".json")return;const i=s===".bolt"?"As of firebase-tools@15.0.0, .bolt rules are no longer supported.":`Unexpected rules format ${s}`;throw new Error(`${t}: ${i}`)}function mE(e){if(e===void 0)return sa(void 0);const t=wp(e);try{return Nc(t).name}catch{return t}}function yE(e,t={}){const n=t.resolveFile??(o=>o),r=mE(t.projectId);if(e==null){const o=pE;return{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:"firebase.json",configured:!1}],unresolved:[]}}if(!Array.isArray(e)){const o=typeof e=="object"?e.rules:void 0;if(typeof o!="string"||o==="")return{defaultInstance:r,targets:[],unresolved:[]};const a="firebase.json database.rules";return Iu(o,a),{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:a,configured:!0}],unresolved:[]}}const s=[],i=[];return e.forEach((o,a)=>{const l=`firebase.json database[${a}]`,u=o!==null&&typeof o=="object"?o:{};let d;if(typeof u.target=="string"&&u.target!==""){const f=t.targetInstances?.(u.target);d=Array.isArray(f)?f.filter(p=>typeof p=="string"&&p!==""):[]}else if(typeof u.instance=="string"&&u.instance!=="")d=[u.instance];else throw new Error(`${l}: Must supply either "target" or "instance" in database config`);if(typeof u.rules!="string"||u.rules==="")return;Iu(u.rules,l);const h=n(u.rules);if(d.length===0&&typeof u.target=="string"){i.push({target:u.target,label:l,file:h});return}for(const f of d){let p;try{p=Nc(f).name}catch(g){const b=g instanceof Error?g.message.trim():String(g);throw new Error(`${l}: instance "${f}" is not a database instance name: ${b}`)}vp(p,t.projectId)&&(p=r);const m=s.find(g=>g.instance===p);if(m===void 0){s.push({instance:p,file:h,configuredFile:u.rules,label:l,configured:!0});continue}if(m.file!==h)throw new Error(`firebase.json deploys two rules files to database instance "${p}": ${m.file} from ${m.label} and ${h} from ${l}. The Firebase CLI deploys both at once, so the configuration does not determine which one production keeps. Deploy one rules file to each instance.`)}}),{defaultInstance:r,targets:s,unresolved:i}}const gE="__pyric_no_password__",bE=300*1e3;function uo(e){return ok(e.claims)}class Hp{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new U_;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;photoOriginByUid=new Map;authenticatedAtByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;avatarMint=Y_;tenantId=null;getTenantId(){return this.tenantId}setTenantId(t){this.tenantId=t}constructor(t,n=t,r=gp(),s){this.sandbox=t,this.session=n,this.usersByEmail=r.usersByEmail,this.usersByUid=r.usersByUid,this.userDbSubs=r.userDbSubscribers,this.providerConfig=r.providerConfig,this.providerConfigSubs=r.providerConfigSubscribers,this.sharedCounters=r.counters,this.cachedUser=this.buildUserFromState(n.currentUser),this.lastNotifiedUid=this.cachedUser?.uid??null;const i=n.onCurrentUserChanged(o=>{if(this.applyingTransition)return;const a=o===null?null:o.uid,l=this.cachedUser?.uid??null;a!==l&&(this.cachedUser=this.buildUserFromState(o)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}getCurrentSignInProvider(){const t=this.cachedUser;return t===null?null:this.signInProviderByUid.get(t.uid)??null}subscribe(t,n){const r=t==="auth-state"?this.authStateSubs:this.idTokenSubs,s={observer:n,hasFired:!1,lastValue:null};return r.push(s),queueMicrotask(()=>{r.includes(s)&&(s.hasFired&&s.lastValue===this.cachedUser||this.deliverOne(s,this.cachedUser))}),()=>{const i=r.indexOf(s);i!==-1&&r.splice(i,1)}}fanOut(t="both"){const n=this.cachedUser;if(t==="both"||t==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(t==="both"||t==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){this.fanOut("id-token");const t=this.cachedUser?.uid??null;this.lastNotifiedUid!==t&&(this.lastNotifiedUid=t,this.fanOut("auth-state"))}deliverOne(t,n){t.hasFired=!0,t.lastValue=n;const r=t.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(t,n=null){const r={email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:this.now().toISOString(),lastLoginAt:null,tenantId:null,...t},s=wE(r,n);return vE(r,s)&&(r.photoUrl=this.avatarMint({uid:r.uid,displayName:r.displayName,email:r.email,providerId:s})),r}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}now(){return De(this.sandbox).date()}emitAuthEvent(t,n={}){try{dt(this.sandbox,Ln({at:this.now().getTime(),service:"auth",op:t,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(t){return this.userDbSubs.add(t),()=>{this.userDbSubs.delete(t)}}isProviderEnabled(t){return this.providerConfig.get(t)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([t,n])=>({providerId:t,enabled:n}))}setProviderConfig(t,n){const r=this.providerConfig.get(t)??!0;r!==n&&(this.providerConfig.set(t,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:t,auth:null,before:{providerId:t,enabled:r},after:{providerId:t,enabled:n}}))}notifyProviderConfigChanged(){for(const t of[...this.providerConfigSubs])try{t()}catch{}}subscribeProviderConfig(t){return this.providerConfigSubs.add(t),()=>{this.providerConfigSubs.delete(t)}}setProviderEnforcementDelegated(t){this.providerEnforcementDelegated=t}setAvatarMint(t){this.avatarMint=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw Z("auth/operation-not-allowed",`${t} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${t}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(t){if(this.providerConfig.clear(),t&&typeof t=="object")for(const[n,r]of Object.entries(t))typeof r=="boolean"&&this.providerConfig.set(n,r);else this.providerConfig.set("password",!0),this.providerConfig.set("anonymous",!0);this.notifyProviderConfigChanged()}getPersistenceMode(){return this.persistenceMode}setPersistenceMode(t){this.persistenceMode!==t&&(this.persistenceMode=t,this.notifySessionChanged())}sessionChangeSubs=new Set;notifySessionChanged(){for(const t of[...this.sessionChangeSubs])try{t()}catch{}}subscribeSession(t){return this.sessionChangeSubs.add(t),()=>{this.sessionChangeSubs.delete(t)}}seedUsers(t){for(const r of t){const i=this.usersByUid.get(r.uid)?.email;typeof i=="string"&&i.length>0&&i.toLowerCase()!==r.email?.toLowerCase()&&this.usersByEmail.delete(i.toLowerCase());const l=r.providerId==="anonymous",u=r.providerUserInfo??[{providerId:r.providerId??"password"}],d=l?[]:u.map(k=>({...k})),h=d.some(k=>k.providerId==="password"),p=(r.password===gE||r.password==="__pyric_popup_no_password__")&&!h,m=l||p,g=this.makeStored({uid:r.uid,email:l?null:r.email??null,password:m?null:r.password??null,displayName:r.displayName??null,phoneNumber:r.phoneNumber??null,photoUrl:r.photoUrl??null,customClaims:r.customClaims??{},emailVerified:r.emailVerified??!1,disabled:r.disabled??!1,isAnonymous:l,providerUserInfo:d,tenantId:r.tenantId??null}),{createdAt:b,lastLoginAt:w,email:x}=r;b!==void 0&&(g.createdAt=b),w!==void 0&&(g.lastLoginAt=w),!l&&x!==void 0&&this.usersByEmail.set(x.toLowerCase(),g),this.usersByUid.set(r.uid,g)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){const{email:r,displayName:s,photoUrl:i,tenantId:o,phoneNumber:a,isAnonymous:l,disabled:u,emailVerified:d}=n,h=s!==null,f=i!==null,p=Object.keys(n.customClaims).length>0,m=o!==null;if(l){const _={uid:n.uid,providerId:"anonymous",createdAt:n.createdAt,lastLoginAt:n.lastLoginAt};h&&(_.displayName=s),f&&(_.photoUrl=i),p&&(_.customClaims=n.customClaims),u&&(_.disabled=!0),m&&(_.tenantId=o),t.push(_);continue}if(r===null)continue;const b={uid:n.uid,createdAt:n.createdAt,lastLoginAt:n.lastLoginAt,email:r,providerId:n.providerUserInfo[0]?.providerId??"password",providerUserInfo:n.providerUserInfo.map(_=>({..._}))},{password:w}=n;w!==null&&(b.password=w),h&&(b.displayName=s),f&&(b.photoUrl=i),a!==null&&(b.phoneNumber=a),p&&(b.customClaims=n.customClaims),d&&(b.emailVerified=!0),u&&(b.disabled=!0),m&&(b.tenantId=o),t.push(b)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw Z("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw Z("auth/user-disabled",`restoreSession: user ${t} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password",s=this.buildUserFromStored(n);return this.setCurrentUser(s,r),s}findByEmail(t){return this.usersByEmail.get(t.toLowerCase())}findByUid(t){return this.usersByUid.get(t)}mintActionCode(t){return this.flow.mintActionCode(t)}stageActionCode(t,n){this.flow.stageActionCode(t,n)}peekActionCode(t){return this.flow.peekActionCode(t)}consumeActionCode(t){return this.flow.consumeActionCode(t)}deliverMail(t){this.flow.deliverMail(t)}takeMail(t){return this.flow.takeMail(t)}listMail(){return this.flow.listMail()}setMailResolver(t){this.flow.setMailResolver(t)}setEmailVerified(t,n){const r=this.requireByEmail(t);return r.emailVerified!==n&&(r.emailVerified=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailVerified:n}})),r}setPasswordByEmail(t,n){Zn(n);const r=this.requireByEmail(t);return r.password=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{passwordReset:!0}}),r}changeEmail(t,n){Yt(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw Z("auth/email-already-in-use",`An account already exists for ${n}.`);return r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n,r.emailVerified=!0,this.usersByEmail.set(s,r),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailChanged:n}}),r}upsertEmailLinkUser(t){Yt(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r!==void 0)return!r.providerUserInfo.some(l=>l.providerId==="password")&&r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw Z("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(o=>o.providerId===n))throw Z("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Yt(i);const o=i.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a.uid!==t)throw Z("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(Zn(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==o&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(o,s),r.emailVerified!==void 0&&(s.emailVerified=r.emailVerified)}return s.providerUserInfo.push({providerId:n}),s.isAnonymous&&(s.isAnonymous=!1),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(t,n){const r=this.usersByUid.get(t);if(!r)throw Z("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw Z("auth/no-such-provider",`User was not linked to an account with the given provider (${n}).`);return r.providerUserInfo.splice(s,1),n==="password"&&(r.password=null),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(r),detail:{unlinked:n}}),r}requireByEmail(t){const n=this.usersByEmail.get(t.toLowerCase());if(!n)throw Z("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Yt(t),Zn(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw Z("auth/email-already-in-use",`An account already exists for ${t}.`);const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o)}),o}beforeAuthStateChanged(t,n){const r={callback:t,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(t){if(t===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(t),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const i of n)try{i()}catch{}const s=r instanceof Error?r.message:String(r);throw Z("auth/login-blocked",s)}}transitionCurrentUser(t,n){return t!==null&&n!==void 0&&this.scopeSignInToTenant(t),!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}scopeSignInToTenant(t){const n=this.tenantId;t.tenantId=n;const r=this.usersByUid.get(t.uid);r&&(r.tenantId=n)}setCurrentUser(t,n){if(t===null){const p=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}p!==null&&(this.tokenCache.delete(p.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:p.uid,auth:{uid:p.uid}}));return}const s=n!==void 0;s&&this.signInProviderByUid.set(t.uid,n),(s||!this.authenticatedAtByUid.has(t.uid))&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{};s&&o!==void 0&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),this.cachedUser=t;const u=this.mintToken(t.uid,a,t.tenantId??null),d={uid:t.uid,token:uo(u.result)};typeof t.tenantId=="string"&&(d.tenant=t.tenantId);const f=d;this.applyingTransition=!0;try{this.session.currentUser=f}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),s&&this.emitAuthEvent("sign_in",{path:t.uid,auth:f,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n??"anonymous"}})}setMockResult(t,n){this.flow.setMockResult(t,n)}consumeMockResult(t){return this.flow.consumeMockResult(t)}setResolver(t){this.flow.setResolver(t)}getResolver(){return this.flow.getResolver()}setRedirectResult(t){this.flow.setRedirectResult(t)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(t,n){let r=!1;const s=t.photoURL??null;let i=this.usersByUid.get(t.uid);i?Au(i,s)&&(r=!0):(i=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,photoUrl:s,isAnonymous:t.isAnonymous},n),this.usersByUid.set(t.uid,i),t.email&&this.usersByEmail.set(t.email.toLowerCase(),i),r=!0),i.providerUserInfo.some(o=>o.providerId===n)||(i.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(t){const{providerId:n}=t;let r;if("uid"in t){const s=this.usersByUid.get(t.uid);if(!s)throw Z("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);this.assertUserEnabled(s),r=s}else{const{spec:s}=t,i=s.photoUrl??null,o=this.usersByEmail.get(s.email.toLowerCase());o?(this.assertUserEnabled(o),r=o,Au(r,i)&&this.notifyUsersChanged()):(r=this.makeStored({uid:s.uid??xE(),email:s.email,displayName:s.displayName??null,photoUrl:i,customClaims:s.customClaims??{}},n),this.usersByUid.set(r.uid,r),this.usersByEmail.set(s.email.toLowerCase(),r),this.notifyUsersChanged())}return r.providerUserInfo.some(s=>s.providerId===n)||(r.providerUserInfo.push({providerId:n}),this.notifyUsersChanged()),{user:this.buildUserFromStored(r),providerId:n,operationType:"signIn"}}listIdentities(){return[...this.usersByUid.values()].map(t=>({uid:t.uid,email:t.email,displayName:t.displayName,providerId:t.isAnonymous?"anonymous":t.providerUserInfo[0]?.providerId??"password",providerUserInfo:[...t.providerUserInfo],isAnonymous:t.isAnonymous,customClaims:t.customClaims}))}toRecord(t){return{uid:t.uid,email:t.email,displayName:t.displayName,phoneNumber:t.phoneNumber,photoUrl:t.photoUrl,customClaims:{...t.customClaims},providerUserInfo:t.providerUserInfo.map(n=>({...n})),isAnonymous:t.isAnonymous,disabled:t.disabled,emailVerified:t.emailVerified,tenantId:t.tenantId,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>({...this.toRecord(t),photoUrl:Xt(t,this.photoOriginByUid)}))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const o of t){const a=o?.providerId?.trim();if(!a)throw Z("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);a==="password"||a==="anonymous"||s.has(a)||(s.add(a),i.push({providerId:a}))}return n&&i.unshift({providerId:"password"}),i}nextAvailableAdminUid(){for(;;){const t=`user-${this.sharedCounters.nextAdminUserId++}`;if(!this.usersByUid.has(t))return t}}createUser(t){t.customClaims!==void 0&&fu(t.customClaims);const n=t.uid??this.nextAvailableAdminUid();if(this.usersByUid.has(n))throw Z("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Yt(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw Z("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(Zn(t.password),t.email===void 0))throw Z("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:t.email??null,password:t.password??null,displayName:t.displayName??null,phoneNumber:t.phoneNumber??null,photoUrl:t.photoUrl??null,customClaims:t.customClaims??{},disabled:t.disabled??!1,emailVerified:t.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(t.providerUserInfo??[],t.password!==void 0,"createUser")});this.usersByUid.set(n,r),r.email&&this.usersByEmail.set(r.email.toLowerCase(),r),this.notifyUsersChanged();const s=this.toRecord(r);return this.emitAuthEvent("user_create",{path:n,auth:null,after:s}),{...this.toRecord(r),photoUrl:Xt(r,this.photoOriginByUid)}}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw Z("auth/user-not-found",`No user found for uid ${t}.`);n.customClaims!==void 0&&fu(n.customClaims);const s=this.toRecord(r);if(n.email!==void 0){Yt(n.email);const o=n.email.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a!==r)throw Z("auth/email-already-in-use",`An account already exists for ${n.email}.`);r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n.email,this.usersByEmail.set(o,r)}n.password!==void 0&&(Zn(n.password),r.password=n.password,r.providerUserInfo.some(o=>o.providerId==="password")||r.providerUserInfo.push({providerId:"password"})),n.providerUserInfo!==void 0&&(r.providerUserInfo=this.sanitizeLinkedProviders(n.providerUserInfo,r.password!==null,"updateUser")),n.displayName!==void 0&&(r.displayName=n.displayName),n.customClaims!==void 0&&(r.customClaims={...n.customClaims}),n.disabled!==void 0&&(r.disabled=n.disabled),n.emailVerified!==void 0&&(r.emailVerified=n.emailVerified),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:null,before:s,after:i}),{...this.toRecord(r),photoUrl:Xt(r,this.photoOriginByUid)}}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw Z("auth/user-not-found",`No user found for uid ${t}.`);const r=this.toRecord(n);this.usersByUid.delete(t),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(t),this.signInProviderByUid.delete(t),this.photoOriginByUid.delete(t),this.authenticatedAtByUid.delete(t),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:t,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const t=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:t}})}assertSignInAllowed(t){if(this.usersByUid.get(t)?.disabled)throw Z("auth/user-disabled","The user account has been disabled by an administrator.")}buildUserFromStored(t){return this.makeUser({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous,claims:t.customClaims,photoURL:Xt(t,this.photoOriginByUid),emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo,tenantId:t.tenantId})}mintAnonymousUser(){const t=`anonymous-${globalThis.crypto.randomUUID()}`,n=this.makeStored({uid:t,isAnonymous:!0});return this.usersByUid.set(t,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:t,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:t,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(t){const n=t.tenantId??null;switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous",n,!0,t.origin);case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password",n,!0,t.origin);case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password",n,!0,t.origin);case"provider":case"custom":case"uid":{const r=t.kind==="provider";r&&this.assertProviderEnabled(t.providerId);const s=this.usersByUid.get(t.uid);if(s===void 0)throw Z("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);this.assertUserEnabled(s);const a=s.isAnonymous?"anonymous":s.providerUserInfo[0]?.providerId??"password";let l=r?t.providerId:a;t.kind==="custom"&&(l="custom");const d=t.kind!=="uid"||!this.authenticatedAtByUid.has(t.uid);return this.establishDetachedSession(this.buildUserFromStored(s),l,n,d,t.origin)}}}establishDetachedSession(t,n,r,s=!0,i){this.signInProviderByUid.set(t.uid,n),i!==void 0&&this.photoOriginByUid.set(t.uid,i),s&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{},l=o!==void 0;l&&(t.photoURL=Xt(o,this.photoOriginByUid)),l&&s&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),t.tenantId=r;const u=this.mintToken(t.uid,a,r),d={uid:t.uid,token:uo(u.result)};return r!==null&&(d.tenant=r),this.emitAuthEvent("sign_in",{path:t.uid,auth:d,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:d}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims,tenantId:t.tenant??n.tenantId}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{},tenantId:t.tenant??null})}mintToken(t,n,r){const s=this.now(),i=new Date(s.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,a=this.signInProviderByUid.get(t)??null,l=new Date(this.authenticatedAtByUid.get(t)??s.getTime()),u=this.usersByUid.get(t),d={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(l.getTime()/1e3),iat:Math.floor(s.getTime()/1e3),exp:Math.floor(i.getTime()/1e3),...Np(t,u?{...ak(u),photoUrl:Xt(u,this.photoOriginByUid)}:null,n,a)},f=Ei({uid:t,tenant:r??void 0,token:d})?.token??d,p=B_(t,f,o),m={token:p,claims:f,expirationTime:i.toISOString(),issuedAtTime:s.toISOString(),authTime:l.toISOString(),signInProvider:a},g={token:p,result:m},b=this.tokenCache.get(t)??new Map;return b.set(r,g),this.tokenCache.set(t,b),g}getIdTokenFor(t,n,r,s=null){return this.getIdTokenResultFor(t,n,r,s).token}getIdTokenResultFor(t,n,r,s=null){if(r){const l=this.mintToken(t,n,s),u=this.session.currentUser;if(u!==null&&u.uid===t&&(u.tenant??null)===s){this.applyingTransition=!0;try{this.session.currentUser={...u,token:uo(l.result)}}finally{this.applyingTransition=!1}}return this.fanOut("id-token"),l.result}const i=this.tokenCache.get(t)?.get(s);return i!==void 0?i.result:this.mintToken(t,n,s).result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",o=t.providers??[{providerId:"password"}],l=t.isAnonymous===!0?[]:o.map(d=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:d.providerId})),u={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:i,providerData:l,getIdToken:async d=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId),getIdTokenResult:async d=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId)};return Object.defineProperty(u,T_,{value:{updateProfile:d=>(this.updateProfileFor(u,d),Promise.resolve()),delete:()=>(this.deleteFor(u),Promise.resolve()),updateEmail:d=>(this.updateEmailFor(u,d),Promise.resolve()),updatePassword:d=>(this.updatePasswordFor(u,d),Promise.resolve()),reload:()=>(this.reloadFor(u),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),u}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(t,n){const r=this.usersByUid.get(t.uid),s=r?this.toRecord(r):void 0;r&&(n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL)),this.applyProfileToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t.uid,auth:{uid:t.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(t,n){const r=t;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=t.providerData?.[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(t,n){const r=this.usersByUid.get(t);if(!r)throw Z("auth/user-not-found",`updateProfile: no identity with uid ${t}.`);const s=this.toRecord(r);n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL),this.cachedUser&&this.cachedUser.uid===t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:{uid:t},before:s,after:i,detail:{displayName:n.displayName,photoURL:n.photoURL}}),i}recordAuthentication(t){this.authenticatedAtByUid.set(t,this.now().getTime())}assertRecentLogin(t){if(this.usersByUid.get(t)?.isAnonymous===!0)return;const r=this.authenticatedAtByUid.get(t);if(r===void 0)return;if(this.now().getTime()-r>bE)throw Z("auth/requires-recent-login","Error")}deleteFor(t){this.assertRecentLogin(t.uid),this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.assertRecentLogin(t.uid),this.updateUser(t.uid,{email:n}),this.applyEmailToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(t,n){t.email=n;const r=t.providerData?.[0];r&&(r.email=n)}updatePasswordFor(t,n){this.assertRecentLogin(t.uid),this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw Z("auth/user-token-expired","The user's credential is no longer valid. The user must sign in again.");this.applyStoredToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyStoredToUser(this.cachedUser,n)}applyStoredToUser(t,n){const r=t;r.email=n.email,r.displayName=n.displayName,r.photoURL=Xt(n,this.photoOriginByUid),r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}assertUserEnabled(t){if(t.disabled)throw Z("auth/user-disabled","The user account has been disabled by an administrator.")}validatePassword(t,n){if(Yt(t),typeof n!="string"||n.length===0)throw Z("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw Z("auth/user-not-found",`No user found for ${t}.`);if(this.assertUserEnabled(r),r.password!==n)throw Z("auth/wrong-password","Invalid password.");return r}}function wE(e,t){if(t!==null)return t;const n=e.providerUserInfo[0];return n===void 0?null:n.providerId}function vE(e,t){return e.photoUrl!==null||e.isAnonymous||t===null?!1:t.includes(".")}function Xt(e,t){return Wp(e.photoUrl,t.get(e.uid)??zp())}function Au(e,t){return t===null||e.photoUrl===t?!1:(e.photoUrl=t,!0)}function xE(){return`provider-${globalThis.crypto.randomUUID()}`}const Ou=new WeakSet,bs=new WeakMap;function Kp(e,t,n,r="[DEFAULT]"){return _E(e,t),SE(e,t,n,r)}function _E(e,t){Ou.has(e)||(Ou.add(e),e.registerPersistableService("auth",{snapshot:()=>({users:t.exportUsers(),providers:t.exportProviderConfig()}),restore:n=>{const r=n;t.clearUsers(),Array.isArray(r?.users)&&r.users.length>0&&t.seedUsers(r.users),t.restoreProviderConfig(r?.providers)},reset:()=>{t.clearUsers(),t.restoreProviderConfig(void 0)},subscribe:n=>{const r=t.subscribeUsers(n),s=t.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function $u(e){return{snapshot:()=>null,restore:()=>{},session:{currentUid:()=>e.session.currentUser?.uid??null,restore:(t,n)=>{e.backend.setPersistenceMode(n),e.backend.restoreSession(t)},mode:()=>e.backend.getPersistenceMode(),subscribe:t=>(e.subscribers.add(t),e.unsubscribeBackend||(e.unsubscribeBackend=e.backend.subscribeSession(()=>{for(const n of e.subscribers)n()})),()=>{e.subscribers.delete(t),e.subscribers.size===0&&(e.unsubscribeBackend?.(),e.unsubscribeBackend=void 0)})}}}function SE(e,t,n,r){let s=bs.get(e);s||(s=new Map,bs.set(e,s));const i=`auth-session:${r}`,o=s.get(i);if(o){const u=++o.generation;return o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.backend=t,o.session=n,o.unregisterService=e.registerPersistableService(i,$u(o)),()=>{o.generation===u&&(o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.subscribers.clear(),s.get(i)===o&&s.delete(i),s.size===0&&bs.delete(e))}}const a={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,a),a.unregisterService=e.registerPersistableService(i,$u(a));const l=a.generation;return()=>{a.generation===l&&(a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.subscribers.clear(),s.get(i)===a&&s.delete(i),s.size===0&&bs.delete(e))}}async function Dq(e){const{backend:t}=Rc(e);t.assertProviderEnabled("anonymous");const n=t.getCurrentUser();if(n?.isAnonymous)return{user:n,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!1,profile:{},providerId:null}};const r=t.mintAnonymousUser();return await t.transitionCurrentUser(r,"anonymous"),{user:r,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!0,profile:{},providerId:null}}}async function kE(e){const t=Rc(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const Pu=new WeakMap,Du=new WeakMap,Tu=new WeakMap;function Gp(e){let t=Du.get(e);return t||(t=gp(),Du.set(e,t)),t}function EE(e){let t=Pu.get(e);return t||(t=new Hp(e,e,Gp(e)),Pu.set(e,t),Kp(e,t,e)),t}function jE(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new Hp(n,r,Gp(n),i=>{t.onDelete(i)});return t.onDelete(Kp(n,s,r,e.name)),s})}function Mc(e){if(e===void 0)return Mc($v());const t=Pv(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:jE(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return Mu(n,e)});if(CE(e)){let n=Tu.get(e);return n||(n=Mu({kind:"sandbox",sandbox:e,backend:EE(e)}),Tu.set(e,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric sandbox or @pyric/cli/register before importing to select the sandbox.")}function CE(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function Mu(e,t){const n={[Ec]:e,...t?{app:t}:{},signOut(){return kE(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}}),Object.defineProperty(n,"tenantId",{enumerable:!0,get(){return e.backend.getTenantId()},set(r){e.backend.setTenantId(r)}})}const Lu=Symbol.for("pyric.auth.servedSandbox");function te(e){return Rc(e)}function RE(e){if(Object.hasOwn(e,Lu))return e[Lu]}function NE(e){return Ec in e}const ve={setUser(e,t){te(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){te(e).backend.setResolver(t)},setAuthMailResolver(e,t){te(e).backend.setMailResolver(t)},takeAuthMail(e,t){return te(e).backend.takeMail(t)},listAuthMail(e){return te(e).backend.listMail()},mockActionCode(e,t,n){te(e).backend.stageActionCode(t,n)},listIdentities(e){return te(e).backend.listIdentities()},createSignInCredential(e,t){return te(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new Ah("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");const r=RE(e);if(r!==void 0&&!NE(e)){r.mockSignInResult(t);return}te(e).backend.setMockResult(n,t)},seedUsers(e,t){te(e).backend.seedUsers(t)},exportUsers(e){return te(e).backend.exportUsers()},restoreSession(e,t){return te(e).backend.restoreSession(t)},getTenantId(e){return te(e).backend.getTenantId()},setTenantId(e,t){te(e).backend.setTenantId(t)},mintSession(e,t){return te(e).backend.mintDetachedSession(t)},signInProvider(e){return te(e).backend.getCurrentSignInProvider()},listUsers(e){return te(e).backend.listUsers()},createUser(e,t){return te(e).backend.createUser(t)},updateUser(e,t,n){return te(e).backend.updateUser(t,n)},updateProfile(e,t,n){return te(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){te(e).backend.deleteUser(t)},clearUsers(e){te(e).backend.clearUsers()},subscribeUsers(e,t){return te(e).backend.subscribeUsers(t)},exportProviderConfig(e){return te(e).backend.exportProviderConfig()},restoreProviderConfig(e,t){te(e).backend.restoreProviderConfig(t)},getAuthProviderConfig(e){return te(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){te(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){te(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){te(e).backend.setProviderEnforcementDelegated(t)},setAvatarMint(e,t){te(e).backend.setAvatarMint(t)},subscribeAuthProviderConfig(e,t){return te(e).backend.subscribeProviderConfig(t)}};function da(e){return e!==void 0&&/^[0-9]+$/.test(e)?BigInt(e):0n}function IE(e,t){return e>t?e:t}function Lc(e,t){return e===void 0?t:t===void 0||da(e)>=da(t)?e:t}function Jp(e,t){return Lc(e,t)??t}function Yp(e){return BigInt(Math.floor(e*1e3))}function AE(e){return t=>String(IE(Yp(e),da(t)+1n))}const fa="pyric-storage",re="pyric-default";function ce(e,t){return`${e}/${t}`}function ii(e){const t=e.indexOf("/");return t===-1?null:{bucket:e.slice(0,t),path:e.slice(t+1)}}function OE(e){return e?`${fa}:${e}`:fa}const $E=2,Se="blobs",le="metadata",br="generations";function Qp(e,t,n){if(e.metadata.bucket!==t||e.metadata.fullPath!==n)throw new Error("A prior Storage object can only be put back at its own bucket and path.");Uc(e.blob,e.metadata)}function Uc(e,t){if(t.size!==e.size)throw new Error("Storage metadata does not match its object.")}async function PE(e=fa,t){try{const n=await UE(e);return new LE(n,t)}catch(n){return typeof indexedDB<"u"&&Xp(e,TE(n),"other tabs reload"),new ME(t)}}class DE extends Error{name="OpenBlockedError"}function TE(e){return e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?`${e.name}: ${e.message}`:String(e)}function Xp(e,t,n){console.warn(`[pyric] Storage could not use the IndexedDB store "${e}" (${t}). Storage will not persist until ${n}.`)}class Zp{uploads=new Map;beginUpload(t,n,r,s,i){const o=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`upl-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return this.uploads.set(o,{uploadId:o,bucket:t,path:n,size:r,contentType:s,customMetadata:i,parts:new Map,createdAt:Date.now()}),o}putPart(t,n,r){const s=this.uploads.get(t);if(!s){const o=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw o.code="storage/object-not-found",o}s.parts.set(n,r);let i=0;for(const o of s.parts.values())i+=o.byteLength;return{bytesReceived:i}}readUpload(t){const n=this.uploads.get(t);if(!n){const i=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw i.code="storage/object-not-found",i}let r=0;const s=Array.from(n.parts.keys()).sort((i,o)=>i-o);for(const i of s)r+=n.parts.get(i).byteLength;if(r!==n.size){const i=new Error(`storage/invalid-argument: Uploaded bytes (${r}) did not match declared size (${n.size}).`);throw i.code="storage/invalid-argument",i}return new Blob(s.map(i=>n.parts.get(i)),{type:n.contentType})}abortUpload(t){this.uploads.delete(t)}}class ME{blobs=new Map;metadata=new Map;highWater=new Map;staging=new Zp;_defaultBucket;constructor(t){this._defaultBucket=t}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||re;this._defaultBucket||(this._defaultBucket=i),Uc(n,r),r.bucket||(r.bucket=i);const o=ce(i,t),a=this.objectAt(o),l=this.highWater.get(o);return s!==void 0&&(r.generation=s(Lc(a?.metadata.generation,l))),this.blobs.set(o,n),this.metadata.set(o,r),this.highWater.set(o,Jp(l,r.generation)),a}objectAt(t){const n=this.blobs.get(t),r=this.metadata.get(t);if(!(n===void 0||r===void 0))return{blob:n,metadata:r}}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??re;r!==void 0&&Qp(r,i,t);const o=ce(i,t);return this.metadata.get(o)?.generation!==n?!1:(this.blobs.delete(o),this.metadata.delete(o),r===void 0||(this.blobs.set(o,r.blob),this.metadata.set(o,r.metadata)),!0)}async getBlob(t,n){if(n)return this.blobs.get(ce(n,t));const r=this._defaultBucket??re,s=this.blobs.get(ce(r,t));if(s!==void 0)return s;if(r!==re){const i=this.blobs.get(ce(re,t));if(i!==void 0)return i}for(const[i,o]of this.blobs.entries()){const a=ii(i);if(a&&a.path===t)return o}}async getMetadata(t,n){if(n)return this.metadata.get(ce(n,t));const r=this._defaultBucket??re,s=this.metadata.get(ce(r,t));if(s!==void 0)return s;if(r!==re){const i=this.metadata.get(ce(re,t));if(i!==void 0)return i}for(const[i,o]of this.metadata.entries()){const a=ii(i);if(a&&a.path===t)return o}}async getObject(t,n){return this.objectAt(ce(n??this._defaultBucket??re,t))}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??re;n.bucket||(n.bucket=s),this.metadata.set(ce(s,t),n)}async delete(t,n){const r=n??this._defaultBucket??re;this.blobs.delete(ce(r,t)),this.metadata.delete(ce(r,t))}async listByPrefix(t,n){const s=`${n??this._defaultBucket??re}/${t}`,i=[],o=Array.from(this.metadata.keys()).sort();for(const a of o)if(a.startsWith(s)){const l=this.metadata.get(a);l&&i.push(l)}return i}async reset(t){if(!t){this.blobs.clear(),this.metadata.clear(),this._defaultBucket=void 0;return}const n=`${t}/`;for(const r of Array.from(this.blobs.keys()))r.startsWith(n)&&this.blobs.delete(r);for(const r of Array.from(this.metadata.keys()))r.startsWith(n)&&this.metadata.delete(r)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||re;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){}scoped(t){return new Oi(this,t)}}class LE{db;staging=new Zp;_defaultBucket;closedReason;constructor(t,n){this.db=t,this._defaultBucket=n,t.addEventListener("versionchange",()=>{t.close(),this.closedReason="a newer pyric build opened it in another tab",Xp(t.name,this.closedReason,"this tab reloads")})}transaction(t,n){if(this.closedReason!==void 0)throw new Error(`The IndexedDB store "${this.db.name}" closed because ${this.closedReason}. Reload this tab to use Storage.`);return this.db.transaction(t,n)}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||re;this._defaultBucket||(this._defaultBucket=i),Uc(n,r),r.bucket||(r.bucket=i);const o=ce(i,t),a=this.transaction([Se,le,br],"readwrite"),l=BE(a,o),u=a.objectStore(br).get(o);let d;u.addEventListener("success",()=>{const h=u.result;try{s!==void 0&&(r.generation=s(Lc(l.object()?.metadata.generation,h))),a.objectStore(Se).put(n,o),a.objectStore(le).put(r,o),a.objectStore(br).put(Jp(h,r.generation),o)}catch(f){d={error:f},a.abort()}});try{await tr(a)}catch(h){throw d!==void 0?d.error:h}return l.object()}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??re;r!==void 0&&Qp(r,i,t);const o=ce(i,t),a=this.transaction([Se,le],"readwrite");let l=!1;const u=a.objectStore(le).get(o);return u.addEventListener("success",()=>{if(u.result?.generation===n){if(l=!0,r===void 0){a.objectStore(Se).delete(o),a.objectStore(le).delete(o);return}a.objectStore(Se).put(r.blob,o),a.objectStore(le).put(r.metadata,o)}}),await tr(a),l}async getBlob(t,n){const s=this.transaction(Se,"readonly").objectStore(Se);if(n)return yt(s.get(ce(n,t)));const i=this._defaultBucket??re,o=await yt(s.get(ce(i,t)));if(o!==void 0)return o;if(i!==re){const a=await yt(s.get(ce(re,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ii(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getMetadata(t,n){const s=this.transaction(le,"readonly").objectStore(le);if(n)return yt(s.get(ce(n,t)));const i=this._defaultBucket??re,o=await yt(s.get(ce(i,t)));if(o!==void 0)return o;if(i!==re){const a=await yt(s.get(ce(re,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ii(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getObject(t,n){const r=ce(n??this._defaultBucket??re,t),s=this.transaction([Se,le],"readonly"),[i,o]=await Promise.all([yt(s.objectStore(Se).get(r)),yt(s.objectStore(le).get(r))]);if(!(i===void 0||o===void 0))return{blob:i,metadata:o}}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??re;n.bucket||(n.bucket=s);const i=ce(s,t),o=this.transaction(le,"readwrite");o.objectStore(le).put(n,i),await tr(o)}async delete(t,n){const r=n??this._defaultBucket??re,s=ce(r,t),i=this.transaction([Se,le],"readwrite");i.objectStore(Se).delete(s),i.objectStore(le).delete(s),await tr(i)}async listByPrefix(t,n){const r=n??this._defaultBucket??re,s=this.transaction(le,"readonly"),i=`${r}/${t}`,o=IDBKeyRange.bound(i,i+"�",!1,!1);return yt(s.objectStore(le).getAll(o))}async reset(t){const n=this.transaction([Se,le],"readwrite");if(!t)n.objectStore(Se).clear(),n.objectStore(le).clear(),this._defaultBucket=void 0;else{const r=`${t}/`,s=IDBKeyRange.bound(r,r+"�",!1,!1);n.objectStore(Se).delete(s),n.objectStore(le).delete(s)}await tr(n)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||re;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){this.db.close()}scoped(t){return new Oi(this,t)}}class Oi{underlying;bucket;constructor(t,n){this.underlying=t,this.bucket=n}get replacedObjectsOnDisk(){return this.underlying.replacedObjectsOnDisk}async put(t,n,r,s){const i=r.bucket?r:{...r,bucket:this.bucket},o=await this.underlying.put(t,n,i,s);return r.generation=i.generation,o}deleteIfGeneration(t,n,r){return this.underlying.deleteIfGeneration(t,n,r??this.bucket)}replaceIfGeneration(t,n,r,s){return this.underlying.replaceIfGeneration(t,n,r,s??this.bucket)}references(t){if(this.underlying.references)return this.underlying.references(t??this.bucket);throw new Error("The underlying storage backend keeps no object files to refer to.")}putReference(t,n,r,s){const i=s.bucket?s:{...s,bucket:this.bucket};if(this.underlying.putReference)return this.underlying.putReference(t,n,r,i);throw new Error("The underlying storage backend keeps no object files to refer to.")}getBlob(t,n){return this.underlying.getBlob(t,n??this.bucket)}getMetadata(t,n){return this.underlying.getMetadata(t,n??this.bucket)}getObject(t,n){return this.underlying.getObject(t,n??this.bucket)}putMetadata(t,n,r){const s=n.bucket?n:{...n,bucket:this.bucket};return this.underlying.putMetadata(t,s,r??this.bucket)}delete(t,n){return this.underlying.delete(t,n??this.bucket)}listByPrefix(t,n){return this.underlying.listByPrefix(t,n??this.bucket)}reset(t){return this.underlying.reset(t??this.bucket)}beginUpload(t,n,r,s,i){const o=t??this.bucket;if(this.underlying.beginUpload)return this.underlying.beginUpload(o,n,r,s,i);throw new Error("Chunked upload not supported by underlying storage backend")}putPart(t,n,r){if(this.underlying.putPart)return this.underlying.putPart(t,n,r);throw new Error("Chunked upload not supported by underlying storage backend")}readUpload(t){if(this.underlying.readUpload)return this.underlying.readUpload(t);throw new Error("Chunked upload not supported by underlying storage backend")}abortUpload(t){return this.underlying.abortUpload?this.underlying.abortUpload(t):Promise.resolve()}close(){this.underlying.close()}scoped(t){return t===this.bucket?this:this.underlying.scoped?this.underlying.scoped(t):new Oi(this.underlying,t)}}function UE(e){return new Promise((t,n)=>{try{if(typeof indexedDB>"u"||!indexedDB.open)return n(new Error("IndexedDB not available"));const r=indexedDB.open(e,$E);r.addEventListener("upgradeneeded",()=>{const i=r.result;i.objectStoreNames.contains(Se)||i.createObjectStore(Se),i.objectStoreNames.contains(le)||i.createObjectStore(le),i.objectStoreNames.contains(br)||i.createObjectStore(br)});let s=!1;r.addEventListener("success",()=>{if(s){r.result.close();return}t(r.result)}),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>{s=!0,n(new DE("another tab holds it open on an older pyric build"))})}catch(r){n(r)}})}function BE(e,t){const n=e.objectStore(Se).get(t),r=e.objectStore(le).get(t);return{object(){const s=n.result,i=r.result;if(!(s===void 0||i===void 0))return{blob:s,metadata:i}}}}function yt(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function tr(e){return new Promise((t,n)=>{e.addEventListener("complete",()=>t()),e.addEventListener("error",()=>n(e.error)),e.addEventListener("abort",()=>n(e.error??new Error("IndexedDB transaction aborted")))})}class em{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}function Uu(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const FE=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function tm(e){return{segments:e.path.segments.map(qE),children:e.children.map(tm),allows:e.allows.map(t=>({verbs:t.operations,condition:se(t.condition)})),functions:e.functions.map(ha)}}function qE(e){switch(e.type){case"literal":return{kind:"literal",value:e.value};case"wildcard":return{kind:"param",name:e.name};case"recursive":return{kind:"wildcard",name:e.name}}}function ha(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>{const n={name:t.name,value:se(t.value)};return Oh(t,n),n}),body:se(e.body)}}function se(e){const t=VE(e);return Oh(e,t),t}function VE(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Te(e.value)}:e.value instanceof Uint8Array?{kind:"literal",value:new ji(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:se(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:se(e.object),method:e.method,args:e.args.map(se)};case"bracketAccess":return{kind:"index",target:se(e.object),index:se(e.index)};case"sliceAccess":return{kind:"slice",target:se(e.object),start:se(e.start),end:se(e.end)};case"binaryOp":if(!FE.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:se(e.left),right:se(e.right)};case"unaryOp":if(e.op!=="!"&&e.op!=="-")throw new SyntaxError(`Unsupported unary operator '${e.op}' in storage rules.`);return{kind:"unary",op:e.op,arg:se(e.operand)};case"ternary":return{kind:"ternary",cond:se(e.condition),then:se(e.consequent),else:se(e.alternate)};case"inExpr":return{kind:"in",element:se(e.element),collection:se(e.collection)};case"isExpr":return{kind:"is",value:se(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(se)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:se(t.key),value:se(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:se(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(se)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function pa(e){const t=_w(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: ${Sw(t.error,e)}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r=kw(n);if(r.length>0)throw new SyntaxError(`Storage rules do not compile: ${Ew(r)}`);const s=(n.imports??[]).flatMap(d=>d.functions.map(h=>({name:h,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:d.module,scopeKind:"global",declCaptures:new Set}))),i=(n.functions??[]).map(d=>{const h=ha(d);return h.scopeKind="global",h.declCaptures=new Set,h}),o=new Map;for(const d of s)o.set(d.name,d);for(const d of i)o.set(d.name,d);for(const d of o.values())d.declScope=o;const a=(n.service.functions??[]).map(d=>{const h=ha(d);return h.scopeKind="service",h.declCaptures=new Set,h}),l=new Map(o);for(const d of a)l.set(d.name,d);for(const d of a)d.declScope=l;const u={segments:[],children:[tm(n.service.match)],allows:[],functions:[...s,...i,...a],visibleFuncs:l};for(const d of u.children)nm(d,l,new Set);return{_root:u,_version:n.version}}function nm(e,t,n){const r=new Set(n);for(const i of e.segments)(i.kind==="param"||i.kind==="wildcard")&&r.add(i.name);const s=new Map(t);for(const i of e.functions)s.set(i.name,i);e.visibleFuncs=s;for(const i of e.functions)i.declScope=s,i.scopeKind="match",i.declCaptures=r;for(const i of e.children)nm(i,s,r)}function fe(e,t){if(e.kind==="methodcall"&&e.target.kind==="ident"&&e.target.name==="firestore"&&!t.has("firestore")&&(e.method==="get"||e.method==="exists"))return!0;switch(e.kind){case"member":return fe(e.target,t);case"index":return fe(e.target,t)||fe(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>fe(n,t));case"unary":return fe(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>fe(n,t));case"in":return fe(e.element,t)||fe(e.collection,t);case"is":return fe(e.value,t);case"list":return e.elements.some(n=>fe(n,t));case"map":return e.entries.some(({key:n,value:r})=>fe(n,t)||fe(r,t));case"binary":return fe(e.left,t)||fe(e.right,t);case"call":return e.args.some(n=>fe(n,t));case"methodcall":return fe(e.target,t)||e.args.some(n=>fe(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&fe(n.expr,t));case"ident":case"literal":return!1}}function rm(e,t=new Set){const n=new Set(t);for(const r of e.segments)r.kind!=="literal"&&n.add(r.name);if(e.allows.some(({condition:r})=>r&&fe(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(fe(i.value,s))return!0;s.add(i.name)}if(fe(r.body,s))return!0}return e.children.some(r=>rm(r,n))}function ie(e){if(e.kind==="methodcall"&&e.method==="matches"&&e.args.length===1){const t=e.args[0],n=t?.kind==="literal"&&typeof t.value=="string"?jw(t.value):null;if(n!==null)throw new SyntaxError(`Storage rules do not compile: ${n}`)}switch(e.kind){case"member":ie(e.target);return;case"index":ie(e.target),ie(e.index);return;case"slice":ie(e.target),ie(e.start),ie(e.end);return;case"unary":ie(e.arg);return;case"ternary":ie(e.cond),ie(e.then),ie(e.else);return;case"in":ie(e.element),ie(e.collection);return;case"is":ie(e.value);return;case"list":for(const t of e.elements)ie(t);return;case"map":for(const{key:t,value:n}of e.entries)ie(t),ie(n);return;case"binary":ie(e.left),ie(e.right);return;case"call":for(const t of e.args)ie(t);return;case"methodcall":ie(e.target);for(const t of e.args)ie(t);return;case"path":for(const t of e.segments)t.kind==="interp"&&ie(t.expr);return;case"ident":case"literal":return}}function sm(e){for(const{condition:t}of e.allows)t&&ie(t);for(const t of e.functions){for(const n of t.lets)ie(n.value);ie(t.body)}for(const t of e.children)sm(t)}function WE(e){let t=e,n=[],r=[],s=[],i=pa(t);if(i._version!=="2+modules"){if(i._root.functions.some(a=>a.unresolvedImport!==void 0))throw new SyntaxError("Import statements require rules_version = '2+modules'.")}else{const a=jh(t);if(!a.success)throw new SyntaxError(`Storage rules module resolution failed (${a.error.code}): ${a.error.message}`);t=a.data.resolved,n=a.data.modules,r=a.data.bundledModules,s=a.data.evidenceIds,i=pa(t)}sm(i._root);const o=zE(t,n,r,s,i);return{rules:i,resolution:o}}function zE(e,t,n,r,s){const i=new Set;for(const o of r)o.startsWith("storage-rules#")&&i.add(o);return rm(s._root)&&i.add("storage-rules#131"),Object.freeze({targetService:"firebase.storage",source:e,modules:Object.freeze([...t]),bundledModules:Object.freeze([...n]),evidenceIds:Object.freeze([...i].sort())})}const HE=/^gs:\/\/([^/]+)\/?$/;function Bc(e,t){return t!==void 0&&t!==""?HE.exec(t)?.[1]??t:e}function Bu(e,t,n){return e.bucket===t?{...e,bucket:n}:e}function KE(e,t,n){const r=e.request.path.replace(/^\/+/,""),s=e.request.resource;return{...e,request:{...e.request,path:r===""?`b/${n}/o`:`b/${n}/o/${r}`,...s===void 0?{}:{resource:Bu(s,t,n)}},...e.resource==null?{}:{resource:Bu(e.resource,t,n)}}}const Fc="pyric-default",$i=Symbol.for("pyric/storage/target");function qt(e){return e.currentAuth?.()??e.context.auth}const GE=Symbol.for("pyric.storage.service-caches"),JE=globalThis,Et=JE[GE]??={openServices:new WeakMap,hostBackends:new WeakMap,scopedServices:new WeakMap,sandboxHandles:new WeakMap,bareSandboxHandles:new WeakMap,adminContextHandles:new WeakMap,bareAdminHandles:new WeakMap},YE=Et.bucketRules??=new WeakMap,Fu=Et.defaultStoreNames??=new WeakMap,qu=Et.openServices,QE=Et.hostBackends,Vu=Et.scopedServices;function XE(e,t,n){let r=Vu.get(e);r||(r=new Map,Vu.set(e,r));let s=r.get(t);return s||(s=n.then(i=>{const o=i.backend.scoped?i.backend.scoped(t):i.backend;return new em(o,i.rules,i.crossServiceIam)}),r.set(t,s)),s}Et.sandboxHandles;Et.bareSandboxHandles;function Wu(e,t,n,r,s){if(n===void 0||n===r)return;const i=r===null?`without ${e}`:`with a different ${t}`;throw new Error(`pyric/storage: ${s} received a ${t}, but this sandbox's storage service is already open ${i}. ${e} is honored only on the FIRST storage call per Sandbox, so this value would be silently discarded. Configure it on the first storage call for this sandbox.`)}function ZE(e,t){if(!im(e)||e.bucketName===void 0)return null;const r=Fu.get(e.sandbox);return r!==void 0?r:(Fu.set(e.sandbox,t),t)}function im(e){return e.bucket===Fc}function ej(e,t){const n=YE.get(t.sandbox);if(n===void 0)return e.rules?{kind:"rules",rules:e.rules}:{kind:"none"};const r=Bc(t.bucket,t.bucketName),s=ZE(t,r);if(s!==null&&s!==r)return{kind:"second-default",bucket:r,defaultBucket:s};const i=n.get(r);if(i!==void 0)return{kind:"rules",rules:i.rules};const o=im(t)?e.rules:null;return o?{kind:"rules",rules:o}:{kind:"locked",bucket:r}}function tj(e,t,n){const r=qu.get(e);if(r!==void 0)return Wu("rules","rules source",t.rules,r.rulesSource,n),Wu("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let i=null,o=null;const a=t.rules;if(typeof a=="string"&&a.length>0){const m=WE(a);i=m.rules,o=m.resolution}const u=t.crossServiceIam??"granted",d=QE.get(e);let h;d!==void 0?h=Promise.resolve(d):h=PE(t.dbName??OE(t.projectId),t.bucket??Fc);const p=h.then(m=>new em(m,i,u));return qu.set(e,{service:p,rulesSource:t.rules??null,rulesResolution:o,crossServiceIam:u}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await p).backend.reset()}}),p}function fo(e){return e instanceof Cw||"sandbox"in e&&e.sandbox!==void 0}const ho=Et.adminContextHandles,po=Et.bareAdminHandles;function nj(e,t={}){const n=!fo(e),r=fo(e)?e.sandbox:e,s=tj(r,t,"getAdminStorageSandbox"),i=t.bucket??Fc;if(n){const p=po.get(r)?.get(i);if(p)return p}const o=fo(e)?e:r.withAuth(null),a=o.operationContext.authLens.mode==="admin"?o:$h(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),l=ho.get(o)?.get(i);if(l)return l;const u=XE(r,i,s),d={kind:"sandbox",sandbox:r,context:a,bucket:i,servicePromise:u,admin:!0},h=Object.freeze({[$i]:d});let f=ho.get(o);if(f||(f=new Map,ho.set(o,f)),f.set(i,h),n){let p=po.get(r);p||(p=new Map,po.set(r,p)),p.set(i,h)}return h}function Wt(e,t){const n=Rw(t,Jo(e.context.operationContext));return{...t,...Jo(n),service:"storage"}}function Me(e){const t=e[$i];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function zt(e){return Me(e).servicePromise}function rj(e){return`storage/${e}`}class jt extends Error{code;constructor(t,n){const r=rj(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,jt.prototype)}}function om(e){return new jt("object-not-found",`no object at "${e}".`)}function zu(e,t,n){return new jt("unauthorized",hE(`${e} "${t}" denied by rules${n}`))}function Pi(e){return new jt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Hu(){return new jt("canceled","User canceled the upload/download.")}const ws="([A-Za-z0-9.\\-_]+)",sj=e=>e,ij=[{pattern:new RegExp(`^gs://${ws}(?:/(.*))?$`,"i"),path:sj},{pattern:new RegExp(`^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/${ws}/o(?:/([^?#]*).*)?$`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://(?:storage\\.googleapis\\.com|storage\\.cloud\\.google\\.com)/${ws}/([^?#]*)`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://[^/?#]+/__pyric/storage/v0/b/${ws}/o/([^?#]+)`),path:decodeURIComponent}];function oj(e){for(const t of ij){const n=t.pattern.exec(e);if(n!==null)return{bucket:n[1],path:t.path(n[2]??"")}}}const aj=/^[A-Za-z]+:\/\//,qc=/^data:[^,]*,/i;function Ku(e,t){return new jt("invalid-url",`Invalid URL '${e}'. ${t}`)}function cj(e){return aj.test(e)||qc.test(e)}function lj(e){if(qc.test(e))throw Ku(e.length>64?`${e.slice(0,64)}...`:e,"A data: URI carries an object's bytes, not its location. Reference the object by its path or its gs:// URL.");const n=oj(e);if(n!==void 0)return n;throw Ku(e,"Expected a gs:// URL or a Storage download URL.")}function ma(e,t){const n=e??"";if(!cj(n))return n;const s=qc.test(n);if(!t&&!s)throw new jt("invalid-argument","To use ref(service, url), the first argument must be a Storage instance.");return lj(n).path}function Pr(e,t){return dj(e)?(Me(e.storage),new Dr(e.storage,uj(e.fullPath,ma(t,!1)))):(Me(e),new Dr(e,am(ma(t,!0))))}class Dr{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Me(t);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const t=this.fullPath.lastIndexOf("/");return t===-1?this.fullPath:this.fullPath.slice(t+1)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new Dr(this.storage,n)}get root(){return this.fullPath===""?this:new Dr(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function am(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function uj(e,t){const n=am(t);return e===""?n:n===""?e:`${e}/${n}`}function dj(e){if(e===null||typeof e!="object"||$i in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}const oi=new WeakMap;function Lt(e){oi.get(e)?.progress()}function ai(e){const t=oi.get(e);t?.delivered(void 0,{}),t?.progress()}function qn(e,t){return(n,...r)=>{const s=Yr.begin({app:n.storage??n.port??n,method:e,kind:"operation",source:{service:"storage",target:`${n.bucket}/${n.fullPath}`,key:`storage:${n.bucket}/${n.fullPath}`}});try{const i=t(n,...r);return e==="uploadBytesResumable"&&oi.set(i,s),i.then(o=>{const a=fj(e,o);s.delivered(void 0,e.startsWith("get")||e==="listAll"?a:{}),e==="uploadBytesResumable"&&s.progress(),s.complete(e.startsWith("get")||e==="listAll"?void 0:a)},()=>{s.fail(),oi.delete(i)}),i}catch(i){throw s.fail(),i}}}function fj(e,t){if(e==="getBytes"&&t instanceof ArrayBuffer)return{downloadedBytes:t.byteLength};if(e==="getBlob"&&t&&typeof t=="object"&&"size"in t&&typeof t.size=="number")return{downloadedBytes:t.size};if(e.startsWith("upload")&&t&&typeof t=="object"&&"metadata"in t){const n=t.metadata;if(typeof n.size=="number")return{uploadedBytes:n.size}}return{}}class K{message;constructor(t){this.message=t}}function J(e){return e instanceof K}function ci(e){if(typeof e=="number")return e;if(e instanceof Te)return e.value}class W extends Error{}class is extends W{}class os extends W{}class Gu extends os{position;constructor(t,n){super(t),this.position=n}}function hj(e){return e instanceof W&&!(e instanceof is)&&!(e instanceof os)}function Le(e){return new W(Nw(e))}function hn(e){if(e.args.length!==0)throw new W(`${e.method}() expects no arguments`)}function Qe(e,t){return ct(e.args,t)}function as(e,t){const n=Qe(e,t);return J(n)||t.expressionBudget?.node(e),n}function Ae(e,t){if(hn(t),e instanceof it){const n=e.callMethod(t.method,[]);if(n!==Yo)return n}throw Le(t.method)}const pj=/^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|\$\(([A-Za-z_][A-Za-z0-9_]*)\))$/;class ze extends it{path;typeName="path";bindings;constructor(t,n={}){super(),this.path=t,this.bindings=n}get segments(){return this.path.split("/").filter(Boolean)}bind(t){const n=[],r={...this.bindings};for(const s of this.segments){const i=pj.exec(s);if(!i){n.push(s);continue}const o=i[1]??i[2];if(Object.hasOwn(t,o)){const a=t[o];if(a==null||typeof a!="string"&&typeof a!="number")throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const l=String(a);n.push(l),r[o]=l}else n.push(s)}return new ze("/"+n.join("/"),r)}valueOf(){return NaN}toJSON(){return{__type:"path",path:this.toString()}}equals(t){return(t instanceof ze||t instanceof it&&t.typeName==="path")&&String(t)===this.toString()}toString(){return this.path.startsWith("/")?this.path:`/${this.path}`}}function mj(e,t,n){if(!(e instanceof ze))throw Le("bind");const r=Qe(t,n);if(J(r))return r;if(r.length!==1)throw new W(`Incorrect number of arguments. Received: ${r.length}. Expected: path.bind(map).`);const[s]=r;if(!Bt(s))return new K("path.bind() requires a map argument");try{return e.bind(s)}catch(i){return new K(i.message)}}const yj={bind:mj};function cm(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function gj(e){return cm({size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Ju(e.timeCreated),updated:Ju(e.updated)})}function Ju(e){if(e===void 0)return;const t=Date.parse(e);if(!Number.isNaN(t))return Er.fromMillis(t)}function bj(e,t){const n=e.request.auth;let r;return n==null?r=new K("Property auth is undefined on object."):r=Ei(n),{auth:r,resource:e.request.resource!==void 0?cm(e.request.resource):new K("Property resource is undefined on object."),method:e.request.method,path:new ze(e.request.path),time:Er.fromMillis(t)}}const wj=["addedKeys","affectedKeys","changedKeys","removedKeys","unchangedKeys"];function vj(e,t,n){return e instanceof Qr?Vc(e,t,n):(hn(t),typeof e=="string"||Array.isArray(e)?e.length:Bt(e)?Object.keys(e).length:Ae(e,t))}function Yu(e,t,n){if(!Bt(e))throw Le(t.method);const r=Qe(t,n);if(J(r))return r;const s=Aw(t.method,e,r);if(s instanceof Ow)throw new W(s.message);return s}function Vc(e,t,n){const r=Qe(t,n);if(J(r))return r;const s=Pw(e,t.method,r);if(s instanceof Dw)throw new W(s.message);return s}const xj={concat:(e,t)=>Lw(e,t),join:(e,t)=>Mw(e,t),removeAll:(e,t)=>Tw(e,t)};function mo(e,t,n){if(!Array.isArray(e))throw Le(t.method);const r=Qe(t,n);if(J(r))return r;const s=xj[t.method](e,r);if(s instanceof Ph)throw new W(s.message);return s}function _j(e,t,n){if(!Bt(e))throw Le(t.method);if(t.args.length!==2)throw new W("get() expects a key and default value");const r=Qe(t,n);if(J(r))return r;const[s,i]=r;if(typeof s=="string")return Object.hasOwn(e,s)&&e[s]!==void 0?e[s]:i;if(Array.isArray(s)){for(const a of s)if(typeof a!="string")throw new W("get() key list elements must be strings");let o=e;for(const a of s){if(!Bt(o)||!Object.hasOwn(o,a)||o[a]===void 0)return i;o=o[a]}return o}throw new W("get() key must be a string or list of strings")}function yo(e,t,n){if(e instanceof Qr)return Vc(e,t,n);if(!Array.isArray(e))throw Le(t.method);const r=Qe(t,n);if(J(r))return r;const s=$w(t.method,e,r);if(s instanceof Ph)throw new W(s.message);return s}function Sj(e,t){if(!Array.isArray(e))throw Le(t.method);if(t.args.length!==0)throw new W(`Incorrect number of arguments. Received: ${t.args.length}. Expected: list.toSet().`);return new Qr(e)}function kj(e,t,n){if(!(e instanceof Qr))throw Le(t.method);return Vc(e,t,n)}function Ej(e,t,n){if(!Bt(e))throw Le(t.method);if(t.args.length!==1)throw new W("diff() expects one map argument");const r=Qe(t,n);if(J(r))return r;const[s]=r;if(!Bt(s))throw new W(`diff() argument must be a map, got ${Pe(s)}`);return new Dh(s,e)}function jj(e,t){if(hn(t),!(e instanceof Dh))throw Le(t.method);return e[t.method]()}function Qu(e,t){return Object.fromEntries(e.map(n=>[n,t]))}const Cj={concat:mo,diff:Ej,get:_j,hasAll:yo,hasAny:yo,hasOnly:yo,join:mo,keys:Yu,removeAll:mo,size:vj,toSet:Sj,values:Yu,...Qu([...Iw],kj),...Qu(wj,jj)};function Rj(e){if(typeof e=="number")return e;if(e instanceof Te)return e.value}function Nj(e,t,n,r){const i=f=>f*Math.PI/180,o=i(e),a=i(n),l=i(n-e),u=i(r-t),d=Math.sin(l/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}function Tr(e){return e instanceof li?{latitude:e.latitude,longitude:e.longitude}:e instanceof Th?{latitude:e.lat,longitude:e.lng}:null}function Ij(e,t){const n=as(e,t);if(J(n))return n;if(e.method!=="value")return new K(`unsupported latlng.${e.method}()`);const[r,s]=n.map(Rj);return n.length!==2||r===void 0||s===void 0||!Number.isFinite(r)||!Number.isFinite(s)?new K("latlng.value() expects (latitude: number, longitude: number)"):r<-90||r>90?new K(`Latitude must be in the range [-90, 90], got ${r}.`):s<-180||s>180?new K(`Longitude must be in the range [-180, 180], got ${s}.`):new li(r,s)}class li extends it{latitude;longitude;typeName="latlng";constructor(t,n){super(),this.latitude=t,this.longitude=n}valueOf(){return NaN}toJSON(){return{__type:"latlng",latitude:this.latitude,longitude:this.longitude}}equals(t){const n=Tr(t);return n!==null?n.latitude===this.latitude&&n.longitude===this.longitude:t instanceof it&&t.typeName==="latlng"&&t.latitude===this.latitude&&t.longitude===this.longitude}toString(){return`[${this.latitude}, ${this.longitude}]`}}function Aj(e,t){const n=Tr(e);if(n===null)throw Le("latitude");return hn(t),new Te(n.latitude)}function Oj(e,t){const n=Tr(e);if(n===null)throw Le("longitude");return hn(t),new Te(n.longitude)}function $j(e,t,n){const r=Tr(e);if(r===null)throw Le("distance");const s=Qe(t,n);if(J(s))return s;if(s.length!==1)throw new W(`Incorrect number of arguments. Received: ${s.length}. Expected: latlng.distance(latlng).`);const i=Tr(s[0]);return i===null?new K("latlng.distance() requires a latlng argument"):new Te(Nj(r.latitude,r.longitude,i.latitude,i.longitude))}const Pj={distance:$j,latitude:Aj,longitude:Oj};function ya(e){if(e==null)return e;if(typeof e=="number")return Number.isInteger(e)?e:new Te(e);if(e instanceof Date)return Er.fromMillis(e.getTime());if(e instanceof Uint8Array)return new ji(e);if(e instanceof Th)return new li(e.lat,e.lng);if(e instanceof Uw)return new ze(e.toString());if(e instanceof it)return e;if(typeof e=="object"){if(Array.isArray(e))return e.map(ya);const t=e,n=Object.keys(t),r=t.latitude??t._latitude,s=t.longitude??t._longitude;if(t.__type==="latlng"||n.length===2&&typeof r=="number"&&typeof s=="number")return new li(r,s);if(t.__type==="path"||n.length===1&&typeof t.path=="string"&&t.path.startsWith("/databases/"))return new ze(t.path);const i={};for(const[o,a]of Object.entries(t))i[o]=ya(a);return i}return e}function Dj(e,t){if(t.expressionBudget?.node(e),e.method!=="get"&&e.method!=="exists")throw new is(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new W(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new W(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];let r;if(n.kind==="path"){t.expressionBudget?.node(n);for(const l of n.segments)l.kind==="literal"&&t.expressionBudget?.pathSegment(n);r=Xu(n,t)}else{const l=et(n,t);if(J(l))return l;if(lm(l)){const u=um(l).map(d=>({kind:"literal",value:d}));r=Xu({segments:u},t)}else return new K(`Function not found error: Name: [${e.method}].`)}const s=r.map(Tj).join("/");if(!t.firestoreAccesses.has(s)){if(t.firestoreAccesses.size>=2)throw new os("firestore access limit exceeded: at most two distinct documents");t.firestoreAccesses.add(s)}const i=r.find(l=>l.includes("/"));if(i!==void 0)return new K(`Service call error. Function: [firestore.${e.method}]: the path segment "${i}" holds a "/", and an interpolated string is one segment, so no document has this path`);const o=r.join("/");if(e.method==="exists")return t.firestoreLookup.exists(o);const a=t.firestoreLookup.get(o);return a===null?new K(`firestore.get() targeted a nonexistent document: ${o}`):{data:ya(a)}}function lm(e){return e instanceof ze||e instanceof it&&e.typeName==="path"}function um(e){return e instanceof ze?e.segments:String(e).split("/").filter(Boolean)}function Tj(e){return e.replaceAll("%","%25").replaceAll("/","%2F")}function Mj(e){if(typeof e=="string")return[e];if(typeof e=="number")return[String(e)];if(lm(e))return um(e);throw new W(`Firestore path interpolation resolved to ${Pe(e)} (expected a string or a path)`)}function Xu(e,t){const n=ct(e.segments.flatMap(o=>o.kind==="literal"?[]:[o.expr]),t);if(J(n))throw new W(n.message);let r=0;const s=e.segments.flatMap(o=>o.kind==="literal"?[o.value]:Mj(n[r++]));if(s.length<4||s[0]!=="databases"||s[2]!=="documents")throw new W(`malformed Firestore path — expected /databases/<db>/documents/... , got /${s.join("/")}`);if(s[1]!=="(default)")throw new W(`Storage rules may access only the default Firestore database, got ${s[1]}`);const i=s.slice(3);if(i.length===0||i.length%2!==0)throw new W(`Firestore path does not point at a document (needs an even segment count): ${i.join("/")}`);return i}const Lj=new Set(["crc32","crc32c","md5","sha256"]);function Uj(e,t){if(!Lj.has(e.method))throw new is(`unsupported method hashing.${e.method}()`);const n=as(e,t);if(J(n))return n;if(n.length!==1)throw new W(`hashing.${e.method}() expects a single string or bytes argument`);const[r]=n;if(typeof r!="string"&&!(r instanceof ji))throw new W(`Unsupported operation error. Received: hashing.${e.method}(${Pe(r)}). Expected: hashing.${e.method}(bytes), hashing.${e.method}(string).`);return Bw(e.method,[r])}const Bj={toBase64:Ae,toHexString:Ae};function Fj(e,t){const n=as(e,t);if(J(n))return n;const r=Fw(e.method,n);return r instanceof qw?new K(r.message):r}function cs(e,t){if(typeof e!="string")throw Le(t.method);return e}function dm(e,t){if(e.args.length!==1)throw new W(`${e.method}() expects a single pattern argument`);const n=Qe(e,t);if(J(n))return n;const[r]=n;if(typeof r!="string")throw new W(`${e.method}() pattern must be a string`);return r}function qj(e,t,n){const r=cs(e,t),s=dm(t,n);return typeof s!="string"?s:Wc(()=>Ww(s,r))}function Vj(e,t,n){const r=cs(e,t),s=dm(t,n);return typeof s!="string"?s:Wc(()=>zw(r,s))}function Wj(e,t,n){const r=cs(e,t),s=Qe(t,n);if(J(s))return s;const[i,o]=s;if(s.length!==2||typeof i!="string"||typeof o!="string")throw new W("replace() expects (pattern: string, replacement: string)");return Wc(()=>Hw(r,i,o))}function Wc(e){try{return e()}catch(t){throw new W(t.message)}}function go(e,t){const n=cs(e,t);return hn(t),t.method==="lower"?n.toLowerCase():t.method==="upper"?n.toUpperCase():Vw(n)}function zj(e,t){const n=cs(e,t);return hn(t),ji.fromUtf8(n)}const Hj={lower:go,matches:qj,replace:Wj,split:Vj,toUtf8:zj,trim:go,upper:go},Zu=["w","d","h","m","s","ms","ns"],Kj=-621355968e5,Gj=0xe677d21fdbff;function Jj(e,t){const n=as(e,t);if(J(n))return n;if(e.method==="value"){if(n.length!==1||typeof n[0]!="number"||!Number.isInteger(n[0]))throw new W("timestamp.value() expects (epochMillis: number)");const r=n[0];if(r<Kj||r>Gj)throw new W("timestamp.value() out of range [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999Z]");return Er.fromMillis(r)}if(e.method==="date"){if(n.length!==3||!n.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new W("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;try{return Er.fromYMD(r,s,i)}catch(o){throw new W(o.message)}}throw new W(`unsupported timestamp.${e.method}()`)}function Yj(e,t){const n=as(e,t);if(J(n))return n;if(e.method==="value"){if(n.length!==2||typeof n[0]!="number"||!Number.isInteger(n[0])||typeof n[1]!="string")throw new W("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n;if(!Zu.includes(s))throw new W(`duration.value() got unknown unit "${s}", expected one of ${Zu.join(", ")}`);return ed(()=>ms.fromValue(r,s))}if(e.method==="time"){if(n.length!==4||!n.every(a=>typeof a=="number"&&Number.isInteger(a)))throw new W("duration.time() expects (hours, minutes, seconds, nanos) numbers");const[r,s,i,o]=n;return ed(()=>ms.fromTime(r,s,i,o))}if(e.method==="abs"){if(n.length!==1||!(n[0]instanceof ms))throw new W("duration.abs() expects a single duration");return ms.abs(n[0])}throw new W(`unsupported duration.${e.method}()`)}function ed(e){try{return e()}catch(t){throw t instanceof Mh?new W(t.message):t}}const Qj={date:Ae,day:Ae,dayOfWeek:Ae,dayOfYear:Ae,hours:Ae,minutes:Ae,month:Ae,nanos:Ae,seconds:Ae,time:Ae,toMillis:Ae,year:Ae},Xj=new Map([["duration",Yj],["firestore",Dj],["hashing",Uj],["latlng",Ij],["math",Fj],["timestamp",Jj]]),Zj=nC([Bj,Cj,Pj,yj,Hj,Qj]);function eC(e,t){const n=tC(e,t);if(n!==void 0)return n(e,t);const r=Zj.get(e.method);if(r===void 0)throw new is(`unsupported method .${e.method}()`);const s=Mr(e.target,t);return J(s)?(Qe(e,t),s):r(s,e,t)}function tC(e,t){if(e.target.kind!=="ident")return;const n=e.target.name;if(!(Object.hasOwn(t.locals,n)||Object.hasOwn(t.params,n)))return Xj.get(n)}function nC(e){const t=new Map;for(const n of e)for(const[r,s]of Object.entries(n)){if(t.has(r))throw new Error(`storage rules method .${r}() has two evaluators`);t.set(r,s)}return t}const rC=new Set(["timestamp","duration","bytes","latlng","path"]);function sC(e,t){switch(t){case"string":return typeof e=="string";case"bool":return typeof e=="boolean";case"int":return typeof e=="number"&&Number.isInteger(e);case"float":return e instanceof Te||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Te||typeof e=="number";case"list":return Array.isArray(e);case"set":return e instanceof Qr;case"map":return Bt(e);case"null":return e===null}return rC.has(t)?e instanceof it&&e.typeName===t:new K(`'is ${t}' is not supported by the storage evaluator.`)}function td(e){return e instanceof it&&!(e instanceof Te)}function iC(e,t,n){try{return oC(e,t,n)}catch(r){if(r instanceof Mh)return new K(r.message);throw r}}function oC(e,t,n){if(t instanceof it){const r=t.binaryOp(e,n);if(r!==Yo)return r}if(e==="+"&&n instanceof it){const r=n.binaryOp(e,t);if(r!==Yo)return r}return zc(e,t,n)}function zc(e,t,n){return new K(`Unsupported operation error. Received: ${Pe(t)} ${e} ${Pe(n)}.`)}function nd(e){return e instanceof Te}function aC(e,t,n){if(e==="+"&&typeof t=="string"&&typeof n=="string")return t+n;const r=ci(t),s=ci(n);if(r===void 0||s===void 0)return zc(e,t,n);const i=nd(t)||nd(n);let o;switch(e){case"+":o=r+s;break;case"-":o=r-s;break;case"*":o=r*s;break;case"/":if(!i&&s===0)return new K($l);o=i?r/s:Math.trunc(r/s);break;case"%":if(!i&&s===0)return new K($l);o=r%s;break}return i?new Te(o):o}function cC(e,t,n){const r=ci(t),s=ci(n);return r!==void 0&&s!==void 0?rd(e,r,s):typeof t=="string"&&typeof n=="string"?rd(e,t,n):zc(e,t,n)}function rd(e,t,n){switch(e){case"<":return t<n;case">":return t>n;case"<=":return t<=n;case">=":return t>=n}}function lC(e){return e.split("/").filter(t=>t.length>0)}function gn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function sd(e,t,n,r){let s=0;const i={...n},o=Lh(r);for(let a=0;a<e.length;a++){const l=e[a];if(l.kind==="wildcard"){const u=e.length-1-a,d=t.length-s-u;if(d<o)return null;const h=t.slice(s,s+d);i[l.name]=new ze("/"+h.join("/")),s+=d;continue}if(s>=t.length)return null;if(l.kind==="literal"){if(t[s]!==l.value)return null;s++}else i[l.name]=t[s],s++}return{left:t.slice(s),params:i}}function fm(e,t,n=new Date,r){const s=n.getTime(),i=lC(t.request.path),o=[],a=new Set,l=new Kw((g,b)=>new Gu(g,b));let u,d=!1,h;const f=new Set(Uu(t.request.method));function p(g,b,w){if(d)return!1;const x=sd(g.segments,b,w,e._version);if(!x)return!1;const v=x.params,_=x.left;if(_.length===0)for(const k of g.allows){const R=new Set(k.verbs.flatMap(Uu));if(![...f].some(A=>R.has(A)))continue;let P;try{let A=!0;if(k.condition&&(A=et(k.condition,{input:t,now:s,params:v,matchParams:v,scopeKind:"match",locals:{},funcs:g.visibleFuncs??new Map,firestoreLookup:r,firestoreAccesses:a,expressionBudget:l})),typeof A=="boolean")P=A;else{let E;J(A)?E=A:E=new K(`Allow condition expected bool, got ${Pe(A)}.`),h??=E.message,o.push(`match ${gn(g.segments)} ${t.request.method}: ${E.message}`);continue}}catch(A){if(A instanceof Gu)return d=!0,h===void 0?(u={message:A.message,position:A.position},o.push(`match ${gn(g.segments)} ${t.request.method}: ${Jw(A.message,A.position)}`)):o.push(`match ${gn(g.segments)} ${t.request.method}: ${A.message} Reached after an earlier allow rule raised an error; production reports that earlier error: ${h}`),!1;if(A instanceof os)return d=!0,o.push(`match ${gn(g.segments)} ${t.request.method}: ${A.message}`),!1;if(A instanceof W){h??=A.message,o.push(`match ${gn(g.segments)} ${t.request.method}: ${A.message}`);continue}throw A}if(P)return!0;o.push(`match ${gn(g.segments)} ${t.request.method}: condition false`)}const S=g.segments[g.segments.length-1];if(g.children.length>0&&S!==void 0&&S.kind==="wildcard"){const k=g.segments.slice(0,-1),R=sd(k,b,w,e._version);if(R){const O=R.left,P=Lh(e._version);for(let A=O.length;A>=P;A--){const E=O.slice(0,A),j=O.slice(A),$={...R.params,[S.name]:new ze("/"+E.join("/"))};for(const C of g.children)if(p(C,j,$))return!0}return!1}}for(const k of g.children)if(p(k,_,v))return!0;return!1}const m=p(e._root,i,{});return!m&&o.length===0&&o.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:m,reasons:o,evaluatedExpressions:l.evaluated,...u!==void 0?{resourceLimit:{kind:"expressions",limit:Gw,message:u.message,...u.position===void 0?{}:{line:u.position.line,column:u.position.column}}}:{}}}function uC(e,t){const n=tv(e,t);return n instanceof Uh?new K(n.message):n}function et(e,t){const n=t.expressionBudget;if(!n)return bo(e,t);if(e.kind==="call")return n.call(e),bo(e,t);let r;try{r=bo(e,t)}catch(s){throw s instanceof os||n.node(e),s}return n.node(e),r}function bo(e,t){switch(e.kind){case"literal":return e.value;case"ident":{if(Object.hasOwn(t.locals,e.name))return t.locals[e.name];if(t.scopeKind!=="global"){if(e.name==="request")return bj(t.input,t.now);if(e.name==="resource")return t.input.resource===null?new K("Null value error."):gj(t.input.resource)}return Object.hasOwn(t.params,e.name)?t.params[e.name]:new K(`Identifier ${e.name} is undefined.`)}case"member":{const n=et(e.target,t);return J(n)?n:n==null?new K("Null value error."):uC(n,e.name)}case"index":{const n=ct([e.index,e.target],t);if(J(n))return n;const[r,s]=n;if(s==null)return new K("Null value error.");const i=ev(s,r);return i instanceof Uh?new K(i.message):i}case"call":return dC(e,t);case"methodcall":return eC(e,t);case"path":{t.expressionBudget?.node(e);for(const i of e.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(e);const n=ct(e.segments.flatMap(i=>i.kind==="literal"?[]:[i.expr]),t);if(J(n))return n;let r=0;const s=[];for(const i of e.segments){if(i.kind==="literal"){s.push(i.value);continue}const o=n[r++];if(typeof o!="string"&&typeof o!="number")return new K(`Path interpolation resolved to ${Pe(o)} (expected a string)`);s.push(String(o))}return new ze(`/${s.join("/")}`)}case"unary":{const n=et(e.arg,t);if(e.op==="!"){if(J(n))throw new W(n.message);if(typeof n!="boolean")throw new W(`Unary '!' expects a boolean, got ${Pe(n)}.`);return!n}return J(n)?n:e.op==="-"?n instanceof Te?new Te(-n.value):typeof n!="number"?new K(`Unary '-' applied to ${Pe(n)}.`):-n:void 0}case"ternary":{t.expressionBudget?.ternary(e);const n=et(e.cond,t);return J(n)?n:typeof n!="boolean"?new K(`Ternary condition expected bool, got ${Pe(n)}.`):n?et(e.then,t):(t.expressionBudget?.ternaryElse(e),et(e.else,t))}case"in":{const n=ct([e.collection,e.element],t);if(J(n))return n;const[r,s]=n,i=Xw(s,r);return i instanceof Zw?new K(i.message):i}case"is":{const n=et(e.value,t);return J(n)?n:sC(n,e.typeName)}case"list":return ct(e.elements,t);case"map":{const n=ct(e.entries.flatMap(s=>[s.key,s.value]),t);if(J(n))return n;const r=[];for(let s=0;s<n.length;s+=2){const i=n[s];if(typeof i!="string")return new K(`Map literal key is ${Pe(i)} (expected a string).`);r.push([i,n[s+1]])}return Qw(r)}case"slice":{const n=ct([e.target,e.start,e.end],t);if(J(n))return n;const[r,s,i]=n;if(typeof s!="number"||typeof i!="number"||!Number.isInteger(s)||!Number.isInteger(i))return new K("Slice bounds must be integers.");if(Array.isArray(r)||typeof r=="string"){const o=Yw(s,i,r.length);return o?new K(o):r.slice(s,i)}return new K(`Slice applied to ${Pe(r)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return id(e,!1,t);if(e.op==="||")return id(e,!0,t);const n=ct([e.left,e.right],t);if(J(n))return n;const[r,s]=n;if(e.op!=="=="&&e.op!=="!="&&(td(r)||td(s)))return iC(e.op,r,s);switch(e.op){case"==":return Pl(r,s);case"!=":return!Pl(r,s);case"<":case">":case"<=":case">=":return cC(e.op,r,s);case"+":case"-":case"*":case"/":case"%":return aC(e.op,r,s)}}}}function id(e,t,n){const{left:r,right:s}=e,i=od(r,n);if(i===t)return t;n.expressionBudget?.logicalRight(e);const o=od(s,n);return o===t?t:J(i)?i:o}function od(e,t){const n=Mr(e,t);return J(n)?n:typeof n!="boolean"?new K(`Expected a boolean '&&'/'||' operand, got ${Pe(n)}.`):n}function Mr(e,t){try{return et(e,t)}catch(n){if(hj(n))return new K(n.message);throw n}}function ct(e,t){const n=[];let r;for(const s of e){const i=Mr(s,t);J(i)&&(r??=i),n.push(i)}return r??n}function dC(e,t){const n=t.funcs.get(e.name);if(!n)return fC(e,t);if(n.unresolvedImport!==void 0)throw new is(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)return new K(`Incorrect number of arguments. Received: ${e.args.length}. Expected: ${e.name}(${n.params.join(", ")}).`);const r=e.args.map(l=>Mr(l,t)),s={};n.params.forEach((l,u)=>{s[l]=r[u]});const i=t.matchParams??t.params,o={};if(n.declCaptures)for(const l of n.declCaptures)Object.hasOwn(i,l)&&(o[l]=i[l]);const a={input:t.input,now:t.now,params:o,matchParams:i,scopeKind:n.scopeKind??"match",locals:s,funcs:n.declScope??new Map,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses,expressionBudget:t.expressionBudget};for(const l of n.lets)s[l.name]=Mr(l.value,a),a.expressionBudget?.letBinding(l);return et(n.body,a)}function fC(e,t){if(e.name==="path"&&e.args.length===1){const i=et(e.args[0],t);return J(i)?i:typeof i=="string"?i.includes("//")?new K("Invalid argument error in path(): empty path segment."):new ze(i):new K(`path() expects a string, got ${Pe(i)}.`)}const n=nv(e.name);if(!n)return new K(`Function not found error: Name: [${e.name}].`);const r=ct(e.args,t);if(J(r))return r;const s=rv(n,r);return s instanceof sv?new K(s.message):s}function ls(e,t,n,r){const s=n?.kind==="sandbox"?Wt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){vs(n,t,"not-applicable",void 0,"admin",!1,s);return}const i=hC(e,n);if(i.kind!=="rules"){const u=pC(i);throw vs(n,t,"deny",[u],"user",!1,s),zu(t.request.method,t.request.path,` — ${u}`)}const o=n?mC(t,n):t,a=n?De(n.sandbox).date():void 0,l=fm(i.rules,o,a,yC(n,e.crossServiceIam));if(!l.allowed){vs(n,t,"deny",l.reasons,"user",!0,s);const u=l.reasons.length>0?` — ${l.reasons.join("; ")}`:"";throw zu(t.request.method,t.request.path,u)}vs(n,t,"allow",l.reasons,"user",!0,s)}function hC(e,t){return t!==void 0?ej(e,t):e.rules?{kind:"rules",rules:e.rules}:{kind:"none"}}function pC(e){if(e.kind==="none")return"No Storage rules configured; default deny.";if(e.kind==="second-default")return`Storage bucket "${e.bucket}" is a second default bucket in this sandbox, which already serves "${e.defaultBucket}" as its default bucket, so pyric denies every client operation on it rather than share that bucket's objects. Give each app the same storageBucket, or open the other bucket with getStorage(app, "gs://${e.bucket}").`;const{bucket:t}=e;return`Storage bucket "${t}" has no rules deployed in firebase.json, so pyric denies every client operation on it. Add {"bucket": "${t}", "rules": "<file>"} to the storage array.`}function mC(e,t){return KE(e,t.bucket,Bc(t.bucket,t.bucketName))}function vs(e,t,n,r,s,i,o){if(e)try{dt(e.sandbox,Ch({at:De(e.sandbox).now(),service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,detail:{bucket:e.bucket,bucketName:Bc(e.bucket,e.bucketName)},rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:i?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:i?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...o,service:"storage"})}catch{}}function yC(e,t){if(e)return gC(e.sandbox,t)}function gC(e,t){if(t==="denied")return bC();const n=e.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function bC(){const e=t=>{throw new W(`firestore.${t}() failed: cross-service Firestore access is not authorized: the Storage service agent lacks roles/firebaserules.firestoreServiceAgent (crossServiceIam: 'denied')`)};return{get:()=>e("get"),exists:()=>e("exists")}}function Lr(e){return e.admin===!0?"admin":"client"}const wC="identity";function hm(e,t){return e??`inline; filename*=utf-8''${xC(t.split("/").pop()??"")}`}function pm(e){return e??wC}const vC=/[A-Za-z0-9!#$&+\-.^_`|~]/;function xC(e){let t="";for(const n of e){if(vC.test(n)){t+=n;continue}for(const r of new TextEncoder().encode(n))t+=`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}function mm(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Di(e){return e?mm({size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:ym(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:ad(e.generation),metageneration:ad(e.metageneration)}):null}function ym(e,t){if(e===void 0)return;const n=e.startsWith("/")?e.slice(1):e;if(t!==void 0){const s=`b/${t}/o/`;if(n.startsWith(s))return n.slice(s.length)}const r=/^b\/[^/]+\/o\//.exec(n);return r?n.slice(r[0].length):n}function ad(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function _C(e,t){const n=ym(e.fullPath,e.bucket),r={name:n,bucket:e.bucket,size:e.size,contentType:e.contentType,contentDisposition:hm(e.contentDisposition,n??""),contentEncoding:pm(e.contentEncoding),contentLanguage:e.contentLanguage??null,cacheControl:e.cacheControl??null,metadata:e.customMetadata??null};return r.generation=null,r.metageneration=null,r.etag=null,mm(r)}function Hc(e,t){return t==="admin"?{...e}:{...e,contentEncoding:pm(e.contentEncoding)}}async function SC(e){kC(e,"getMetadata");const t=Me(e.storage),n=Wt(t),r=await zt(e.storage),s=await r.backend.getMetadata(e.fullPath);if(ls(r,{request:{auth:qt(t),method:"get",path:e.fullPath},resource:Di(s)},t,n),!s)throw om(e.fullPath);return Hc(s,Lr(t))}function kC(e,t){if(e.fullPath==="")throw Pi(t)}const EC="application/octet-stream";async function jC(e,t,n,r){return CC(e,t,n,{provenance:r})}async function CC(e,t,n,r={}){const{result:s}=await gm(e,t,n,r);return s}async function gm(e,t,n,{provenance:r,downloadTokens:s}={}){NC(e,"uploadBytes");const i=Me(e.storage),o=s!==void 0;if(o&&Lr(i)!=="admin")throw new jt("unauthorized","Only the admin plane sets download tokens on upload.");const a=Wt(i,r),l=RC(t,n?.contentType),u=De(i.sandbox).date(),d=bm({ref:e,blob:l,settable:n,now:u});o&&(d.downloadTokens=s);const h=await zt(e.storage),f=await h.backend.getMetadata(e.fullPath);ls(h,{request:{auth:qt(i),method:"create",path:e.fullPath,resource:_C(d)},resource:Di(f)},i,a);const p=await h.backend.put(e.fullPath,l,d,AE(u.getTime()));try{dt(i.sandbox,Ln({at:De(i.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:qt(i),before:p?.metadata,after:d,detail:{bucket:e.bucket,size:d.size,contentType:d.contentType,overwrite:p!==void 0}}),a)}catch{}return{result:{ref:e,metadata:Hc(d,Lr(i))},replaced:p}}function bm(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=String(Yp((e.now??new Date).getTime())),o=t.name,a=Lr(Me(t.storage))==="client";return{fullPath:t.fullPath,name:o,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||EC,cacheControl:r?.cacheControl,contentDisposition:a?hm(r?.contentDisposition,t.fullPath):r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function RC(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function NC(e,t){if(e.fullPath==="")throw Pi(t)}async function IC(e,t){return Kc(e,"getBlob"),$C(e,t)}async function AC(e,t){Kc(e,"deleteObject");const n=Me(e.storage),r=Wt(n,t),s=await zt(e.storage),i=await s.backend.getMetadata(e.fullPath);ls(s,{request:{auth:qt(n),method:"delete",path:e.fullPath},resource:Di(i)},n,r),await s.backend.delete(e.fullPath),wm(e,i,r)}async function OC(e,t,n){Kc(e,"deleteObject");const r=Me(e.storage),s=await zt(e.storage),i=await s.backend.getMetadata(e.fullPath),o=await s.backend.deleteIfGeneration(e.fullPath,t);return o&&wm(e,i,Wt(r,n)),o}function wm(e,t,n){const r=Me(e.storage);try{dt(r.sandbox,Ln({at:De(r.sandbox).now(),service:"storage",op:"object_delete",path:e.fullPath,auth:qt(r),before:t??void 0,detail:{bucket:e.bucket}}),n)}catch{}}async function $C(e,t){const n=Me(e.storage),r=Wt(n),s=await zt(e.storage),i=await s.backend.getMetadata(e.fullPath);ls(s,{request:{auth:qt(n),method:"get",path:e.fullPath},resource:Di(i)},n,r);const o=await s.backend.getBlob(e.fullPath);if(!o)throw om(e.fullPath);return typeof t=="number"&&o.size>t?o.slice(0,t):o}function Kc(e,t){if(e.fullPath==="")throw Pi(t)}async function PC(e,t,n,r){const s=(await zt(e.storage)).backend,i=await s.getMetadata(e.fullPath),o=await s.replaceIfGeneration(e.fullPath,t,n);return o&&DC(e,i,n.metadata,r),o}function DC(e,t,n,r){const s=Me(e.storage);try{dt(s.sandbox,Ln({at:De(s.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:qt(s),before:t,after:n,detail:{bucket:e.bucket,size:n.size,contentType:n.contentType,overwrite:!0}}),Wt(s,r))}catch{}}async function TC(e,t,n){const r=t.prior;return r!==void 0?PC(e,t.generation,r,n).then(s=>({deleted:!1,restored:s}),s=>({deleted:!1,restored:!1,error:ga(e.fullPath,s,"restore")})):OC(e,t.generation,n).then(s=>({deleted:s,restored:!1}),s=>({deleted:!1,restored:!1,error:ga(e.fullPath,s,"remove")}))}async function MC(e,t,n){return(await TC(e,t,n)).error}const LC={remove:"removing it failed",restore:"restoring the object it replaced failed"};function UC(e){const t=e?.code;if(typeof t=="string")return t}function ga(e,t,n="remove"){const r=UC(t)??"storage/unknown",s=t instanceof Error?t.message:String(t),i=LC[n],o=`${r}: The upload to '${e}' was canceled after it was stored, and ${i}: ${s}`,a=new Error(o,{cause:t});return a.code=r,a}function BC(e,t){if(e instanceof Blob)return t!==void 0&&t!==e.type?new Blob([e],{type:t}):e;let r="";return t!==void 0&&(r=t),new Blob([e],{type:r})}class FC{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_sentCommit;_heldOutcome;_error;_ref;_blob;_metadata;_provenance;constructor(t,n,r,s){this._ref=t,this._metadata=r,this._provenance=s;let i;r!==void 0&&(i=r.contentType),this._blob=BC(n,i);const a=bm({ref:t,blob:this._blob,settable:r}),l=Hc(a,Lr(Me(t.storage)));this._promise=new Promise((u,d)=>{this._resolve=u,this._reject=d}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:this._blob.size,state:"running",metadata:l,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{if(!(this._snapshot.state==="running"))return;this._releaseHeldOutcome()||this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._rollBackCanceled().then(r=>this._settleCanceled(r)),!0):!1}on(t,n,r,s){let i,o,a,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Lt(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Lt(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Lt(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ai(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const a=i.next;try{Lt(this),a(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const a=i.complete;try{ai(this),a()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=this._storeUpload();this._sentCommit=r;const s=await r;this._committing=!1,this._settleCommit(s)}async _storeUpload(){try{if(await zt(this._ref.storage),this._snapshot.state!=="running")return;const{result:n,replaced:r}=await gm(this._ref,this._blob,this._metadata,{provenance:this._provenance});return{stored:{result:n,prior:r}}}catch(t){return{error:t}}}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){this._report(t);return}n==="paused"&&(this._heldOutcome=t)}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,this._report(t),!0)}_report(t){if(t===void 0){queueMicrotask(()=>this._runStep());return}if("stored"in t){this._updateSnapshot("success",this._snapshot.totalBytes,t.stored.result.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);return}this._fail(t.error)}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}_fail(t){let n;t instanceof Error?n=t:n=new Error(String(t)),this._error=n,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=t??await this._sentCommit;if(!(n!==void 0&&"stored"in n))return Hu();const s={generation:n.stored.result.metadata.generation,prior:n.stored.prior};return await MC(this._ref,s,this._provenance)??Hu()}}function qC(e,t,n,r){if(e.fullPath==="")throw Pi("uploadBytesResumable");return new FC(e,t,n,r)}async function VC(e){const t=e.storage,n=Me(t),r=Wt(n),s=await zt(t);ls(s,{request:{auth:qt(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,o=await s.backend.listByPrefix(i),a=[],l=new Set,u=[];for(const d of o){if(!d.fullPath.startsWith(i))continue;const h=d.fullPath.slice(i.length);if(h==="")continue;const f=h.indexOf("/");if(f===-1)a.push(Pr(t,d.fullPath));else{const p=h.slice(0,f),m=`${i}${p}`;l.has(m)||(l.add(m),u.push(Pr(t,m)))}}return u.sort((d,h)=>d.fullPath<h.fullPath?-1:d.fullPath>h.fullPath?1:0),{items:a,prefixes:u}}const WC=qn("uploadBytes",jC),zC=qn("uploadBytesResumable",qC),HC=qn("getBlob",IC),vm=qn("deleteObject",AC),KC=qn("getMetadata",SC),Gc=qn("listAll",VC),GC="/__pyric/storage/v0/b/";function JC(e,t,n){const r=new URLSearchParams({alt:"media"});return`${GC}${encodeURIComponent(e)}/o/${encodeURIComponent(t)}?${r}`}function YC(e){let t="",n=!1,r=!1,s=!1,i=0;for(;i<e.length;){const o=e[i],a=i+1<e.length?e[i+1]:"";if(r){(o===`
128
+ `||o==="\r")&&(r=!1,t+=o),i++;continue}if(s){o==="*"&&a==="/"?(s=!1,i+=2):((o===`
129
+ `||o==="\r")&&(t+=o),i++);continue}if(n){if(o==="\\"){t+=o,a!==""&&(t+=a,i++),i++;continue}o==='"'&&(n=!1),t+=o,i++;continue}if(o==='"'){n=!0,t+=o,i++;continue}if(o==="/"&&a==="/"){r=!0,i+=2;continue}if(o==="/"&&a==="*"){s=!0,i+=2;continue}t+=o,i++}return t}const QC={"\n":"\\n","\r":"\\r"," ":"\\t"};function XC(e){const t=QC[e];return t!==void 0?t:`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}function xm(e){return e===" "||e===" "||e===`
130
+ `||e==="\r"}function ZC(e,t){let n=t+1;for(;n<e.length&&xm(e[n]);)n++;const r=e[n];return r==="}"||r==="]"}function eR(e){const t=YC(e);let n="",r=!1,s="",i=0;for(;i<t.length;){const o=t[i];if(r){if(o==="\\"){n+=t.slice(i,i+2),i+=2;continue}o==='"'&&(r=!1);const f=o.charCodeAt(0)<32;n+=f?XC(o):o,i++;continue}o==='"'&&(r=!0);const u=o===","&&(s!==""&&s!=="{"&&s!=="["&&s!==",")&&ZC(t,i);u||(n+=o),!u&&!xm(o)&&(s=o),i++}return n}function ba(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(!ba(e[a],t[a]))return!1;return!0}const s=e,i=t,o=Object.keys(s);if(o.length!==Object.keys(i).length)return!1;for(const a of o)if(!Object.prototype.hasOwnProperty.call(i,a)||!ba(s[a],i[a]))return!1;return!0}const kn=Symbol("pyric/firestore/followsCurrentUser"),wr=Symbol("pyric/firestore/authSessionScope");function fr(e){const t=e.keys().next().value;t!==void 0&&e.delete(t)}const Oe=Object.freeze({readThreshold:5,readWindowMs:1e3,duplicateListenerThreshold:3,churnAttachThreshold:4,churnDetachThreshold:3,listenerWindowMs:2e3,maxEventsPerFingerprint:32,criticalReadThreshold:20,criticalDuplicateListenerThreshold:10,criticalChurnThreshold:12});function tR(e,t){for(const n of e.keys())t.delete(n)}function nR(e,t){const n=e.keys().next().value;return n===void 0?!1:(e.delete(n),t.delete(n),!0)}const cd=1800;function rR(e){const t=new Map,n=new Map;let r=1;const s=(i,o)=>{const a=i.get(o);if(a!==void 0)return a;i.size>=e&&fr(i);const l=r++;return i.set(o,l),l};return{incidentFingerprint:i=>`activity:#${s(n,i)}`,readTarget:(i,o)=>hr(o===i?i:`${i}|query:#${s(t,o)}`),listenerTarget:i=>{try{const o=JSON.parse(i);if(o.kind==="query"){const a=typeof o.collection=="string"?o.collection:typeof o.path=="string"?o.path:"<unknown>";return hr(JSON.stringify({collection:a,kind:"query",query:`#${s(t,i)}`}))}if(o.kind==="doc"&&typeof o.path=="string")return hr(JSON.stringify({kind:"doc",path:o.path}))}catch{}return JSON.stringify({kind:"unknown",target:`#${s(t,i)}`})},clear:()=>{t.clear(),n.clear()}}}function hr(e){if(e.length<=cd)return e;const t=`…#${sR(e)}`;return e.slice(0,cd-t.length)+t}function sR(e){let t=2166136261,n=2654435769;for(let r=0;r<e.length;r+=1){const s=e.charCodeAt(r);t=Math.imul(t^s,16777619),n=Math.imul(n^s,2246822507)}return(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}const xs=256,iR=64,oR=8192;function aR(e,t){const n=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Set,l=rR(xs);let u=0,d=!1;const h=_=>{try{t(_)}catch{}},f=(_,S)=>{!i.has(_)&&i.size>=iR&&fr(i),i.set(_,S)},p=(_,S)=>{const k=o.get(_);return k!==void 0?(o.delete(_),k==="critical"||k===S?(o.set(_,k),!1):(o.set(_,S),!0)):(o.size>=xs&&fr(o),o.set(_,S),!0)},m=()=>{n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),u+=1},g=(_,S)=>{if(a.has(_.id))return;if(a.size>=oR&&fr(a),a.add(_.id),_.kind==="session_boundary"){m();return}const k=lR(_);if(!k){const $=cR(_,s);$&&b(_,$,S);return}const R=`segment:${u}|read:${k.method}:${k.targetFingerprint}|actor:${k.actorAuthFingerprint}`;let O=n.get(R);O||(n.size>=xs&&fr(n),O={events:[]},n.set(R,O)),O.events.push({id:_.id,at:_.at});const P=_.at-Oe.readWindowMs;for(;O.events.length>0&&O.events[0].at<P;)O.events.shift();if(O.events.length>Oe.maxEventsPerFingerprint&&O.events.splice(0,O.events.length-Oe.maxEventsPerFingerprint),O.events.length<Oe.readThreshold)return;const A=O.events[0],E=O.events[O.events.length-1],j=Object.freeze({fingerprint:l.incidentFingerprint(R),pattern:"repeated-read",confidence:"high",severity:ld("repeated-read",O.events.length),service:"firestore",method:k.method,targetFingerprint:l.readTarget(k.path,k.targetFingerprint),actor:k.actor,authLens:ui(k.authLens),authUid:k.authUid,count:O.events.length,windowMs:E.at-A.at,usage:Object.freeze({unit:"document-reads",lowerBound:O.events.length,limitations:Object.freeze(["Observed sandbox reads are a lower bound; production cache and billing behavior are not measured."])}),evidenceEventIds:Object.freeze(O.events.slice(-8).map($=>$.id)),sourceAttribution:ud(k.actor)});f(R,j),!S&&p(R,j.severity)&&h(j)},b=(_,S,k)=>{const R=Cr(S.target),O=l.listenerTarget(R),P=`segment:${u}|listener:${R}|actor:${S.actorAuthFingerprint}`;let A=r.get(P);if(!A){if(r.size>=xs){const N=r.keys().next().value;N!==void 0&&(tR(r.get(N).active,s),r.delete(N))}A={active:new Map,lifecycle:[],saturated:!1},r.set(P,A)}if(S.phase==="attach"){if(A.active.has(S.physicalListenerId))return;A.active.size>=Oe.maxEventsPerFingerprint&&nR(A.active,s)&&(A.saturated=!0),A.active.set(S.physicalListenerId,{id:_.id,at:_.at}),s.set(S.physicalListenerId,{listenerId:S.listenerId,target:S.target,actor:S.actor,authLens:S.authLens,authUid:S.authUid,actorAuthFingerprint:S.actorAuthFingerprint})}else A.active.delete(S.physicalListenerId),s.delete(S.physicalListenerId);if(S.phase==="errored"||S.reauthorization)return;A.lifecycle.push({id:_.id,at:_.at,phase:S.phase});const E=_.at-Oe.listenerWindowMs;for(;A.lifecycle.length>0&&A.lifecycle[0].at<E;)A.lifecycle.shift();A.lifecycle.length>Oe.maxEventsPerFingerprint&&(A.lifecycle.splice(0,A.lifecycle.length-Oe.maxEventsPerFingerprint),A.saturated=!0);const j=A.lifecycle.filter(N=>N.phase==="attach").length,$=A.lifecycle.length-j,C=Object.freeze({attaches:j,detaches:$,active:A.active.size,...A.saturated?{isLowerBound:!0}:{}});if(A.active.size>=Oe.duplicateListenerThreshold){const N=[...A.active.values()],I=N[0],M=`${P}|duplicate`;w(M,"duplicate-listener",N.length,_.at-I.at,N.map(T=>T.id),k,S,O,C)}if(j>=Oe.churnAttachThreshold&&$>=Oe.churnDetachThreshold){const N=A.lifecycle[0],I=`${P}|churn`;w(I,"listener-churn",j,_.at-N.at,A.lifecycle.map(M=>M.id),k,S,O,C)}},w=(_,S,k,R,O,P,A,E,j)=>{const $=Object.freeze({fingerprint:l.incidentFingerprint(_),pattern:S,confidence:S==="duplicate-listener"&&k<Oe.criticalDuplicateListenerThreshold?"medium":"high",severity:ld(S,k),service:"firestore",method:"listen",targetFingerprint:hr(E),actor:A.actor,authLens:ui(A.authLens),authUid:A.authUid,count:k,windowMs:R,listenerBalance:j,usage:Object.freeze({unit:"listener-attaches",lowerBound:k,limitations:Object.freeze(["Listener lifecycle events count attachments; document deliveries and production billing are not measured.",...j.isLowerBound?["Listener retention saturated; reported counts are observed lower bounds."]:[]])}),evidenceEventIds:Object.freeze(O.slice(-8)),sourceAttribution:ud(A.actor)});f(_,$),!P&&p(_,$.severity)&&h($)},x=e.history();for(const _ of x)g(_,!0);x.length>0&&m();const v=e.subscribe(_=>{d||g(_,!1)});return{report:()=>Object.freeze({incidents:Object.freeze([...i.values()])}),dispose:()=>{d||(d=!0,v(),n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),l.clear())}}}function ld(e,t){const n=e==="repeated-read"?Oe.criticalReadThreshold:e==="duplicate-listener"?Oe.criticalDuplicateListenerThreshold:Oe.criticalChurnThreshold;return t>=n?"critical":"warning"}function cR(e,t){const n=e.kind==="listener_attach"||e.kind==="listener_detach"||e.kind==="listener_errored",r=e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored");if(!n&&!r||(e.service??"firestore")!=="firestore"||e.planId)return null;let s;if(e.kind==="listener_attach")s="attach";else if(e.kind==="listener_detach")s="detach";else if(e.kind==="listener_errored")s="errored";else if(e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored"))s=e.phase;else return null;const i=pc(e),o=s!=="attach"?t.get(e.listenerId):void 0;if(!(o!==void 0)&&(i.source.kind!=="app"||i.authLens.mode==="admin"))return null;const l=e.activity?.listenerId??o?.listenerId??e.listenerId,u=o??{listenerId:l,target:e.target,actor:i.source,authLens:i.authLens,authUid:e.auth?.uid??null,actorAuthFingerprint:Cr({actor:i.source,authLens:ui(i.authLens),uid:e.auth?.uid??null})};return{phase:s,physicalListenerId:e.listenerId,reauthorization:e.activity?.listenerLifecycle==="reauthorize",...u}}function ud(e){return e.kind==="app"&&e.journeyId!==void 0?`app ${e.journeyId}`:"app"}function ui(e){return e.mode==="as"?{mode:"as",uid:e.uid}:{mode:e.mode}}function lR(e){if(e.kind!=="request"&&e.kind!=="operation"||(e.kind==="request"?e.service??"firestore":e.service)!=="firestore"||e.method!=="get"&&e.method!=="list"||e.origin!=="user"||e.result!=="allow"||e.groupId||e.groupKind||e.activity?.groupKind||e.planId||e.detail?.admin===!0)return null;const n=pc(e);if(n.source.kind!=="app"||n.authLens.mode==="admin")return null;const r=e.path??"<unknown>",s=e.kind==="request"?e.detail?.activityQuery??e.detail?.query:e.request?.query,i=s===void 0?void 0:Cr(s);return{method:e.method,path:r,targetFingerprint:i===void 0?r:`${r}|query:${i}`,actorAuthFingerprint:Cr({actor:n.source,authLens:ui(n.authLens),uid:e.auth?.uid??null}),actor:n.source,authLens:n.authLens,authUid:e.auth?.uid??null}}const _m=new WeakMap;function uR(e){return _m.get(e)?.raw??e}const dR=new WeakMap,dd=new WeakMap;function di(e,t,n,r,s){_m.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function fd(e){return typeof e.exists=="function"?e.exists():e.exists===!0}function fR(e,t){const n=Qo(e),r=Qo(t);return n.isStructurallyEqual?.(r)??n===r}function hR(e,t,n,r){const s=e,i=(dd.get(s)??[]).filter(a=>a.query.deref()!==void 0),o=i.find(a=>{const l=a.query.deref();return l!==void 0&&fR(l,t)});if(o!==void 0){const a=pR(o.docs,n)&&o.metadata.fromCache===r.fromCache&&o.metadata.hasPendingWrites===r.hasPendingWrites;return o.docs=n,o.metadata=r,a?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),dd.set(s,i),"initial"}function pR(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&Dv(n.data,s.data)})}function wa(e,t,n,r,s){const i=t,o=d=>({path:d.ref?.path??"",data:gc(d.data?.(),n)}),a=Object.freeze((i.docs??[]).map(o)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...o(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),u=Object.freeze({fromCache:i.metadata?.fromCache===!0,hasPendingWrites:i.metadata?.hasPendingWrites===!0});dR.set(e,{target:n,query:r,converter:Zr(r)??null,source:s,...s==="read"?{readPhase:hR(n,r,a,u)}:{},metadata:u,docs:a,changes:l})}function fi(e,t){const n=e;xa(n);const r=n.data.bind(e),s=t!==void 0;let i;if(s&&(i={create:o=>tt({[Ks]:t},o)}),Object.defineProperty(n,"data",{value:()=>Hh(r(),i),configurable:!0,writable:!0}),s){const o=n.ref?.path;o!==void 0&&o.length>0&&Object.defineProperty(n,"metadata",{value:St(t).snapshotMetadata(o),configurable:!0})}return e}function Sm(e,t,n,r){const s=tt({[Ks]:n},e.ref.path),i=s.withConverter(t),o={create:l=>tt({[Ks]:n},l)},a={id:e.id,ref:i,exists:()=>fd(e),metadata:St(n).snapshotMetadata(e.ref.path),data:()=>{if(!fd(e))return;const u=Hh(e.data(),o),d={id:e.id,ref:s,exists:()=>!0,metadata:St(n).snapshotMetadata(e.ref.path),data:()=>u};return t.fromFirestore(d)}};return nn(a,n),nn(e.ref,n),va(e.ref,n),di(a,e,n,t,r),a}function hd(e,t,n,r){const s=e,i=s.ref?.path??"",o=s.data.bind(e),a=tt({[Ks]:n},i),l=a.withConverter(t);Object.defineProperty(s,"ref",{value:l,configurable:!0,writable:!0}),Object.defineProperty(s,"data",{value:()=>{const d=o();if(d===void 0)return;const f={id:s.id,ref:a,exists:()=>!0,metadata:St(n).snapshotMetadata(i),data:()=>d};return t.fromFirestore(f)},configurable:!0,writable:!0});const u={ref:{path:i},exists:s.exists,data:o};di(e,u,n,t,r)}function Ti(e,t){if(!e||typeof e!="object")return e;nn(e,t);const n=e;if(n.ref&&(nn(n.ref,t),va(n.ref,t)),xa(n),Array.isArray(n.docs))for(const r of n.docs)r&&(nn(r,t),di(r,r,t,null,"query-child")),r?.ref&&(nn(r.ref,t),va(r.ref,t)),r&&xa(r);else n.ref&&di(e,e,t,null,"document");return e}function va(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Tl.get(e),s=r??yc(t).doc(n);r===void 0&&Tl.set(e,s),Bh(e,n,t,s),t.kind==="sandbox-live"&&Kh.set(s,i=>i.doc(n))}catch{}}function xa(e){const t=e.exists;if(typeof t=="function")return;const n=t===!0;try{Object.defineProperty(e,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}function km(e){return mR(e,"getDoc")}async function mR(e,t){return yR(e,bc(Un(e),e,t,"operation"))}async function yR(e,t){const n=Un(e),r=St(n);r.markStarted();try{const s=Zr(e),i=await Gh(()=>Mv(n,e).get());return r.cachePath(e.path),s?On(t,Sm(i,s,n,"document")):(Ti(i,n),On(t,fi(i,n)))}catch(s){throw t.fail(),s}}function hi(e){return gR(e,"getDocs")}async function gR(e,t){return bR(e,bc(Un(e),e,t,"operation"))}async function bR(e,t){const n=Un(e),r=St(n);r.markStarted();try{const s=Zr(e),i=await Gh(()=>Tv(n,e).get());if(r.cacheQuery(e),s){const a=s,l=i.docs.map(d=>Sm(d,a,n,"query-child")),u=nn({size:l.length,empty:l.length===0,docs:l,forEach:Fh(l),metadata:r.querySnapshotMetadata()},n);for(const d of l)r.cachePath(d.ref.path);return wa(u,i,n,e,"read"),On(t,u)}Ti(i,n);const o=i.docs;for(const a of o)r.cachePath(a.ref.path),fi(a,n);return Object.defineProperty(i,"metadata",{value:r.querySnapshotMetadata(),configurable:!0}),wa(i,i,n,e,"read"),On(t,i)}catch(s){throw t.fail(),s}}function wR(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.path=="string"&&t.path.length>0?t.path:typeof t.collectionPath=="string"&&t.collectionPath.length>0?t.collectionPath:null}function pd(e){if(e!==null&&typeof e=="object"){const t=e.snapshotConstraints;if(typeof t=="function")return t.call(e)}}function vR(e){if(e!==null&&typeof e=="object"){const t=e.snapshotScope;if(typeof t=="function")return t.call(e)}}function md(e){if(e===null||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&t.path.length>0&&t.parent!==void 0&&t.parent!==null}function Em(e,t,n,r,s){let i={},o,a;if(typeof t=="object"&&t!==null&&typeof t.next!="function"&&typeof t.error!="function"&&typeof t.complete!="function"){if(i=t,typeof n=="function")o=n,a=r;else if(typeof n=="object"&&n!==null){const v=n;o=v.next,a=v.error}}else if(typeof t=="function")o=t,a=n;else if(typeof t=="object"&&t!==null){const v=t;o=v.next,a=v.error}if(!o&&!a)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=Bv(e);if(u){if(i[kn]===!0)throw new Ah("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,o,a)}const d=xR(e),h=Xr(d.sandbox);let f;const p=md(e)?void 0:vR(e);if(md(e))f={kind:"doc",path:e.path};else if(p?.kind==="collection-group")f={kind:"query",collection:p.collectionId,collectionGroup:!0,constraints:pd(e)};else{const v=wR(e);if(v===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const _=pd(e);f={kind:"query",collection:v,constraints:_}}const m=i[kn]===!0,g=i[wr],b=e[Fv]===!0;if(kn in i){const{[kn]:v,..._}=i;i=_}if(wr in i){const{[wr]:v,..._}=i;i=_}const w=()=>h.addSnapshotListener(f,o??(()=>{}),i,d.auth,a?v=>a(SR(v,d)):void 0,m,b,g);return typeof d.sandbox.runWithProvenance=="function"?d.sandbox.runWithProvenance(Jo(d.operationContext),w):w()}function xR(e){if(e===null||typeof e!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const t=e[qv];if(!t)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return t}Lv(Em);Uv(Em);function _R(e){return typeof e=="object"&&e!==null&&"code"in e&&ov.some(t=>t===e.code)&&"message"in e&&typeof e.message=="string"}function SR(e,t){if(!_R(e))return e;const n=Vv(new iv(e),{...t,auth:e.request?e.request.auth:t.auth});if(n instanceof Error)for(const r of["request","resource","query","rule","queryProof"])e[r]!==void 0&&Object.assign(n,{[r]:e[r]});return n}function jm(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function pi(e,...t){const n=Un(e),r=Zr(e),s=Wv(e);let i,o;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw Xo(u)}const a=u=>{let d=s(u);for(const h of i)d=h.applySandbox(d);return d};try{o=a(yc(n))}catch(u){throw Xo(u)}const l=zv(Hv(o,n,u=>a(u)));return r?Kv(l,r):l}function kR(e,t,n){return Cm(jm(e),t,n,!1)}function Cm(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const o=gc(n,i,t==="in"||t==="not-in");return Cm(e,t,o.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function yd(e,t){const n=jm(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function mi(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function ER(e){if(e.length!==1)return!1;const t=e[0];return t!==null&&typeof t=="object"&&"data"in t&&typeof t.data=="function"}function jR(...e){return ER(e)?Rm(e[0],!1,!0):Nm(e,!1,!0)}function Rm(e,t,n,r=!1){return{type:n?"startAt":"endAt",applySandbox:s=>n?s.startCursorFromSnapshot(e,t):s.endCursorFromSnapshot(e,t),prepareSandbox:r?void 0:()=>{const s=uR(e),i=s.data(),o=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Rm(o,t,n,!0)}}}function Nm(e,t,n,r=!1){return{type:n?"startAt":"endAt",applySandbox:s=>n?s.startCursor([...e],t):s.endCursor([...e],t),prepareSandbox:r?void 0:s=>Nm(e.map(i=>gc(i,s).executionValue),t,n,!0)}}function CR(e,t,n,r){const s=Un(e);St(s).markStarted();const i=NR(s,e),o=typeof t=="object"&&t!==null&&!Jc(t)?t:void 0,a=bc(s,e,"onSnapshot","subscription",o),l=IR(t,n,r,s,e,a),u=AR(l,s);let d;try{d=Yr.registering(a,()=>u.length===3?i.onSnapshot(u[0],u[1],u[2]):u.length===2?i.onSnapshot(u[0],u[1]):i.onSnapshot(u[0]))}catch(g){throw a.fail(),g}if(!s.own)return()=>{a.close(),d()};let h=!1;const f=()=>{h||(h=!0,a.close(),d())},p=()=>{h||(a.fail(),f(),RR(u)?.(new G("aborted","The operation was aborted.")))},m=s.own(p);return()=>{m(),f()}}function RR(e){const t=e.at(-1);if(typeof t=="function"&&e.length>=3)return t;if(t&&typeof t=="object"){const n=t.error;if(typeof n=="function")return n}}function NR(e,t){const n=Qo(t);if(e.kind==="sandbox")return n;const r=Kh.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(yc(e))}function Jc(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.next=="function"||typeof t.error=="function"||typeof t.complete=="function"}function IR(e,t,n,r,s,i){if(typeof e=="object"&&e!==null&&!Jc(e)){const a=t;return typeof a=="function"?[e,gd(a,r,s,i),Sa(n??_a,i)]:a&&typeof a=="object"?[e,bd(a,r,s,i)]:[e]}return typeof e=="function"?[gd(e,r,s,i),Sa(t??_a,i)]:e&&typeof e=="object"?[bd(e,r,s,i)]:[e]}function AR(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Jc(n)?[{...n,[kn]:!0,...t.authScope?{[wr]:t.authScope}:{}},...e.slice(1)]:[{[kn]:!0,...t.authScope?{[wr]:t.authScope}:{}},...e]}function Im(e,t,n){if(!e||typeof e!="object")return e;const r=e,s=Zr(n)??null,i=s!==null;if(typeof r.data=="function"&&(fi(e,t),i&&hd(e,s,t,"document")),Array.isArray(r.docs)){for(const o of r.docs)fi(o,t),i&&hd(o,s,t,"query-child");wa(e,e,t,n,"listener")}return e}function _a(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function gd(e,t,n,r){return s=>{const i=Im(Ti(s,t),t,n);r.delivered(i),e(i),St(t).notifySnapshotDelivered()}}function bd(e,t,n,r){return{...e,next:e.next?s=>{const i=Im(Ti(s,t),t,n);r.delivered(i),e.next(i),St(t).notifySnapshotDelivered()}:void 0,error:Sa(e.error??_a,r)}}function Sa(e,t){return n=>{t.fail(),e(Xo(n))}}const It={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string",description:"Tenant id, visible to rules as request.auth.token.firebase.tenant."},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},OR={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Gv]},value:{}},required:["field","op","value"]};function $R(e){const{resolveDb:t}=e;return[{name:"firestore_get_document",description:"Get a Firestore document by path. Admin by default; pass `as:{uid}` to read with rules enforced as that user.",parameters:{type:"object",properties:{path:{type:"string",description:'e.g. "users/alice"'},as:It},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=tt(s,r.path),o=await km(i),a=typeof o.exists=="function"?o.exists():o.exists;return{ok:!0,summary:a?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:a,data:a?o.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:It},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=pr(s,r.collection),o=[];r.orderBy&&o.push(yd(r.orderBy)),r.limit&&o.push(mi(r.limit));const a=await hi(pi(i,...o));return{ok:!0,summary:`${a.size} docs in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:It},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Gs(tt(s,r.path),r.data),{ok:!0,summary:`Created ${r.path}`}}},{name:"firestore_add_document",description:"Add a document with an auto-generated id under a collection (mirrors the Web SDK addDoc). Admin by default — the right tool for seeding; pass `as:{uid}` to write as a user with rules enforced. Returns the minted path.",parameters:{type:"object",properties:{collection:{type:"string",description:'Collection to add the doc under, e.g. "users" or "users/u1/posts".'},data:{type:"object"},as:It},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await Jh(pr(s,r.collection),r.data);return{ok:!0,summary:`Created ${i.path}`,data:{path:i.path,id:i.id}}}},{name:"firestore_update_document",description:"Merge fields into an existing Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:It},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Ml(tt(s,r.path),r.data),{ok:!0,summary:`Updated ${r.path}`}}},{name:"firestore_delete_document",description:"Delete a Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},as:It},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await Zo(tt(s,r.path)),{ok:!0,summary:`Deleted ${r.path}`}}},{name:"firestore_batch_write",description:"Apply many writes (set / update / delete) in ONE call — the efficient way to seed or bulk-edit (one call, not N). Applied in order; stops on the first failure. Admin by default; pass `as:{uid}` to apply them as a user with rules enforced. Up to 500 ops.",parameters:{type:"object",properties:{operations:{type:"array",description:"Writes applied in order; stops on the first failure (NOT atomic — earlier writes are not rolled back).",minItems:1,maxItems:500,items:{type:"object",properties:{op:{type:"string",enum:["set","update","delete"]},path:{type:"string"},data:{type:"object",description:"Required for set/update; ignored for delete."}},required:["op","path"]}},as:It},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const o=tt(s,i.path);i.op==="set"?await Gs(o,i.data??{}):i.op==="update"?await Ml(o,i.data??{}):await Zo(o)}return{ok:!0,summary:`Applied ${r.operations.length} write(s)`,data:{count:r.operations.length}}}},{name:"firestore_query_where",description:"Query a collection with one or more where clauses (AND-semantics) + optional orderBy + limit. For OR semantics use a single where clause with the `in` / `array-contains-any` op. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},where:{type:"array",description:"One or more where clauses. AND across clauses.",items:OR,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:It},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=pr(s,r.collection),o=r.where.map(l=>kR(l.field,l.op,l.value));r.orderBy&&o.push(yd(r.orderBy)),r.limit&&o.push(mi(r.limit));const a=await hi(pi(i,...o));return{ok:!0,summary:`${a.size} matches in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function PR(e){const{resolveSandbox:t}=e;return[{name:"sandbox_inspect",description:"Single-call sandbox diagnostic. Returns current rules source, lint summary, doc count by collection, and recent denials + requests. Use this FIRST when debugging unexpected sandbox behavior — it surfaces the rules / state / event log without forcing per-tool grep.",parameters:{type:"object",properties:{recentEventLimit:{type:"number",description:"Cap on recent denials/requests returned. Default 10.",default:10}}},async execute(n){const r=n,s=await t(),i=av(s,{recentEventLimit:r.recentEventLimit});return{ok:!0,summary:`rules: ${i.rules.isEmpty?"EMPTY (setRules has not been called)":`${i.rules.sizeBytes}B, ${i.rules.lint.errors} errors / ${i.rules.lint.warnings} warnings`} · docs: ${i.documents.totalCount} across ${Object.keys(i.documents.byCollection).length} collections · events: ${i.events.totalCount} total, ${i.events.recentDenials.length} recent denials`,data:i}}}]}const DR="modulepreload",TR=function(e){return"/__pyric/ui/"+e},wd={},Am=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=o(n.map(u=>{if(u=TR(u),u in wd)return;wd[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":DR,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,m)=>{f.addEventListener("load",p),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};function Om(e){return e.kind==="session_boundary"&&e.phase==="reset"}function MR(e,t){return Om(t)?[t]:[...e,t]}const $m=y.createContext(null),Pm={status:"disabled",handles:null,events:[]};function LR({children:e}){return c.jsx($m.Provider,{value:Pm,children:e})}function Ht(){return y.useContext($m)??Pm}function Ot(e,t){return`${e.replace(/\/$/,"")}${t}`}const wo=new Map;let vo=null;function UR(e){return e||(vo||(vo=`studio-writer-${Math.random().toString(36).slice(2)}`),vo)}function Dm(e){return{token:e?.token,writerId:e?.writerId}}async function Mi(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=wo.get(n);if(r)return r;const s=fetch(Ot(n,"/__pyric/init.json")).then(i=>i.ok?i.json():null).then(i=>typeof i?.sessionToken=="string"?i.sessionToken:null).catch(()=>null).then(i=>(i||wo.delete(n),i));return wo.set(n,s),s}async function Tm(e,t,n=!1){const r={},{token:s,writerId:i}=Dm(t);n&&(r["x-pyric-writer"]=UR(i));const o=await Mi(e,s);return o&&(r["x-pyric-session-token"]=o),r}function Mm(e,t){const n=e,{token:r}=Dm(t),s=(i=!1)=>Tm(n,t,i);return{async read(i){const o=await s(!1),a=await fetch(Ot(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:o});if(a.status===404)return null;if(!a.ok)throw new Error(`workspace.read(${i}) → ${a.status}`);return a.text()},async write(i,o){const a=await s(!0),l=await fetch(Ot(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:a,body:o});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const o=await s(!1),a=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch(Ot(n,`/__pyric/workspace/list${a}`),{headers:o});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async branches(){const i=await s(!1),o=await fetch(Ot(n,"/__pyric/workspace/branches"),{headers:i});if(!o.ok)throw new Error(`workspace.branches() → ${o.status}`);return await o.json()},async remove(i){const o=await s(!0),a=await fetch(Ot(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:o});if(!a.ok)throw new Error(`workspace.remove(${i}) → ${a.status}`)},watch(i){let o=null,a=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Mi(n,r).then(u=>{if(a)return;const d=u?Ot(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):Ot(n,"/__pyric/workspace/watch");o=new EventSource(d),o.addEventListener("change",l)}),()=>{a=!0,o&&(o.removeEventListener("change",l),o.close())}}}}function nr(e,t){return`${e.replace(/\/$/,"")}${t}`}function BR(e,t){const n=e,r=(s=!1)=>Tm(n,t,s);return{async list(){const s=await r(!1),i=await fetch(nr(n,"/__pyric/projects"),{headers:s});if(!i.ok)throw new Error(`projects.list() → ${i.status}`);return await i.json()},async open(s){const i=await r(!1),o=await fetch(nr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!o.ok)throw new Error(`projects.open(${s}) → ${o.status}`);return{meta:await o.json(),workspace:Mm(n,t)}},async create(s){const o={...await r(!0),"content-type":"application/json"},a=await fetch(nr(n,"/__pyric/projects"),{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok)throw new Error(`projects.create() → ${a.status}`);return await a.json()},async update(s,i){const a={...await r(!0),"content-type":"application/json"},l=await fetch(nr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:a,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),o=await fetch(nr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!o.ok)throw new Error(`projects.remove(${s}) → ${o.status}`)}}}function FR(e,t){return`${e.replace(/\/$/,"")}${t}`}function xo(e){return/auth/i.test(e)?"auth":"firestore"}function qR(e){const t=e,n=`studio-${Math.random().toString(36).slice(2)}`,r=async()=>{const u=await Mi(t);return u!==null?{"x-pyric-session-token":u}:{}},s=async()=>({"content-type":"application/json","x-pyric-writer":n,...await r()}),i=new Map,o=u=>FR(t,`/__pyric/state?section=${xo(u)}`),a=async u=>{const d=xo(u),h=i.get(d);if(h)return h;const f=await fetch(o(u),{headers:await r()});let p=new Map;if(f.ok){const m=await f.text();m&&m!=="null"&&(p=cv(m))}else if(f.status!==404)throw new Error(`persistence.read(${u}) → ${f.status}`);return i.set(d,p),p},l=async(u,d)=>{const h=await fetch(o(u),{method:"POST",headers:await s(),body:lv(d)});if(h.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!h.ok)throw new Error(`persistence.write(${u}) → ${h.status}`)};return{async getRecord(u,d){return(await a(u)).get(d)??null},async listRecords(u){return[...(await a(u)).keys()]},async putRecords(u,d){const h=await a(u);for(const[f,p]of d)h.set(f,p);await l(u,h)},async deleteRecords(u,d){const h=await a(u);for(const f of d)h.delete(f);await l(u,h)},async clear(u){i.set(xo(u),new Map);const d=await fetch(o(u),{method:"POST",headers:await s(),body:"null"});if(!d.ok&&d.status!==423)throw new Error(`persistence.clear(${u}) → ${d.status}`)}}}const VR="local";function WR(){const e=new Map,t=new Set,n=r=>{for(const s of t)s(r)};return{async read(r){return e.has(r)?e.get(r):null},async write(r,s){const i=e.has(r)?"update":"create";e.set(r,s),n({path:r,type:i})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",i=[];for(const o of e.keys())s&&!o.startsWith(s)||i.push({path:o,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},async branches(){return[]},watch(r){return t.add(r),()=>t.delete(r)}}}function zR(){const e=WR();let t={id:VR,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[t]},async open(n){if(n!==t.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:t,workspace:e}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===t.id&&(t={...t,...r,updatedAt:Date.now()})},async remove(){}}}var _o={};const HR="/__pyric/sdk/worker.js",$t="pyric-shared-worker",KR="/__pyric/ui/studio";function GR(e,t){if(typeof process<"u"&&_o){const s=_o.NEXT_PUBLIC_PYRIC_STUDIO_URL||_o.PYRIC_STUDIO_URL;if(typeof s=="string"&&s.trim().length>0)return s.trim()}const n=globalThis.__PYRIC_WORKER_INIT__;if(typeof n?.studioUrl=="string"&&n.studioUrl.trim().length>0)return n.studioUrl.trim();if(typeof n?.bridgeUrl=="string"&&n.bridgeUrl.trim().length>0)try{const s=t?.href||(typeof location<"u"?location.href:""),i=new URL(n.bridgeUrl,s||"http://localhost"),o=t?.host||(typeof location<"u"?location.host:"")||(s?new URL(s).host:"");if(i.host&&(!o||i.host!==o))return`${i.protocol==="wss:"||i.protocol==="https:"?"https:":"http:"}//${i.host}/__pyric/ui/studio`}catch{}const r=e?.querySelector('meta[name="pyric-studio-url"]')?.getAttribute("content")?.trim()||e?.querySelector('meta[name="pyric-runtime-chip"]')?.getAttribute("data-studio-url")?.trim();return r||KR}function Lm(e=typeof document>"u"?void 0:document,t=typeof location>"u"?void 0:location){const n=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:GR(e,t),worker:{url:HR,name:$t,servedEpoch:n}}}const yi="pyric:worker-generation",rr="pyric:worker-generation-probe";function JR(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${$t}:${n}`:$t;try{const r=t.getItem(yi);return r&&/^[a-f0-9]{16}$/.test(r)?`${$t}:${r}`:n?(t.setItem(yi,n),`${$t}:${n}`):$t}catch{return n?`${$t}:${n}`:$t}}function YR(e,t){if(!/^[a-f0-9]{16}$/.test(e))throw new Error("Pyric cannot replace the worker: invalid served worker epoch.");if(!t)throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.");try{if(t.setItem(yi,e),t.getItem(yi)!==e)throw new Error("the worker generation could not be read back")}catch(n){throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.",{cause:n})}}function QR(e){if(!e?.removeItem)throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.");try{const t=e.getItem(rr);if(e.setItem(rr,"ok"),e.getItem(rr)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(rr):e.setItem(rr,t)}catch(t){throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.",{cause:t})}}function XR(e){const t=e.schedule??(s=>{setTimeout(s,100)});let n=!1;const r=e.subscribeReload(s=>{if(!n){try{e.commitGeneration(s)}catch(i){e.onPreparationError?.(i);return}n=!0,t(e.reload)}});return{async request(){e.preflight(),await e.retire()},dispose:r}}const ZR=Symbol.for("pyric.ai-evidence"),eN=globalThis,tN=eN[ZR]??=new WeakMap;function vd(e,t){return tN.set(e,Object.freeze({...t})),e}function nN(){let e=null;const t=new Set;return{get currentUser(){return e},set currentUser(n){if(e!==n){e=n;for(const r of[...t])r(n)}},onCurrentUserChanged(n){return t.add(n),()=>t.delete(n)}}}const Um=new WeakMap;let ka;function rN(e,t,n=nN()){const r=e.name,s=n===t?void 0:{},i=new Map,o=new Set,a={app:e,sandbox:t,session:n,services:i,cleanups:o,assertAlive(){if(a.deleted)throw new G("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(l,u){const d=i.get(l);if(d!==void 0)return d;a.assertAlive();const h=u();return i.set(l,h),h},onDelete(l){return a.deleted?(l(),()=>{}):(o.add(l),()=>o.delete(l))},deleted:!1};return Um.set(e,a),a}function sN(e){ka=e}Jv({resolve(e,t){const n=typeof e=="object"&&e!==null?Um.get(e):void 0;if(n)return n},defaultApp(){if(!ka)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return ka()}});const iN="[DEFAULT]",oN=new Map;function aN(e,t){return new G(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function cN(e){return aN("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function lN(e=iN){const t=oN.get(e);if(!t)throw cN(e);return t.app}sN(lN);const Bm=new uv;function uN(e){Bm.follow(e)}function dN(){return Bm.now()}const xd=5174,Ur=12*1024*1024,fN=256,hN=24*1024*1024,_d="/sandbox",pN=4001,mN=4010,yN="worker-relay",gN="storage-byte-route",bN="worker-port",wN=6e4,Fm=15e3,Sd=3*Fm,vN=4004;function qm(e){if(e===null||typeof e!="object")return!1;const n=e.type;return n==="hello"||n==="hello-ack"||n==="attach"||n==="attach-ack"||n==="tool-call"||n==="tool-result"||n==="worker-op"||n==="worker-res"||n==="worker-sub"||n==="worker-unsub"||n==="worker-snap"||n==="worker-client-disconnect"||n==="worker-client-interrupted"||n==="consumer-presence"||n==="remote-set-lens"||n==="remote-set-lens-ack"||n==="worker-event"||n==="worker-message"||n==="worker-message-result"||n==="ping"||n==="pong"}function Ea(e){if(e===null||typeof e!="object")return null;if(typeof Blob<"u"&&e instanceof Blob)return"Blob";if(e instanceof ArrayBuffer)return"ArrayBuffer";if(ArrayBuffer.isView(e))return e.constructor?.name??"TypedArray";if(Array.isArray(e)){for(const t of e){const n=Ea(t);if(n)return n}return null}for(const t of Object.values(e)){const n=Ea(t);if(n)return n}return null}function kd(e,t){const n=Ea(t);if(!n)return;const r=new Error(`worker ${e} produced a binary payload (${n}) that cannot cross the JSON bridge relay — it would be silently corrupted by JSON.stringify. Use the base64 storage ops instead ('storage.getBytes' / 'storage.putBytes'), which carry bytes as JSON-safe 'dataB64' strings; 'storage.getBlob' is MessagePort-only.`);throw r.code="invalid-argument",r}const xN=new TextEncoder;function _N(){let e=0,t=0;return{reserve(n){if(e>=fN)return{accepted:!1,error:{code:"resource-exhausted",message:"This client already has 256 pending operations."}};let s;try{s=xN.encode(JSON.stringify(n)).byteLength}catch{return{accepted:!1,error:{code:"invalid-argument",message:"The operation must have a JSON-serializable encoding."}}}return t+s>hN?{accepted:!1,error:{code:"resource-exhausted",message:"This client exceeds the 24 MiB queued operation byte limit."}}:(e+=1,t+=s,{accepted:!0,release(){e-=1,t-=s}})}}}function Vm(e){if(e===null||typeof e!="object")return;const t=e,n=t.target,s=typeof n=="object"&&n!==null?n.instance:t.instance;return typeof s=="string"&&s.length>0?s:void 0}function In(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function SN(e){return In(e)?(e.mode==="wall"||e.mode==="fixed"||e.mode==="offset")&&Number.isFinite(e.fixedAt)&&Number.isFinite(e.offsetMs):!1}function Wm(e){if(e.ok===!0)return!0;const n=e.error,r=In(n);return e.ok===!1&&r&&typeof n.code=="string"&&typeof n.message=="string"}function zm(e){if(!In(e)||e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return!1;switch(e.t){case"res":return typeof e.id=="string";case"snap":return typeof e.subId=="string";case"event":return typeof e.subId=="string"&&Array.isArray(e.events);case"runtime-reload":return typeof e.epoch=="string";case"clock":return SN(e.state);default:return!1}}function Ed(e){const t={code:"unavailable",message:"The sandbox sent a malformed subscription reply."};if(!Object.hasOwn(e,"value"))return t;const r=e.value;if(!(In(r)&&Object.hasOwn(r,"__error")))return;const o=r.__error;if(!In(o))return t;const u=o.code,d=o.message;if(typeof u!="string"||typeof d!="string")return t;const f=o.aiEvidence,p=In(f),m=o.codeless===!0?{codeless:!0}:{};return{code:u,...m,message:d,denialContext:o.denialContext,aiEnvelope:o.aiEnvelope,aiEvidence:p?f:void 0,envelope:o.envelope}}const Br=new WeakMap;function Hm(e){let t=Br.get(e);return t===void 0&&(t={entries:[],closed:!1},Br.set(e,t)),t}function kN(){return new G("app/app-deleted","Firebase App was deleted")}function Km(e,t){try{e.postMessage(t.message)}catch(n){t.failed?.(n)}}function EN(e,t){for(;t.entries.length>0;){const n=t.entries[0],r=n.frames.splice(0);for(const i of r)Km(e,i);if(!n.released)return;t.entries.shift()}}const jN=()=>performance.now();let CN=jN;function Yc(){return CN()}function Li(e,t,n){const r=Br.get(e);if(!(r!==void 0&&r.entries.length>0)){e.postMessage(t);return}r.entries.push({frames:[{message:t,failed:n}],released:!0})}function Gm(e){const t=Hm(e),n={frames:[],released:!1};return t.closed||t.entries.push(n),{issuedAt:Yc(),send(s,i){const o=t.entries[0]===n;if(t.closed){i(kN());return}if(o){Km(e,{message:s,failed:i});return}n.frames.push({message:s,failed:i})},release(){if(n.released)return;n.released=!0,t.entries[0]===n&&EN(e,t)}}}function Jm(e,t){const n=Br.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>"id"in i.message&&i.message.id===t);if(s>=0)return{entry:r,index:s}}}function Ym(e,t){return Jm(e,t)!==void 0}function RN(e,t){const n=Jm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function Qm(e,t){const n=Br.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>i.message.t==="sub"&&i.message.subId===t);if(s>=0)return{entry:r,index:s}}}function NN(e,t){return Qm(e,t)!==void 0}function IN(e,t){const n=Qm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function Xm(e){const t=Hm(e);t.closed=!0,t.entries.length=0}let AN=0,ON=0;function L(){return`op-${++AN}`}function ln(){return`sub-${++ON}`}const Je=new Map,We=new Map,rt=new Map,Vn=new WeakSet,ja=new Set;function $N(e){return ja.add(e),()=>ja.delete(e)}function Fr(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function PN(e,t,n){if(Vn.has(e))return;const s={...n,message:void 0};We.set(t,s);const i=()=>We.get(t)===s,o=a=>{i()&&We.delete(t)&&n.error?.(a)};return{send(a,l){if(i()){s.message=a;try{l!==void 0?l.send(a,o):Li(e,a,o)}catch(d){queueMicrotask(()=>o(d))}}}}}function us(e,t,n,r,s){const i=PN(e,t,n);return i===void 0?!1:(i.send(r,s),!0)}function DN(e,t,n,r,s,i){if(Vn.has(e))return s?.(Fr()),!1;rt.set(t,{port:e,next:n,error:s,message:r,restored:i});const a=l=>{rt.get(t)?.message===r&&rt.delete(t)&&s?.(l instanceof G?l:Fr())};try{Li(e,r,a)}catch(l){queueMicrotask(()=>a(l))}return!0}function TN(e,t){const n=e.messagingVisibility;n&&t({...n,id:L()});for(const[r,s]of We){const i=s.message;!(s.port===e&&i?.t==="sub")||!(i.target==="messaging.foreground"||i.target==="messaging.background")||(t({t:"unsub",subId:r}),t(i))}}function MN(e,t=n=>e.postMessage(n)){for(const[n,r]of We){const s=r.message;if(!(r.port===e&&s?.t==="sub"))continue;const o=typeof s.target=="object"&&"service"in s.target&&s.target.service==="rtdb",a=r.service==="firestore"||o,l=s.target==="presence";(a||l)&&(t({t:"unsub",subId:n}),t(s))}for(const[n,r]of rt)r.port===e&&(r.restored?.(),t({t:"unsub",subId:n}),t(r.message))}function LN(e,t){for(const n of We.values()){const r=n.message;n.port===e&&r?.t==="sub"&&(r.target==="authState"||r.target==="idToken")&&t(r)}}function nt(e,t,n){const r=We.get(t)??rt.get(t);if(!(r!==void 0)||(We.delete(t),rt.delete(t),Vn.has(e))||r.message===void 0||IN(e,t)||e.withdrawSubscription?.(t)===!0)return;const a={t:"unsub",subId:t};n!==void 0&&n!==""&&(a.clientSessionId=n);const u=()=>{};try{Li(e,a,u)}catch{}}function qr(e,t,n=()=>!0){for(const[r,s]of[...Je])s.port===e&&n(r)&&(Wn(r),s.reject(t))}function UN(e,t){const n=[];for(const[r,s]of Je)s.port===e&&t(r)&&n.push({id:r,message:s.message});return n}function BN(e){const t=[];for(const n of e){const r=Je.get(n),s=r?.message;if(!(r!==void 0&&s?.t==="op"))continue;const o={...s,id:L()};Je.delete(n),Je.set(o.id,{...r,message:o}),t.push(o)}return t}function jd(e,t){Wn(e)?.reject(t)}function FN(e){Wn(e)}function qN(e){Vn.add(e),qr(e,Fr()),Zm(e,new G("aborted","The operation was aborted."),Fr()),e.onmessage=null}function Zm(e,t,n=t){for(const[r,s]of[...We]){if(s.port!==e)continue;We.delete(r),s.service==="firestore"?s.error?.(t):ey(s.message)&&s.error?.(n),s.close?.()}for(const[r,s]of[...rt])s.port===e&&(rt.delete(r),s.error?.(n))}function ey(e){if(!(e?.t==="sub"))return!1;const n=e.target;return typeof n=="object"&&n!==null&&"service"in n&&n.service==="ai"}function VN(e,t,n){for(const[r,s]of[...We])!(s.port===e&&ey(s.message))||!(!n(r)&&!NN(e,r))||(nt(e,r),s.error?.(t))}function Cd(e,t,n,r){if(t.denialContext===void 0||typeof fetch!="function")return;const s={kind:e,code:t.code??"unknown",message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{},...n===void 0?{}:{instance:n},...r!==void 0?{owners:r}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}).catch(()=>{})}catch{}}function Ui(e){e.onmessage=t=>{const n=t.data;if(!zm(n)){const u=new G("unavailable","The sandbox sent a malformed reply envelope. The operation may have completed; check state before retrying.");qr(e,u);for(const[d,h]of We)h.port===e&&(nt(e,d),h.error?.(u));for(const[d,h]of rt)h.port===e&&(nt(e,d),h.error?.(u));return}const s=n.t==="res",i=n.t==="snap",o=n.t==="event",a=n.t==="runtime-reload",l=n.t==="clock";if(s){const u=Je.get(n.id);if(u===void 0||u.port!==e)return;if(Wn(n.id),!Wm(n)){u.reject(new G("unavailable","The sandbox sent a malformed operation reply. The operation may have completed; check state before retrying."));return}if(n.ok)u.resolve(n.value);else{const p=n.error.codeless!==!0;let m;p?m=new G(n.error.code,n.error.message):m=new Error(n.error.message),n.error.denialContext!==void 0&&(m.denialContext=n.error.denialContext);const b=n.error.aiEvidence;b!==void 0&&vd(m,b),n.error.aiEnvelope!==void 0&&(m.aiEnvelope=n.error.aiEnvelope),Cd("read",m,u.instance),u.reject(m)}}else if(i){const u=We.get(n.subId);if(u===void 0){const p=rt.get(n.subId),m=Ed(n);if(p!==void 0&&p.port===e&&m!==void 0){nt(e,n.subId,p.message.clientSessionId);const g=m.codeless!==!0?new G(m.code,m.message):Object.assign(new Error(m.message),{code:"unavailable"});p.error?.(g)}return}if(u.port!==e)return;const h=Ed(n);if(h!==void 0){nt(e,n.subId,u.message?.clientSessionId);const p=h.codeless!==!0;let m;p?m=new G(h.code,h.message):m=new Error(h.message),h.denialContext!==void 0&&(m.denialContext=h.denialContext);const b=h.aiEvidence;b!==void 0&&vd(m,b),h.aiEnvelope!==void 0&&(m.aiEnvelope=h.aiEnvelope);const v=u.message,_=v!==void 0&&"owners"in v?v.owners:void 0;Cd("listener",m,Vm(v),_);const S=u.error;S!==void 0?S.call(u,m):console.error("pyric/firestore: Uncaught Error in snapshot listener:",m);return}u.next(n.value)}else if(o){const u=rt.get(n.subId);u!==void 0&&u.port===e&&u.next(n.events)}else if(a)for(const u of ja)u(n);else l&&uN(n.state)},e.postMessage({t:"clock-subscribe"})}const vr="pyric:auth-lens";function WN(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"||t.mode==="anon"?!0:t.mode==="as"&&typeof t.uid=="string"}function ty(e){if(WN(e))return e}function zN(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(vr);if(!e)return;const t=JSON.parse(e),n=ty(t);if(n)return n;sessionStorage.removeItem(vr);return}catch{try{sessionStorage.removeItem(vr)}catch{}return}}let _t=zN();const Ca=new Set;function HN(e){return Ca.add(e),()=>{Ca.delete(e)}}function Rd(e){if(_t=ty(e),typeof sessionStorage<"u")try{_t?sessionStorage.setItem(vr,JSON.stringify(_t)):sessionStorage.removeItem(vr)}catch{}for(const t of[...Ca])try{t(_t)}catch(n){console.error("Error in subscribeLens listener:",n)}}function KN(){return _t}let Ra;function GN(e){Ra=e}function Qc(e){return Ra&&(e.t==="op"||e.t==="sub")?{...e,issuer:Ra}:e}function Bi(e,t,n,r){if(Vn.has(e))return Promise.reject(Fr());const o=t.t==="op"||t.t==="tool"?JN(e,t.clientSessionId):void 0,a=o?.reserve(t);return a?.accepted===!1?Promise.reject(new G(a.error.code,a.error.message)):(t.t==="disconnect"&&Xm(e),new Promise((d,h)=>{const f=t;Je.set(f.id,{port:e,clientSessionId:t.clientSessionId,instance:Vm(t),budget:o,release:a?.release,issuedAt:r?.issuedAt??Yc(),message:t,resolve:d,reject:h});const p=m=>{Wn(f.id)!==void 0&&h(m)};try{n!==void 0?n(t):r!==void 0?r.send(t,p):Li(e,t,p)}catch(m){p(m)}}))}function JN(e,t){for(const n of Je.values()){const r=n.port===e&&n.clientSessionId===t,s=n.budget;if(r&&s!==void 0)return s}return _N()}function Wn(e){const t=Je.get(e);return Je.delete(e),t!==void 0&&RN(t.port,e),t?.release?.(),t}function ee(e,t,n){return Bi(e,Qc(t),void 0,n)}function ny(e,t,n,r){const s=t.id;let i;const o=new Promise((a,l)=>{i=setTimeout(()=>{Wn(s)!==void 0&&l(new Error(r))},n)});return Promise.race([ee(e,t),o]).finally(()=>{i!==void 0&&clearTimeout(i)})}function pe(e,t,n){if(Vn.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new G("failed-precondition","The client has already been terminated."));const r=_t?{...t,actAs:_t}:t;return ee(e,r,n)}async function YN(e,t,n={}){const r=n.timeoutMs??12e3;await ny(e.port,{t:"op",id:L(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function QN(e){return $N(t=>e(t.epoch))}const Na=Symbol("pyric/database/target"),XN=new WeakMap;function ZN(e){let t;if(Na in e?t=e[Na]:t=XN.get(e),!t)throw new TypeError("pyric/database: unrecognized reference — was it produced by a factory in this package?");return t.kind==="sandbox-live"&&t.assertUsable?.(),t}const Nd=eI();function eI(){let e;try{const n=import.meta.url;typeof n=="string"&&(e=n)}catch{e=void 0}if(e===void 0)return"";const t=e.slice(0,e.lastIndexOf("/"));return t.startsWith("file://")?t.slice(7):t}function tI(e){return Nd.length===0?e:e.split(`
131
+ `).filter(t=>!t.includes(Nd)).join(`
132
+ `)}function ry(e){const t=[],n=nI();n!==void 0&&t.push(n);const r=dv(e?.owner);if(r!==void 0&&t.push(r),t.length!==0)return t}function nI(){if(!fv())return;const e=hv();if(e!==void 0)return pv(tI(e))}function rI(e){const t=new Map,n=new Set,r=()=>{for(const i of[...n])try{i()}catch{}},s=e.subscribe(i=>{i.phase==="remove"&&t.delete(i.record.id)});return{record(i,o){const a=Hs(o);a===void 0||a.kind!=="regions"||(t.set(i,Object.freeze([...a.selectors])),r())},regions:i=>t.get(i)??[],subscribe(i){return n.add(i),()=>{n.delete(i)}},dispose(){s(),t.clear(),n.clear()}}}const Id=Symbol.for("pyric.delivered-regions"),Ad=globalThis,sI=Ad[Id]??(Ad[Id]=rI(Yr));function iI(e,t){sI.record(e,t)}function oI(e,t,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(e,{type:"classic",name:t??"pyric-shared-worker"});n.onError&&r.addEventListener("error",i=>{const o=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${o}`))});const s=r.port;return Ui(s),s.start(),{__kind:"client-db",port:s}}async function aI(e,t={}){const n=L(),r=t.timeoutMs??2e3;return(await ny(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function cI(e){return(await ee(e.port,{t:"op",id:L(),method:"getVersion"})).instanceId??""}async function lI(e){return(await ee(e.port,{t:"op",id:L(),method:"exportState"})).bundle}async function uI(e,t){await ee(e.port,{t:"op",id:L(),method:"importState",bundle:t})}async function dI(e,t){await ee(e.port,{t:"op",id:L(),method:"checkpoint",name:t})}async function fI(e){return(await ee(e.port,{t:"op",id:L(),method:"listCheckpoints"})).checkpoints??[]}async function hI(e,t){await ee(e.port,{t:"op",id:L(),method:"restore",name:t})}async function pI(e,t){await ee(e.port,{t:"op",id:L(),method:"deleteCheckpoint",name:t})}async function mI(e,t,n,r,s){return await ee(e.port,{t:"tool",id:L(),name:t,args:n,clientSessionId:s,actAs:r})}function yI(e,t,n){return Bi(e.port,{...t,issuer:void 0,relaySource:"remote",clientSessionId:n,t:"op",id:L()})}function gI(e,t,n,r){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const s=ln();return us(e.port,s,{port:e.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...t,issuer:void 0,relaySource:"remote",clientSessionId:r,t:"sub",subId:s})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{nt(e.port,s,r)}}function bI(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}function sy(e){return e.kind==="where"?{...e,value:qh(e.value)}:{kind:e.kind,filters:e.filters.map(sy)}}function wI(e){return e.kind==="where"||e.kind==="and"||e.kind==="or"?sy(e):"values"in e?{...e,values:e.values.map(qh)}:e}function zn(e,t,n,r=ry(void 0)){const s=e.descriptor,i=s.__ref==="query"?s.source:s,o=i.__ref==="group"?i.collectionId:i.path,a=s.__ref==="query"?s.constraints:[];return Yr.begin({app:e.port,method:t,kind:n,owners:r,source:{service:"firestore",target:o,isQuery:s.__ref!=="doc",...s.__ref==="doc"?{}:{indexQuery:Yv(o,i.__ref==="group",a.filter(l=>["where","and","or"].includes(l.kind)),a.filter(l=>l.kind==="orderBy").map(l=>({...l,direction:l.direction??"asc"})))},key:Cr({base:i,constraints:s.__ref==="query"?s.constraints.map(wI):[]})}})}const vI=[];function iy(e){for(const t of[...vI])t.port===e&&t.close()}const xI=5e3;function _I(){return Object.assign(new Error("Timed out waiting for SharedWorker app cleanup acknowledgment. Close all tabs using this pyric sandbox origin so the worker can restart."),{code:"app/delete-timeout"})}async function SI(e,t={}){let n;try{const r=Bi(e.port,{t:"disconnect",id:L()}),s=new Promise((i,o)=>{n=setTimeout(()=>o(_I()),t.ackTimeoutMs??xI)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),iy(e.port),qN(e.port),e.port.close()}}function kI(e,t){Zm(e,t),iy(e)}function Xc(e){return e.split("/").at(-1)??e}function Vt(e,t,n=null){function r(i){return Vt(e,t,i)}const s={__kind:"doc-ref",descriptor:{__ref:"doc",path:t},port:e,id:Xc(t),path:t,converter:n,withConverter:r};return Bh(s,t,e),s}function EI(e,t){const n=JSON.parse(e.json);return t!==void 0?mv(n,t,e.valueEncoding):mc(n,e.valueEncoding)}const Ia=4*1024*1024,Fi=512*1024*1024;function Zc(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Fi/1048576} MiB maximum storage object cap (MAX_STORAGE_OBJECT_BYTES).`);return n.code="storage/quota-exceeded",n}function Od(e){let t="";for(let r=0;r<e.length;r+=32768){const s=e.subarray(r,r+32768);t+=String.fromCharCode.apply(null,s)}return btoa(t)}function $d(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function jI(e,t){return EI(e,{create:r=>Vt(t,r)})}const oy=Object.freeze({fromCache:!1,hasPendingWrites:!1}),CI=Object.freeze({fromCache:!1,hasPendingWrites:!0});function Aa(e){return e.hasPendingWrites===!0?CI:oy}const ay=new WeakMap;function RI(e){return ay.get(e)}function el(e,t,n,r=oy){if(!tl(e))throw new G("invalid-argument","The sandbox sent a malformed document result.");const i=e.data,o=()=>e.exists&&i!==void 0?jI(i,t):void 0,a=o(),l=e.path??e.id,u=n??Vt(t,l),d=()=>{const f=o();if(f===void 0)return;const m=u.converter;if(m!==null){const b={id:e.id,ref:Vt(t,l),exists:()=>!0,metadata:r,data:()=>f};return m.fromFirestore(b)}return f},h={id:e.id,path:l,ref:u,exists:()=>e.exists,metadata:r,data:d,get:f=>NI(o(),f)};return ay.set(h,{id:e.id,path:l,exists:e.exists,data:a}),h}function NI(e,t){try{return bv(e,t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new G("invalid-argument",`Function DocumentSnapshot.get() called with invalid data. ${r}`)}}function Oa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tl(e){if(!Oa(e))return!1;const r=e.data,s=r===void 0||Oa(r)&&typeof r.json=="string",i=e.path===void 0||typeof e.path=="string";return typeof e.id=="string"&&typeof e.exists=="boolean"&&i&&s&&cy(e)}function cy(e){return e.hasPendingWrites===void 0||typeof e.hasPendingWrites=="boolean"}function ly(e){return Oa(e)&&Array.isArray(e.docs)&&e.docs.every(tl)&&cy(e)}function II(e,t,n,r){if(ly(e)){const o=uy(e,t,n,r);return r.previous!==void 0&&o.docChanges().length===0&&(r.excludesMetadataChanges||o.metadata.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previous=e.docs,r.previousHasPendingWrites=o.metadata.hasPendingWrites,o)}if(tl(e)){const o=Aa(e),a=r.previousDocument;return a!==void 0&&a.exists===e.exists&&(!e.exists||a.data?.json===e.data?.json)&&(r.excludesMetadataChanges||o.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previousDocument=e,r.previousHasPendingWrites=o.hasPendingWrites,el(e,t,Vt(t,e.path??e.id,n),o))}throw new G("invalid-argument","The sandbox sent a malformed Firestore snapshot.")}function uy(e,t,n=null,r={excludesMetadataChanges:!1}){if(!ly(e))throw new G("invalid-argument","The sandbox sent a malformed query result.");const i=Aa(e),o=h=>el(h,t,Vt(t,h.path??h.id,n),Aa(h)),a=e.docs.map(o),l=e.docs.map(h=>({path:h.path??h.id,doc:h})),u=r.previous?.map(h=>({path:h.path??h.id,doc:h})),d=yv(u,l,a,(h,f)=>h.doc.data?.json===f.doc.data?.json,h=>o(h.doc));return{metadata:i,size:a.length,empty:a.length===0,docs:a,forEach:Fh(a),docChanges:gv(d,r.excludesMetadataChanges)}}function AI(e,...t){const n=e.port;let r,s=null;const i=e.__kind==="client-db",o=t.length>0;if(i){if(!o)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const a=e.descriptor.path;s=e.converter,o?r=`${a}/${t.join("/")}`:r=`${a}/${wv()}`}return Vt(n,r,s)}function OI(e,...t){const n=e.port;if(t.length===0)throw new TypeError("collection() requires a path segment.");let r;return e.__kind==="client-db"?r=t.join("/"):r=`${e.descriptor.path}/${t.join("/")}`,dy(n,r,null)}function dy(e,t,n){function r(i){return dy(e,t,i)}return{__kind:"coll-ref",descriptor:{__ref:"collection",path:t},port:e,id:Xc(t),path:t,converter:n,withConverter:r}}function fy(e,t,n){function r(s){return fy(e,t,s)}return{__kind:"query",descriptor:t,port:e,converter:n,withConverter:r}}const $I="__name__",PI=new Set(["<","<=",">",">=","!=","not-in"]),hy=new WeakMap,Pd=new WeakMap;function DI(e,t){if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n}function py(e,t){if(e.kind==="where"){PI.has(e.op)&&t.push(e.field);return}for(const n of e.filters)py(n,t)}function TI(e){return e.length===1&&e[0]!==null&&typeof e[0]=="object"&&"data"in e[0]&&typeof e[0].data=="function"}function MI(e,t){if(!TI(t))return{type:e,_descriptor:{kind:e,values:t.map(jr),valueEncoding:cn}};const n=t[0],r=RI(n)??(()=>{const i=n.data(),o=typeof n.id=="string"?n.id:"",a=typeof n.path=="string"?n.path:typeof n.ref?.path=="string"?n.ref.path:o,l=typeof n.exists=="function"?!!n.exists():i!==void 0;return{id:o,path:a,exists:l,data:i}})(),s={type:e,_descriptor:{kind:e,values:[],valueEncoding:cn}};return hy.set(s,{__snapshotCursor:!0,kind:e,snapshot:r}),s}function So(e){return"__snapshotCursor"in e}function LI(e){if(!e.some(So))return e;const n=[],r=[];for(const o of e)So(o)||(o.kind==="orderBy"?n.push({field:o.field,direction:o.direction??"asc"}):(o.kind==="where"||o.kind==="and"||o.kind==="or")&&py(o,r));const s=vv(n,r),i=s.map(o=>({kind:"orderBy",field:o.field,direction:o.direction}));for(const o of e){if(So(o)){const{snapshot:a}=o;if(!a.exists||a.data===void 0)throw new G("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${a.id||"<unknown>"}.`);const l=s.map(u=>u.field===$I?jr(a.path):jr(DI(a.data,u.field)));i.push({kind:o.kind,values:l,valueEncoding:cn});continue}o.kind!=="orderBy"&&i.push(o)}return i}function UI(e){return{type:"limit",_descriptor:{kind:"limit",n:e}}}function BI(...e){return MI("startAfter",e)}function FI(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),s=[...e.__kind==="query"?Pd.get(e)??e.descriptor.constraints:[],...t.map(a=>hy.get(a)??a._descriptor)],i={__ref:"query",source:n.__ref==="query"?n.source:n,constraints:LI(s)},o=fy(e.port,i,e.converter);return Pd.set(o,s),o}function qI(e){return VI(e,"getDoc")}async function VI(e,t){const n=zn(e,t,"operation");try{const r=await pe(e.port,{t:"op",id:L(),method:"getDoc",path:e.descriptor.path});return On(n,el(r,e.port,e))}catch(r){throw n.fail(),r}}function WI(e){return zI(e,"getDocs")}async function zI(e,t){const n=zn(e,t,"operation");try{const r=await pe(e.port,{t:"op",id:L(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return On(n,uy(r,e.port,e.converter))}catch(r){throw n.fail(),r}}async function HI(e){return(await pe(e.port,{t:"op",id:L(),method:"listRootCollections"})).ids}async function KI(e,t){return(await pe(e.port,{t:"op",id:L(),method:"listSubcollections",docPath:t})).ids}function Dd(e){if(!(typeof e=="object"&&e!==null))return!1;const n=e;return typeof n.next=="function"||typeof n.error=="function"||typeof n.complete=="function"}function GI(e,t,n){const r=typeof e=="object"&&e!==null&&!Dd(e),s=r?e:void 0,i=r?t:e,o=r?n:t;return Dd(i)?{options:s,next:i.next?.bind(i),error:i.error?.bind(i)}:{options:s,next:i,error:o}}function JI(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function YI(e,t,n,r){const{options:s,next:i,error:o}=GI(t,n,r),a=o??JI,l=ry(s),u=s?.includeMetadataChanges===!0,d={excludesMetadataChanges:!u};let h=ln();const f=e.port,p=zn(e,"onSnapshot","subscription",l);p.transport(h);const m={port:f,service:"firestore",next:_=>{let S;try{S=II(_,f,e.converter,d)}catch(A){v(),a(A);return}if(S===null)return;const k=S,R=_;p.delivered(k,R.usage);const O=i;O!==void 0&&iI(p.id,()=>O(k))},error:_=>{p.fail(),a(_)},close:()=>p.close()},g=e.descriptor;function b(){const _={t:"sub",subId:h,target:g};_t!==void 0&&(_.actAs=_t),l!==void 0&&(_.owners=l),u&&(_.includeMetadataChanges=!0);const R=us(f,h,m,Qc(_));return!R&&p.fail(),!R&&o!==void 0&&queueMicrotask(()=>o(new Error("Firebase App was deleted"))),R}b();let w=!1;const x=HN(()=>{w||(nt(f,h),h=ln(),p.transport(h),b())});function v(){w=!0,p.close(),x(),nt(f,h)}return v}function my(e,t){const n=e.converter,r=n!==null;let s=t;return r&&(s=n.toFirestore(t)),xv(s)}async function QI(e,t,n){return wc(zn(e,"setDoc","operation"),async()=>{const r=my(e,t);await pe(e.port,{t:"op",id:L(),method:"setDoc",path:e.descriptor.path,data:jr(r),valueEncoding:cn,options:n})})}async function XI(e){return wc(zn(e,"deleteDoc","operation"),async()=>{await pe(e.port,{t:"op",id:L(),method:"deleteDoc",path:e.descriptor.path})})}async function ZI(e,t){return wc(zn(e,"addDoc","operation"),async()=>{const n=my(e,t),r=await pe(e.port,{t:"op",id:L(),method:"addDoc",collectionPath:e.descriptor.path,data:jr(n),valueEncoding:cn});return Vt(e.port,r.path,e.converter)})}async function eA(e,t){return await ee(e.port,{t:"op",id:L(),method:"admin.listDocuments",path:t})}const tA=mc({__type:"path",segments:[]},cn).constructor;class nA{port;subId=ln();subscribers=new Set;history=new Vh(Wh);isAwaitingHistory=!0;hasReceivedHistory=!1;constructor(t){this.port=t}open(t){this.subscribers.add(t),En.set(this.port,this);const n={t:"sub",subId:this.subId,target:"events"};DN(this.port,this.subId,r=>this.receive(r),n,r=>this.fail(r),()=>{this.isAwaitingHistory=!0})}join(t){this.subscribers.add(t),this.hasReceivedHistory&&queueMicrotask(()=>{this.subscribers.has(t)&&Td(t,this.history.snapshot())})}leave(t){this.subscribers.delete(t)&&this.subscribers.size===0&&(En.delete(this.port),nt(this.port,this.subId))}receive(t){const n=this.isAwaitingHistory;n&&this.history.clear();for(const s of t)this.record(s);this.isAwaitingHistory=!1;const r=n&&!this.hasReceivedHistory;this.hasReceivedHistory=!0;for(const s of[...this.subscribers])this.subscribers.has(s)&&(r?Td(s,t):s.isPrimed&&yy(s,t,n))}record(t){t.kind==="session_boundary"&&t.phase==="reset"?this.history.clear():this.history.append(t)}fail(t){En.get(this.port)===this&&En.delete(this.port);const n=[...this.subscribers];this.subscribers.clear();for(const r of n)try{r.onError?.(t)}catch(s){console.error("pyric: Uncaught Error in event subscriber error handler:",s)}}}const En=new WeakMap;function yy(e,t,n){try{e.callback(t,{history:n})}catch(r){console.error("pyric: Uncaught Error in event subscriber:",r)}}function Td(e,t){e.isPrimed=!0,yy(e,t,!0)}function rA(e,t,n){const r=e.port,s={callback:t,onError:n,isPrimed:!1},i=En.get(r);return i?i.join(s):new nA(r).open(s),()=>{En.get(r)?.leave(s)}}function sA(e){return e.__type__==="__vector__"&&Array.isArray(e.value)?!0:typeof e.__type=="string"?e.__type==="timestamp"||e.__type==="bytes"||e.__type==="latlng"||e.__type==="duration"||e.__type==="reference":typeof e.type=="string"?e.type==="firestore/timestamp/1.0"||e.type==="firestore/bytes/1.0"||e.type==="firestore/geoPoint/1.0"||e.type==="firestore/vectorValue/1.0":!1}function Bs(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Bs);const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;const n=e;if(n.type==="pyric/map/1.0"){const s=n.fields;if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError("Invalid encoded map fields.");const i={};for(const[o,a]of Object.entries(s))i[o]=Bs(a);return i}if(n.__type==="number"){if(n.value==="NaN")return Number.NaN;if(n.value==="Infinity")return 1/0;if(n.value==="-Infinity")return-1/0;if(n.value==="-0")return-0}if(n.__type==="path"&&Array.isArray(n.segments)){const s=n.bindings,i=s!==null&&typeof s=="object"&&!Array.isArray(s)?s:void 0;return new tA(n.segments,i)}if(sA(n))return mc(n,cn);const r={};for(const[s,i]of Object.entries(n))r[s]=Bs(i);return r}async function iA(e){const t=await ee(e.port,{t:"op",id:L(),method:"getSnapshot"}),n={};for(const[r,s]of Object.entries(t.firestore??{}))n[r]=Bs(s);return{firestore:n,services:t.services}}async function oA(e){return await ee(e.port,{t:"op",id:L(),method:"resetAll"})??{errors:[]}}const aA=15e3;function cA(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function Md(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function Ld(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function lA(){return cA()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ud(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Bd(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function uA(e){const{db:t,kind:n}=e,r=e.clientId??lA(),s=e.heartbeatIntervalMs??aA;let i=!1,o=null;const a=()=>{ee(t.port,{t:"op",id:L(),method:"presence.register",clientId:r,kind:n,route:Ud(),visibility:Bd()}).catch(()=>{})},l=()=>{ee(t.port,{t:"op",id:L(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{ee(t.port,{t:"op",id:L(),method:"presence.update",clientId:r,route:Ud(),visibility:Bd()}).catch(()=>{})},d=()=>{ee(t.port,{t:"op",id:L(),method:"presence.disconnect",clientId:r}).catch(()=>{})};a(),Md()&&document.addEventListener("visibilitychange",u),Ld()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",h),o=setInterval(()=>{i||l()},s));function h(){f()}function f(){i||(i=!0,o!=null&&(clearInterval(o),o=null),Md()&&document.removeEventListener("visibilitychange",u),Ld()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",h)),d())}return{clientId:r,kind:n,stop:f}}function dA(e,t){const n=ln();return us(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{nt(e.port,n)}}async function fA(e){return await ee(e.port,{t:"op",id:L(),method:"auth.listUsers"})}async function hA(e,t){return await ee(e.port,{t:"op",id:L(),method:"auth.adminCreateUser",request:t})}async function pA(e,t,n){return await ee(e.port,{t:"op",id:L(),method:"auth.adminUpdateUser",uid:t,request:n})}async function mA(e,t){await ee(e.port,{t:"op",id:L(),method:"auth.adminDeleteUser",uid:t})}async function yA(e){await ee(e.port,{t:"op",id:L(),method:"auth.adminClearUsers"})}async function gA(e){return await ee(e.port,{t:"op",id:L(),method:"auth.getProviderConfig"})}async function bA(e,t,n){await ee(e.port,{t:"op",id:L(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const wA=Symbol("pyric.clientUser.port");function vA(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:Wp(t.photoURL,zp()),phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await ee(e,{t:"op",id:L(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await ee(e,{t:"op",id:L(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,wA,{value:e,enumerable:!1}),n}function gy(e,t){return t?vA(e,t):null}function xA(e,t){let n;if(typeof e=="string"||e instanceof URL){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),Ui(n)}else n=e.port;let s=null;const i={__kind:"client-auth",port:n,currentUser:null,get tenantId(){return s},set tenantId(a){s=a,ee(n,{t:"op",id:L(),method:"auth.setTenantId",tenantId:a})}};n.restoreAuth=async a=>{await a({t:"op",id:L(),method:"auth.setTenantId",tenantId:i.tenantId});const l=i.currentUser;l!==null&&await _A(i,l.uid,a,l.tenantId)};const o=ln();return us(n,o,{port:n,next:a=>{i.currentUser=gy(n,a)}},{t:"sub",subId:o,target:"idToken"}),i}async function _A(e,t,n=s=>ee(e.port,s),r=e.tenantId){const s=await n({t:"op",id:L(),method:"auth.restorePortSession",uid:t,tenantId:r}),i=gy(e.port,s);return e.currentUser=i,i}const SA=1e4,by="The hosted sandbox connection was not restored within 10 seconds. The request was not sent.";let wy=SA;function kA(e){let t;const n=new Promise((r,s)=>{t=setTimeout(()=>s(new G("unavailable",by)),wy)});return Promise.race([e,n]).finally(()=>clearTimeout(t))}function ko(e){if("id"in e&&typeof e.id=="string")return e.id}function Fd(e){if(e.t==="sub"||e.t==="unsub")return e.subId}function EA(e){const t=[];function n(s,i){const o=t.indexOf(s);o<0||(t.splice(o,1),qr(e,new G("unavailable",by),l=>l===i))}function r(){const s=t.splice(0);for(const i of s)clearTimeout(i.deadline);return s}return{hold(s){const i={message:s},o=ko(s);if(t.push(i),o===void 0)return;const l=Je.get(o);if(!(l!==void 0&&l.port===e))return;const d=l.issuedAt+wy-Yc();if(d<=0){n(i,o);return}i.deadline=setTimeout(()=>n(i,o),d)},holdAgain(s){t.unshift(...s.map(i=>({message:i})))},holdsRequest(s){return t.some(i=>ko(i.message)===s)},holdsSubscription(s){const i=Fd(s);return i!==void 0?t.some(a=>a.message.t==="sub"&&a.message.subId===i):!1},forgetSubscription(s){const i=t.findIndex(a=>a.message.t==="sub"&&a.message.subId===s),o=i>=0;return o&&t.splice(i,1),o},flush(s){const i=r(),o=a=>Fd(a.message)!==void 0;for(const a of i.filter(o))s(a.message);for(const a of i.filter(l=>!o(l)))s(a.message)},drop(){r()},fail(s){const i=new Set(r().map(o=>ko(o.message)));qr(e,s,o=>i.has(o))}}}function jA(e){return e.then(t=>({result:t}),t=>({error:t}))}function CA(e){return e!==void 0&&"result"in e?e.result:void 0}function vy(e){const t=e?.code;if(typeof t=="string")return t}async function RA(e,t){if(!(t!==void 0))return!1;try{return await HA(e,t),!0}catch(r){if(vy(r)==="storage/unauthorized")return!1;throw r}}async function NA(e,t){if(t.replacedObject===!0)throw new G("storage/unknown","The host no longer holds the object this upload replaced, so it cannot be restored.");try{await Oy(e)}catch(n){if(!(vy(n)==="storage/object-not-found"))throw n}}function IA(e){return e.replacedObject===!0?"restore":"remove"}async function AA(e,t){try{await RA(e,t.rollbackToken)||await NA(e,t)}catch(n){throw ga(e.fullPath,n,IA(t))}}function OA(e){return e instanceof Error?e:new Error(String(e))}function $A(e){return e instanceof Blob?e.size:e.byteLength}function PA(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function DA(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class TA{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_heldOutcome;_sentCommit;_error;_ref;_data;_metadata;_upload;_inFlight;_sending=!1;_resyncs=!1;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=$A(n),i=new Date(dN()).toISOString();let o="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(o=n.type),r!==void 0&&r.contentType!==void 0){const h=r.contentType;h!==void 0&&(o=h)}const u={fullPath:t.fullPath,name:t.name,bucket:t.bucket||"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:o};this._promise=new Promise((d,h)=>{this._resolve=d,this._reject=h}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},this._start(),queueMicrotask(()=>{this._runStep()})}_start(){!(this._ref.port.byteRouteSettled?.()!==void 0)&&xr(this._ref)!==void 0?this._sendOverRoute():this._commitUpload()}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._resyncs=!0,this._inFlight?.abort(),this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;if((this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t){const r=PA();return this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._inFlight?.abort(),this._rollBackCanceled().then(()=>this._settleCanceled(r),s=>this._settleCanceled(OA(s))),!0}return!1}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=this._sentCommit,r=t??(n===void 0?void 0:await n),s=this._upload;s!==void 0&&await Fs(s);const i=CA(r);i!==void 0&&await AA(this._ref,i)}_sendCommit(t){const n=jA(t);return this._sentCommit=n,n}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,"result"in t?this._succeed(t.result.metadata):this._fail(t.error),!0)}on(t,n,r,s){let i,o,a,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Lt(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Lt(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Lt(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ai(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const a=i.next;try{Lt(this),a(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const a=i.complete;try{ai(this),a()}catch{}}}}async _sendOverRoute(){if(this._sending)return;this._sending=!0;const t=Ny(this._data),n=()=>this._snapshot.state==="running";try{const r=xr(this._ref);let s=this._upload;if(s===void 0){const l=this._metadata?.contentType??(t.type!==""?t.type:void 0);if(s=await Ey(this._ref,r,t.size,l,this._metadata),this._upload=s,this._snapshot.state==="canceled"&&await Fs(s),!n())return}let i=this._snapshot.bytesTransferred;for(this._resyncs&&(i=await zA(s),this._resyncs=!1);n()&&i<s.size;){const l=new AbortController;if(this._inFlight=l,i=await Cy(s,t,i,l.signal),this._inFlight=void 0,!n())return;this._updateSnapshot("running",i),this._notifyObservers("next")}if(!n())return;const o=await this._sendCommit(Ry(s,!0));if("error"in o&&n())throw o.error;this._settleCommit(o)}catch(r){if(this._inFlight=void 0,!n())return;this._error=r instanceof Error?r:new Error(String(r)),this._updateSnapshot("error",this._snapshot.bytesTransferred);const s=this._upload;s!==void 0&&await Fs(s),this._notifyObservers("error"),this._reject(this._error)}finally{this._sending=!1,n()&&queueMicrotask(()=>this._runStep())}}_runStep(){if(this._snapshot.state!=="running")return;if(xr(this._ref)!==void 0&&!this._committing){this._releaseHeldOutcome()||this._sendOverRoute();return}if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let i=0;this._snapshot.totalBytes>0&&(i=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",i),this._notifyObservers("next")}this._releaseHeldOutcome()||this._commitUpload()}_succeed(t){this._updateSnapshot("success",this._snapshot.totalBytes,t),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot)}_fail(t){this._error=t instanceof Error?t:new Error(String(t)),this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=await this._sendCommit(Iy(this._ref,this._data,this._metadata,!0));this._committing=!1,this._settleCommit(r)}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){"result"in t?this._succeed(t.result.metadata):this._fail(t.error);return}n==="paused"&&(this._heldOutcome=t)}}function MA(e,t,n){if(e.fullPath==="")throw DA();return new TA(e,t,n)}class Vr{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=Xc(r),s&&(this.storage=s)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new Vr(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Vr(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function LA(e){return e.replace(/^\/+|\/+$/g,"").replace(/\/+/g,"/")}function UA(e,t,n){let r;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")r=e.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser.");r=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,r.start(),Ui(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function BA(e,t){const n=LA(ma(t,e.__kind==="client-storage"));let r,s,i="pyric-default",o;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,o=e;else{const a=e.fullPath;r=n?a?`${a}/${n}`:n:a,s=e.port,i=e.bucket,o=e.storage}return new Vr(s,i,r,o)}async function FA(e){const t=await pe(e.port,{t:"op",id:L(),method:"storage.listAll",path:e.fullPath}),n=r=>new Vr(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}function xy(e,t){return e.bucket?{...t,bucket:e.bucket}:t}async function _y(e){return await pe(e.port,{t:"op",id:L(),method:"storage.getMetadata",path:e.fullPath})}async function Sy(e){return xy(e,await _y(e))}const qA=4*1024*1024;async function VA(e){const t=await e.sessionToken();if(t===null||t==="")throw new G("unavailable","The page has no session token for the hosted byte route. Reload the page.");return t}function nl(e,t){return e===401||e===403?new G("storage/unauthorized",`The host refused bytes for '${t}' (HTTP ${e}).`):e===404?new G("storage/object-not-found",`Object '${t}' does not exist.`):new G("storage/unknown",`The host's byte route answered HTTP ${e} for '${t}'.`)}async function WA(e,t){for(let n=0;n<2;n++){const r=await _y(t),s=new URL(JC(r.bucket,t.fullPath),e.baseUrl);s.searchParams.set("generation",r.generation);const i=await fetch(s,{headers:{"x-pyric-session-token":await VA(e)}});if(i.status===412)continue;if(!i.ok)throw nl(i.status,t.fullPath);const a=new Uint8Array(await i.arrayBuffer());return{bytes:a,contentType:i.headers.get("content-type")??r.contentType,size:a.byteLength}}throw new G("storage/retry-limit-exceeded",`Object '${t.fullPath}' kept changing while it was read.`)}function xr(e){return e.port.byteRoute}async function ky(e,t){const n=e.port.byteRouteSettled?.();if(n===void 0)return t(xr(e),void 0);const s=Gm(e.port);try{return await kA(n),await t(xr(e),s)}finally{s.release()}}async function Ey(e,t,n,r,s){const i=await pe(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:n,...r!==void 0?{contentType:r}:{},...s!==void 0?{metadata:s}:{}}),o=i.uploadUrl;if(o===void 0)throw new G("storage/unknown","The host began the upload without a byte route URL.");return{uploadId:i.uploadId,url:new URL(o,t.baseUrl).href,size:n,reference:e}}function jy(e,t){if(e.status===200)return t;const r=/^bytes=0-(\d+)$/.exec(e.headers.get("range")??"");return r===null?0:Number(r[1])+1}async function Cy(e,t,n,r){const s=Math.min(n+qA,e.size),i=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes ${n}-${s-1}/${e.size}`},body:t.slice(n,s),signal:r});if(!(i.status===200||i.status===308||i.status===409))throw nl(i.status,e.reference.fullPath);return jy(i,e.size)}async function zA(e,t){const n=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes */${e.size}`},signal:t});if(!(n.status===200||n.status===308))throw nl(n.status,e.reference.fullPath);return jy(n,e.size)}function $a(e,t){const{rollbackToken:n,replacedObject:r,...s}=t,i=xy(e,s);return typeof n=="string"?{metadata:i,rollbackToken:n,replacedObject:r===!0}:{metadata:i}}function Pa(e){return e?{rollback:!0}:{}}async function Ry(e,t=!1){const n=await pe(e.reference.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:e.uploadId,...Pa(t)});return $a(e.reference,n)}async function HA(e,t){await pe(e.port,{t:"op",id:L(),method:"storage.rollbackUpload",rollbackToken:t})}async function Fs(e){try{await pe(e.reference.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:e.uploadId})}catch{}}function Ny(e){return e instanceof Blob?e:new Blob([e])}async function KA(e,t){const n=await GA(e),r=typeof t=="number"&&n.bytes.byteLength>t?n.bytes.subarray(0,Math.max(0,t)):n.bytes,s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return new Blob([s],{type:n.contentType??"application/octet-stream"})}async function GA(e){return ky(e,(t,n)=>t!==void 0?(n?.release(),WA(t,e)):JA(e,n))}async function JA(e,t){try{const n=await pe(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath},t);return{bytes:$d(n.dataB64),contentType:n.contentType,size:n.size}}catch(n){if(n?.code==="payload-too-large"){const r=await Sy(e),s=[];let i=0;for(;i<r.size;){const l=Math.min(Ia,r.size-i),u=await pe(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath,offset:i,length:l,expectedGeneration:r.generation});s.push($d(u.dataB64)),i+=l}const o=new Uint8Array(r.size);let a=0;for(const l of s)o.set(l,a),a+=l.byteLength;return{bytes:o,contentType:r.contentType,size:r.size}}throw n}}async function YA(e,t,n){const r=await Iy(e,t,n,!1);return{ref:e,metadata:r.metadata}}async function Iy(e,t,n,r){return ky(e,(s,i)=>{if(s!==void 0)return i?.release(),XA(e,s,Ny(t),n,r);if(t instanceof Blob)return QA(e,t,n,r,i);const l=t instanceof ArrayBuffer?new Uint8Array(t):t;return Ay(e,l,n?.contentType,n,r,i)})}async function QA(e,t,n,r,s){if(t.size>Fi)throw Zc(t.size,`uploadBytes payload for '${e.fullPath}'`);const o=n?.contentType??(t.type!==""?t.type:void 0),a=s??Gm(e.port);try{const l=new Uint8Array(await t.arrayBuffer());return await Ay(e,l,o,n,r,a)}finally{a.release()}}async function Ay(e,t,n,r,s,i){if(t.byteLength>Fi)throw Zc(t.byteLength,`uploadBytes payload for '${e.fullPath}'`);if(t.byteLength<=Ia){const u=pe(e.port,{t:"op",id:L(),method:"storage.putBytes",path:e.fullPath,dataB64:Od(t),...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{},...Pa(s)},i);return i?.release(),$a(e,await u)}const o=pe(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:t.byteLength,...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{}},i);i?.release();const l=(await o).uploadId;try{let u=0,d=0;for(;u<t.byteLength;){const f=Math.min(u+Ia,t.byteLength),p=t.subarray(u,f);await pe(e.port,{t:"op",id:L(),method:"storage.putPart",uploadId:l,partIndex:d,dataB64:Od(p)}),u=f,d++}const h=await pe(e.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:l,...Pa(s)});return $a(e,h)}catch(u){try{await pe(e.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:l})}catch{}throw u}}async function XA(e,t,n,r,s){if(n.size>Fi)throw Zc(n.size,`uploadBytes payload for '${e.fullPath}'`);const o=r?.contentType??(n.type!==""?n.type:void 0),a=await Ey(e,t,n.size,o,r);try{let l=0;for(;l<a.size;)l=await Cy(a,n,l);return await Ry(a,s)}catch(l){throw await Fs(a),l}}async function Oy(e){await pe(e.port,{t:"op",id:L(),method:"storage.deleteObject",path:e.fullPath})}function ds(e,t){return{instance:t??("instance"in e?e.instance?.name:void 0)}}async function ZA(e,t){return ee(e.port,{t:"op",id:L(),method:"rtdb.adminSnapshot",...ds(e,t)})}async function e0(e,t,n,r){await ee(e.port,{t:"op",id:L(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"},...ds(e,r)})}async function t0(e,t,n,r){await ee(e.port,{t:"op",id:L(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"},...ds(e,r)})}async function n0(e,t,n){await ee(e.port,{t:"op",id:L(),method:"rtdb.remove",path:t,actAs:{mode:"admin"},...ds(e,n)})}function r0(e,t,n,r,s){const i=ln();return!us(e.port,i,{port:e.port,next:a=>n(a?.value??null),error:r},Qc({t:"sub",subId:i,target:{service:"rtdb",...ds(e,s),path:bI(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>nt(e.port,i)}const s0="/__pyric/diagnostics";function i0(e){const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))throw new Error("Unsupported diagnostic URL scheme.");const r=t.pathname==="/__pyric/sandbox"?t.pathname:"";return`${t.origin}${r}`}function o0(){if(globalThis.__pyricDiagnostics)return globalThis.__pyricDiagnostics;if(typeof location>"u"||!(location.protocol==="http:"||location.protocol==="https:"))return;const t={version:1,clientId:`browser-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,sequence:0,realm:typeof document>"u"?"service-worker":"page",pageOrigin:location.origin,events:[]};let n,r=!1;const s=()=>({...t,events:t.events.map(a=>({...a}))}),i=()=>{n!==void 0||r||(n=setTimeout(()=>{n=void 0,o.flush()},100))},o={getSnapshot:s,record(a){const l=a.endpoint?i0(a.endpoint):void 0;t.sequence+=1,t.events.push({...a,endpoint:l,at:Date.now()}),t.events=t.events.slice(-32),i()},async flush(){if(r)return;r=!0;const a=t.sequence,l=new AbortController,u=setTimeout(()=>l.abort(),2e3);try{await fetch(new URL(s0,location.href),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s()),signal:l.signal,credentials:"same-origin",keepalive:!0})}catch{}finally{clearTimeout(u),r=!1,t.sequence>a&&i()}}};return globalThis.__pyricDiagnostics=o,globalThis.addEventListener("online",i),globalThis.addEventListener("pagehide",()=>{clearTimeout(n),n=void 0,o.flush()}),o}function a0(e){try{o0()?.record(e)}catch{}}function c0(e){const t=typeof e.bridgeVersion=="string"&&typeof e.peerConnected=="boolean"&&typeof e.clientSessionId=="string",r=[e.projectKey,e.serveVersion,e.sessionId,e.resumeToken,e.hostInstanceId].every(a=>a===void 0||typeof a=="string"),s=e.capabilities,i=s===void 0||Array.isArray(s)&&s.every(a=>typeof a=="string"),o=e.sandboxConnected===void 0||typeof e.sandboxConnected=="boolean";return t&&r&&i&&o}const Wr="Bridge response exceeds the 12 MiB encoded frame limit.",Da=4009,_r={code:"resource-exhausted",message:Wr},Ta=new TextEncoder,l0=["value","values","priority"];function u0(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}function $y(e,t){if(e===void 0||typeof e=="number"&&!Number.isFinite(e))return{path:t,found:String(e)};if(!(typeof e!="object"||e===null))for(const[s,i]of Object.entries(e)){const o=$y(i,u0(t,s));if(o!==void 0)return o}}function d0(e){if(e.type!=="worker-message")return;const n=e.message;if(!(n.t==="op"&&n.method.startsWith("rtdb.")))return;const s={...n},i=typeof s.path=="string"?s.path:"/";for(const o of l0){if(!Object.hasOwn(s,o))continue;const l=$y(s[o],i);if(l!==void 0)throw new Error(`RTDB ${n.method} ${o} at ${l.path} holds ${l.found}, which a JSON frame cannot carry. The write was not sent.`)}}function Py(e){d0(e);const t=JSON.stringify(e);if(Ta.encode(t).byteLength<=Ur)return t;const r=h0(e),s=JSON.stringify(r);return Ta.encode(s).byteLength>Ur?f0(r):s}function f0(e){if(e.type!=="worker-message-result")return;const n=e.message;if(n.t!=="event")return;const s=n.events[0],i=n.events.at(-1);if(s===void 0||i===void 0)return;const a={...e,message:{...n,events:[{kind:"observation_gap",id:`observation-gap:${s.id}:${i.id}`,at:s.at,reason:"frame-limit",omittedCount:n.events.length,firstEventId:s.id,lastEventId:i.id}]}},l=JSON.stringify(a);if(Ta.encode(l).byteLength<=Ur)return l}function h0(e){switch(e.type){case"tool-result":return{type:"tool-result",id:e.id,ok:!1,error:_r};case"worker-message-result":return{...e,message:p0(e.message)};case"worker-res":return{type:"worker-res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:_r};case"worker-snap":return{...e,value:{__error:_r}};default:return e}}function p0(e){switch(e.t){case"res":return{t:"res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:_r};case"snap":return{...e,value:{__error:_r}};case"event":{const t=e.events.map(n=>{if(n.kind==="snapshot_delivery"){const s={...n};return delete s.sample,s}return n});return{...e,events:t}}default:return e}}const qd={"rtdb.set":"resend","rtdb.setPriority":"resend","rtdb.setWithPriority":"resend","rtdb.update":"resend","rtdb.remove":"resend","rtdb.push":"resend","rtdb.get":"resend","rtdb.onDisconnectSet":"forget","rtdb.onDisconnectUpdate":"forget","rtdb.onDisconnectRemove":"forget","rtdb.onDisconnectCancel":"forget","rtdb.transactionCommit":"disconnect"};function m0(e){return Object.hasOwn(qd,e)?qd[e]:"fail"}function y0(e){return e.t==="op"?m0(e.method):"fail"}function g0(e,t,n,r){const s=[];for(const{id:i,message:o}of UN(e,a=>r(a)&&!Ym(e,a))){const a=y0(o);a==="resend"?s.push(i):a==="forget"?FN(i):a==="disconnect"?jd(i,new Error("disconnect")):jd(i,n)}t.holdAgain(BN(s))}function b0(e){const t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.origin}const Eo="The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying.",jo="The hosted sandbox connection is closed.",w0=new TextEncoder;function v0(e,t){const n=`socket-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;let r=e.url;const s=(D,z)=>{a0({phase:D,connectionId:n,endpoint:r,code:z})},i=new Set;let o="connecting",a,l,u=e.initialHostInstanceId,d=!1,h,f=!1,p=!1,m=0,g,b,w,x,v=0;const _=e.realm;let S=!1,k=()=>{};const R=new Promise(D=>{k=D}),O=()=>{S=!0,k()},P=D=>(_?.releaseTimer(D),D),A=D=>{_?.traffic(E,D)},E=Object.assign({},{onmessage:null,postMessage(D){if(o==="closed")throw new G("unavailable",jo);D.t==="appConfig"&&(h=D),A({sent:D});const Y=o==="attached";if(!Y&&D.t==="disconnect"){j.drop(),M({t:"res",id:D.id,ok:!0,value:void 0});return}if(!Y){if((D.t==="op"||D.t==="tool")&&!Je.has(D.id))return;N({type:"worker-message",message:D}),j.hold(D);return}const we=a;if(we===void 0)throw new G("unavailable",jo);I(we,{type:"worker-message",message:D})},start(){},withdrawSubscription(D){return j.forgetSubscription(D)},byteRouteSettled(){return S?void 0:R},observeConnection(D){return i.add(D),queueMicrotask(()=>{i.has(D)&&D(o==="attached")}),()=>{i.delete(D)}},close(){$(new G("unavailable",jo))}}),j=EA(E);function $(D){if(o==="closed")return;o="closed",C(),i.clear(),Xm(E),j.fail(D),qr(E,D),kI(E,D),l=void 0,g=void 0,u=void 0,d=!1,h=void 0,E.restoreAuth=void 0,E.messagingVisibility=void 0,clearTimeout(b),clearTimeout(w),clearTimeout(x);const ae=a;a=void 0;const Y=ae?.readyState===WebSocket.OPEN;try{Y&&I(ae,{type:"worker-message",message:{t:"disconnect",id:L()}})}catch{}ae?.close(),E.onmessage=null,O(),A({closed:!0})}function C(){s(o),e.onConnection?.(o);const D=o==="attached";for(const z of[...i])z(D)}function N(D){const z=Py(D);if(z===void 0)throw new G("resource-exhausted","Bridge request exceeds the 12 MiB encoded frame limit.");return z}function I(D,z){D.send(N(z))}function M(D){E.onmessage?.(new MessageEvent("message",{data:D})),A({})}function T(D){if(o==="closed")return;const ae=new G("unavailable",D);$(ae),e.onError?.(ae)}function F(D){return a===D&&o!=="closed"}function U(D){if(!F(D))return;clearTimeout(b),clearTimeout(x),g??=performance.now(),o="interrupted",a=void 0,C();const ae=new G("unavailable",Eo);g0(E,j,ae,Y=>!j.holdsRequest(Y)&&!Ym(E,Y)),VN(E,ae,Y=>j.holdsSubscription({t:"unsub",subId:Y})),A({}),D.close(),V()}function V(){const D=Math.min(5e3,250*2**m);m+=1;const z=Math.random()*Math.min(250,D/10);w=P(setTimeout(mn,Math.min(5e3,D+z)))}function B(){o!=="closed"&&(o="interrupted",C(),V())}function _e(D){const z=Sd-(performance.now()-v),ae=Math.max(0,Math.min(Fm,z));x=P(setTimeout(()=>{if(!F(D))return;if(performance.now()-v>=Sd){U(D);return}try{I(D,{type:"ping",id:L()})}catch{U(D);return}_e(D)},ae))}async function ye(D,z){const ae=z||m>0,Y=be=>{if(!F(D))throw new G("unavailable",Eo);I(D,{type:"worker-message",message:be})},ge=be=>{j.holdsSubscription(be)||Y(be)};if(f){o="restoring",s(o),e.onConnection?.(o);const be=h;if(be!==void 0&&Y(d?{...be,fromPriorHost:!0}:be),await E.restoreAuth?.(Jn=>Bi(E,Jn,Y)),!F(D))return;LN(E,ge),f=!1}clearTimeout(b),o="attached",p=!0,m=0,g=void 0,v=performance.now(),clearTimeout(x),_e(D),z&&(Y({t:"clock-subscribe"}),MN(E,ge)),ae&&TN(E,ge),j.flush(Y),C()}async function Rt(){const D=e.currentHostInstanceId;if(!(p&&D!==void 0))return u;try{return await D()??u}catch{return u}}function mn(){if(o==="closed")return;o="connecting",s("connecting");const z=p?"interrupted":"connecting";e.onConnection?.(z),g!==void 0&&performance.now()-g>=wN&&(l=void 0);const Y=l===void 0,ge=e.currentUrl;if(!(p&&ge!==void 0)){Gn(Y);return}ge().then(we=>{o!=="closed"&&(r=we,Gn(Y))},B)}function Gn(D){let z;try{z=_?_.createSocket(r):new WebSocket(r)}catch(Y){throw s("socket-error"),Y}a=z,b=P(setTimeout(()=>{if(!F(z))return;s("timeout"),p||e.retryInitialConnection===!0?U(z):T("Timed out connecting to the hosted sandbox.")},5e3)),z.addEventListener("error",()=>{F(z)&&s("socket-error")});let ae=u;z.addEventListener("open",()=>{F(z)&&(s("transport-open"),Rt().then(ge=>{if(!F(z))return;ae=ge,ge!==u&&(l=void 0),I(z,{type:"attach",protocol:1,transport:"worker-port",resumeToken:l,hostInstanceId:ge,clientInfo:{platform:_?.platform??"browser"}})}))}),z.addEventListener("message",Y=>{if(!F(z))return;if(w0.encode(Y.data).byteLength>Ur){z.close(Da,Wr),T(Wr);return}let we;try{we=JSON.parse(Y.data)}catch{T("The hosted sandbox sent invalid JSON. Requests already sent may have completed; check state before retrying.");return}const H=we;if(!qm(H)){T("The hosted sandbox sent an invalid message. Requests already sent may have completed; check state before retrying.");return}switch(v=performance.now(),H.type){case"attach-ack":{if(H.protocol!==1){T("The hosted sandbox uses an unsupported bridge protocol. Expected version 1.");return}const Yn=H.capabilities;if(!(Array.isArray(Yn)&&Yn.every(Il=>typeof Il=="string")&&Yn.includes(bN))){T("The selected host does not support browser worker ports. Upgrade @pyric/cli, restart with --hosted, and reload this page.");return}const aw=Yn.includes(gN),Nl=e.sessionToken;if(aw&&Nl!==void 0?E.byteRoute={baseUrl:b0(r),sessionToken:Nl}:delete E.byteRoute,O(),_?.attached?.(H),H.projectKey!==e.projectKey){T("The selected hosted sandbox belongs to a different project.");return}if(!c0(H)){T("The hosted sandbox sent a malformed attachment acknowledgment.");return}const hs=p,Zi=typeof H.hostInstanceId=="string"&&H.hostInstanceId.length>0,eo=hs&&u!==void 0&&Zi&&H.hostInstanceId!==u,cw=Zi&&H.hostInstanceId===ae;eo&&!cw&&(d=!0);const lw=hs&&!D,uw=H.resumeToken!==l;if(lw&&uw&&!eo){T("The hosted session could not be resumed.");return}l=typeof H.resumeToken=="string"&&H.resumeToken.length>0?H.resumeToken:void 0,u=Zi?H.hostInstanceId:void 0,hs&&(eo||D)&&(f=!0),ye(z,hs).catch(()=>{F(z)&&T("Could not restore the hosted app session.")});return}case"worker-message-result":{const at=H.message;zm(at)&&at.t==="res"&&Wm(at)&&at.ok===!1&&(at.error.code==="committed-but-not-durable"||at.error.code==="persistence-unhealthy")&&e.onError?.(new G(at.error.code,at.error.message)),M(at);return}}}),z.addEventListener("close",Y=>{if(!F(z))return;s("socket-close",Y.code),clearTimeout(b),p&&Y.code===vN&&(l=void 0),(p||e.retryInitialConnection===!0)&&Y.code!==1008?U(z):T(Eo)})}const yn={__kind:"client-db",port:E};return Ui(E),mn(),yn}function x0(){if(!(typeof document<"u"))return null;const n=document.querySelector('meta[name="pyric-sandbox-host"]');if(!(n?.getAttribute("content")==="node"))return null;const i=n.getAttribute("data-project-key");if(!(i!==null&&i.length>0))throw new Error("The hosted sandbox has no project identity. Restart the host and reload Studio.");return{url:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/__pyric/sandbox`,projectKey:i}}function _0(e){const t=new Set;let n={mode:"hosted",servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:"Connecting to the hosted sandbox."};function r(o){n={...n,error:o};for(const a of t)a()}return{db:v0({...e,sessionToken:()=>Mi(location.origin),onConnection(o){switch(o){case"attached":r(null);return;case"connecting":r("Connecting to the hosted sandbox.");return;case"restoring":r("Restoring the hosted session.");return;case"interrupted":r("Hosted connection lost; reconnecting.");return;case"closed":r("Hosted connection closed. Repair the host and reload Studio.");return}},onError:o=>r(o.message)}),runtime:{getSnapshot:()=>n,subscribe(o){return t.add(o),()=>{t.delete(o)}},async update(){throw new Error("Restart the hosted sandbox and reload Studio to update it.")},dispose(){t.clear()}}}}function S0(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=l=>{n={...n,...l};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let o=null;const a=()=>i?(o??=XR({targetEpoch:i,retire:()=>e.retire?e.retire(i):YN(e.db,i),subscribeReload:e.subscribeReload??QN,preflight:e.preflight??(()=>QR(s)),commitGeneration:e.remember??(l=>YR(l,s)),onPreparationError:l=>r({updating:!1,error:l instanceof Error?l.message:String(l)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),o):null;return(e.readVersion??(()=>aI(e.db)))().then(l=>r({runningEpoch:l,updateAvailable:!!(i&&l!=="dev"&&l!==i)})).catch(l=>r({error:l instanceof Error?l.message:String(l)})),{getSnapshot:()=>n,subscribe(l){return t.add(l),a(),()=>{t.delete(l),t.size===0&&(o?.dispose(),o=null)}},async update(){const l=a();if(!l||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await l.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),o?.dispose(),o=null}}}function k0(e={}){const t=Lm(e.document??(typeof document>"u"?void 0:document));let n=e.storage;if(!n)try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}return{url:e.workerUrl??t.worker.url,name:JR(t.worker.servedEpoch,n)}}const E0="/__pyric/sdk/worker.js";function j0(e){const t=new Vh(Wh);let n=!1;const r=new Set;let s=null;function i(){s||(s=rA(e,o=>{const a=!n;n=!0,a&&t.clear();for(const l of o)Om(l)&&t.clear(),t.append(l);for(const l of o)for(const u of r)u(l)}))}return{history:()=>t.snapshot(),subscribe:o=>(r.add(o),i(),()=>{r.delete(o),r.size===0&&s&&(s(),s=null,n=!1,t.clear())})}}function Vd(e){let t=!1,n=null;const r=()=>{t=!0;const s=(async()=>e())(),i=()=>{t=!1;const o=n;n=null,o&&r().then(o.resolve,o.reject)};return s.then(i,i),s};return()=>{if(!t)return r();if(!n){let s,i;n={promise:new Promise((a,l)=>{s=a,i=l}),resolve:s,reject:i}}return n.promise}}function C0(e=E0){const t=x0(),n=t!==null;if(!n&&typeof SharedWorker>"u")return null;GN("studio");const s=n?_0(t):null;let i;if(s!==null)i=s.db;else try{const m=k0({workerUrl:e});i=oI(m.url,m.name)}catch{return null}let a;try{a=typeof localStorage<"u"?localStorage:void 0}catch{a=void 0}const l=typeof document<"u",u=s?.runtime??S0({db:i,servedEpoch:Lm(l?document:void 0).worker.servedEpoch,storage:a});Rd({mode:"admin"});const d=uA({db:i,kind:"studio"}),h=j0(i),f=xA(i);let p=!1;return{db:i,runtime:u,dispose:async()=>{p||(p=!0,d.stop(),u.dispose(),await SI(i).catch(()=>{}))},presenceClientId:d.clientId,subscribePresence:m=>dA(i,m),instanceId:()=>cI(i),exportState:()=>lI(i),importState:m=>uI(i,m),saveState:m=>dI(i,m),listStates:()=>fI(i),restoreState:m=>hI(i,m),deleteState:m=>pI(i,m),feed:h,setLens:m=>Rd(m),getLens:()=>KN(),listRootCollections:Vd(()=>HI(i)),listSubcollections:m=>KI(i,m),listDocuments:async m=>(await eA(i,m)).map(({path:g,phantom:b})=>({path:g,phantom:b})),readRtdbState:()=>ZA(i),setRtdbValue:(m,g)=>e0(i,m,g),updateRtdbValue:(m,g)=>t0(i,m,g),deleteRtdbValue:m=>n0(i,m),subscribeRtdbValue:(m,g,b)=>r0(i,m,g,b),firestoreApi:{collection:OI,doc:AI,getDoc:qI,getDocs:WI,onSnapshot:YI,setDoc:QI,deleteDoc:XI,addDoc:ZI,query:FI,limit:UI,startAfter:BI},auth:f,authApi:{listUsers:Vd(()=>fA(f)),subscribeUsers:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.service==="auth"&&g()}),createUser:(m,g)=>hA(f,g),updateUser:(m,g,b)=>pA(f,g,b),deleteUser:(m,g)=>mA(f,g),clearUsers:()=>yA(f),getAuthProviderConfig:()=>gA(f),setAuthProviderConfig:(m,g,b)=>bA(f,g,b),subscribeAuthProviderConfig:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.op==="provider_config_update"&&g()})},storage:UA(i),storageApi:{ref:BA,listAll:FA,getMetadata:Sy,getBlob:KA,uploadBytes:YA,uploadBytesResumable:MA,deleteObject:Oy},getSnapshot:()=>iA(i),resetAll:()=>oA(i)}}function Dy(e,t,n,r){const s={uid:e};n!==void 0&&(s.token={...n}),t!==void 0&&(s.tenant=t);const i=Ei(s);if(i===null)throw new Error("projectIdentity requires a uid");const o={uid:i.uid,token:i.token??{}};return i.tenant!==void 0&&(o.tenant=i.tenant),o}const R0={transport:"in-process",order:80,tools:{auth_impersonate:"write",auth_reset:"write",auth_whoami:"read",auth_sessions:"read"}},N0={transport:"forwarded",order:70,tools:{auth_create_user:"write",auth_import_users:"write",auth_get_user:"read",auth_list_users:"read",auth_update_user:"write",auth_delete_user:"write",auth_set_claims:"write",auth_custom_token:"read"}},I0={transport:"in-process",order:90,tools:{sandbox_save_capture:"write",sandbox_list_captures:"read",sandbox_open_capture:"read",sandbox_rename_capture:"write",sandbox_delete_capture:"write"}},A0={transport:"in-process",order:60,tools:{pyric_can_i_use:"read"}},O0={transport:"forwarded",order:20,tools:{firestore_get_document:"read",firestore_list_documents:"read",firestore_create_document:"write",firestore_add_document:"write",firestore_update_document:"write",firestore_delete_document:"write",firestore_batch_write:"write",firestore_query_where:"read"}},$0={transport:"forwarded",order:30,tools:{sandbox_inspect:"read"}},P0={transport:"in-process",order:50,tools:{firestore_simulate_rules:"read",firestore_rules_stdlib_list:"read",firestore_rules_stdlib_get:"read",firestore_lint_rules:"read",firestore_resolve_modules:"read",rules_stdlib_list:"read",rules_stdlib_get:"read",rules_resolve_modules:"read"}},D0={transport:"forwarded",order:10,tools:{firestore_simulator_create:"write",firestore_simulator_execute:"write",firestore_simulator_read:"read",firestore_simulator_batch:"write",firestore_create_with_auto_id:"write",firestore_simulator_undo:"write",firestore_simulator_redo:"write",firestore_simulator_events:"read",firestore_simulator_transaction:"write"}},T0={transport:"forwarded",order:100,tools:{messaging_deliveries:"read"}},M0={transport:"forwarded",order:40,tools:{rtdb_simulate_access:"read",rtdb_crawl_structure:"read"}},L0=[{key:"auth-identity",...R0},{key:"auth-users",...N0},{key:"captures",...I0},{key:"conformance",...A0},{key:"firestore-data",...O0},{key:"firestore-inspect",...$0},{key:"firestore-rules",...P0},{key:"firestore-simulator",...D0},{key:"messaging-inspection",...T0},{key:"rtdb-inspection",...M0}];function Co(e,t){const n=new Set;for(const r of t){if(n.has(r))throw new Error(`duplicate tool family ${e} '${r}'`);n.add(r)}}function U0(e){return Co("key",e.map(t=>t.key)),Co("order",e.map(t=>t.order)),Co("tool name",e.flatMap(t=>Object.keys(t.tools))),[...e].sort((t,n)=>t.order-n.order)}const B0=U0(L0);function Ty(e){return B0.filter(t=>t.transport===e)}function F0(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,o)=>i!==s[o]))throw new Error(`${e} drifted from the default MCP contract
133
+ expected: ${n.join(", ")}
134
+ actual: ${t.join(", ")}`)}function q0(e){const t=e.detail??{};return{messageId:String(t.messageId),recipientId:String(t.recipientId??"sandbox-default"),receipt:"unconfirmed",acknowledgments:[],route:t.route,handled:t.handled===!0,at:e.at,payload:t.payload}}function V0(e,t){const n=e.filter(a=>a.kind==="service_mutation"&&a.service==="messaging"),r=new Map,s=(a,l)=>JSON.stringify([a,l]);for(const a of n){if(a.op!=="delivery_acknowledged")continue;const u=a.detail??{},d=s(u.messageId,u.recipientId),h=r.get(d)??[];h.push({observerId:String(u.observerId),stage:u.stage,at:a.at}),r.set(d,h)}const i=n.filter(a=>a.op==="message_delivered").map(a=>{const l=q0(a);l.acknowledgments=r.get(s(l.messageId,l.recipientId))??[];const u=l.acknowledgments.some(d=>d.stage==="received");return l.receipt=u?"received":"unconfirmed",l});return t===void 0?i:i.filter(a=>a.at>=t)}const Wd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",W0=142,zd="APA91b",Hd=22;function Kd(e){const t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let r=0;r<e;r++)n+=Wd[t[r]%Wd.length];return n}function z0(){const e=Kd(Hd),t=W0-Hd-1-zd.length;return`${e}:${zd}${Kd(t)}`}const H0="pyric-sandbox",K0="999999999999",sr="sandbox-default",G0=null;class J0{projectId;senderId;sandbox;registrations=new Map;tokenRecords=new Map;subscriptions=new Map;clients=new Map;foregroundHandlers=new Map;backgroundHandlers=new Map;numericIdCounter=0;changeListeners=new Set;constructor(t={}){this.projectId=t.projectId??H0,this.senderId=t.senderId??K0,this.sandbox=t.sandbox}snapshot(){return{version:1,tokens:[...this.tokenRecords].map(([t,n])=>[t,{...n}]),topics:[...this.subscriptions].map(([t,n])=>[t,[...n]])}}restore(t){if(!fE(t))throw new Error("Invalid Messaging persistence snapshot.");this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear();for(const[n,r]of t.tokens)this.tokenRecords.set(n,{...r}),r.state==="active"&&this.registrations.set(r.registrationId,n);for(const[n,r]of t.topics)this.subscriptions.set(n,new Set(r))}reset(){this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear(),this.changed()}onChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}changed(){for(const t of this.changeListeners)t()}getTokenFor(t,n=sr){const r=this.registrations.get(t);if(r!==void 0)return r;const s=z0();return this.registrations.set(t,s),this.tokenRecords.set(s,{registrationId:t,recipientId:n,state:"active"}),this.changed(),this.emit("token_minted",{path:s,detail:{registrationId:t}}),s}deleteTokenFor(t){const n=this.registrations.get(t);if(n===void 0)return!0;this.registrations.delete(t);const r=this.tokenRecords.get(n);return r!==void 0&&(r.state="unregistered"),this.changed(),this.emit("token_deleted",{path:n,detail:{registrationId:t}}),!0}tokenState(t){return this.tokenRecords.get(t)?.state??"unknown"}subscribeToTopic(t,n){return this.mutateSubscriptions(t,n,"subscribe")}unsubscribeFromTopic(t,n){return this.mutateSubscriptions(t,n,"unsubscribe")}mutateSubscriptions(t,n,r){if(!Ai(n))throw new Xe(qp());const s=Tc(n),i=this.subscriptions.get(s)??new Set;this.subscriptions.set(s,i);const o={successCount:0,failureCount:0,errors:[]};return t.forEach((a,l)=>{if(!Ii.test(a)){o.failureCount++,o.errors.push({index:l,reason:"invalid-token"});return}if(this.tokenState(a)==="unregistered"){o.failureCount++,o.errors.push({index:l,reason:"unregistered-token"});return}r==="subscribe"?i.add(a):i.delete(a),o.successCount++}),this.changed(),this.emit("subscription_changed",{path:s,detail:{action:r,tokenCount:t.length,successCount:o.successCount,failureCount:o.failureCount}}),o}topicsOf(t){const n=new Set;for(const[r,s]of this.subscriptions)s.has(t)&&n.add(r);return n}tokens(){const t=new Set(this.tokenRecords.keys());for(const n of this.subscriptions.values())for(const r of n)t.add(r);return[...t].sort().map(n=>({token:n,state:this.tokenState(n),topics:[...this.topicsOf(n)].sort()}))}send(t,n={}){const r=n.validateOnly===!0;let s;try{if(s=cE(t),s.kind==="token"&&this.tokenState(s.token)!=="active")throw new Xe(nE())}catch(a){throw a instanceof Xe&&this.emit("message_rejected",{detail:{status:a.envelope.status,errorStatus:a.envelope.error.status,errorCode:a.errorCode,message:a.envelope.error.message,validateOnly:r}}),a}const i=s.kind==="token"?crypto.randomUUID():this.mintNumericId(),o={name:`projects/${this.projectId}/messages/${i}`,messageId:i,target:s,validateOnly:r};if(this.emit("message_accepted",{path:Y0(s),detail:{target:s.kind,name:o.name,messageId:i,validateOnly:r}}),!r){const a=this.toPayload(t,i);for(const l of this.matchingRecipients(s))this.route(a,l)}return o}mintNumericId(){return this.numericIdCounter=(this.numericIdCounter+1)%1e6,`${Date.now()}${String(this.numericIdCounter).padStart(6,"0")}`}matchingRecipients(t){const n=new Set;for(const[r,s]of this.tokenRecords){if(!(s.state==="active"))continue;let o;switch(t.kind){case"token":o=r===t.token;break;case"topic":o=this.subscriptions.get(t.topic)?.has(r)===!0;break;case"condition":o=Q0(t.condition,this.topicsOf(r));break}o&&n.add(s.recipientId)}return n}toPayload(t,n){const r={from:this.senderId,messageId:n};if(t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0){const{title:s,body:i,imageUrl:o}=t.notification;r.notification={...s!==void 0?{title:s}:{},...i!==void 0?{body:i}:{},...o!==void 0?{image:o}:{}}}return r}setClientVisibility(t,n,r=sr){this.clients.set(t,{state:n,recipientId:r})}removeClient(t){this.clients.delete(t)}onForegroundMessage(t,n=sr){return this.foregroundHandlers.set(t,n),()=>this.foregroundHandlers.delete(t)}onBackgroundMessage(t,n=sr){return this.backgroundHandlers.set(t,n),()=>this.backgroundHandlers.delete(t)}deliver(t,n=sr){const r={from:t.from??this.senderId,messageId:t.messageId??crypto.randomUUID()};return t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0&&(r.notification={...t.notification}),this.route(r,n)}route(t,n){let r=!1;for(const a of this.clients.values())if(a.recipientId===n&&a.state==="visible"){r=!0;break}const s=r?"foreground":"background",i=s==="foreground"?this.foregroundHandlers:this.backgroundHandlers;this.emit("delivery_routed",{detail:{route:s,recipientId:n,visibleClient:r,messageId:t.messageId}});let o=0;for(const[a,l]of[...i])if(l===n){o++;try{a(structuredClone(t))}catch{}}return this.emit("message_delivered",{detail:{recipientId:n,route:s,handlerCount:o,handled:o>0,messageId:t.messageId,payload:structuredClone(t)}}),{route:s,handlerCount:o,payload:t}}acknowledge(t,n,r,s){this.emit("delivery_acknowledged",{detail:{messageId:t,recipientId:n,observerId:r,stage:s}})}deliveries(t){return V0(this.sandbox?.history()??[],t)}emit(t,n){if(this.sandbox!==void 0)try{dt(this.sandbox,Ln({at:De(this.sandbox).now(),service:"messaging",op:t,auth:G0,...n}),{service:"messaging"})}catch{}}}function Y0(e){return e.kind==="token"?e.token:e.kind==="topic"?e.topic:e.condition}function Q0(e,t){const n=e;let r=0;function s(){for(;r<n.length&&/\s/.test(n[r]);)r++}function i(l){return s(),n.startsWith(l,r)?(r+=l.length,!0):!1}function o(){if(s(),i("!"))return!o();if(i("(")){const d=a();return i(")"),d}s(),r++;const l=r;for(;r<n.length&&n[r]!=="'";)r++;const u=n.slice(l,r);return r++,i("in"),i("topics"),t.has(u)}function a(){let l=o();for(;;){if(s(),i("&&")){const u=o();l=l&&u;continue}if(i("||")){const u=o();l=l||u;continue}return l}}return a()}const Gd=new WeakMap;function X0(e,t){const n=Gd.get(e);if(n!==void 0)return n;const r=new J0({...t,sandbox:e});return Gd.set(e,r),e.registerPersistableService("messaging",{snapshot:()=>r.snapshot(),restore:s=>r.restore(s),reset:()=>r.reset(),subscribe:s=>r.onChange(s)}),r}function Z0(e){return[{name:"messaging_deliveries",description:"Inspect message routing and browser-reported receipt, callback and native display outcomes. handled only means a broker handler ran; display-accepted is not proof of OS visibility. Missing receipt is unconfirmed.",parameters:{type:"object",properties:{}},async execute(){const t=await e(),n=X0(t).deliveries();return{ok:!0,summary:`${n.length} deliveries`,data:{deliveries:n}}}}]}class Ma extends Error{issues;constructor(t,n){super(t),this.name="RulesCompileError",this.issues=n}}function eO(e){const t=e.severity==="critical"||e.severity==="high"?"error":e.severity==="medium"?"warning":"info";return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}function tO(e){return{...eO(e),rule:e.rule,fix:e.fix}}const nO=new Set(["PARSE_ERROR","COMPILE_ERROR"]);function Jd(e,t){const n=t==="warning"?"lint":nO.has(e.code)?"parse":"validate",r={code:e.code,severity:t,message:e.message,path:e.path,origin:n};return e.rule!=="ruleset"&&(r.rule=e.rule),r}const rO="/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/",sO=new Set(["d","D","w","W","s","S"]),iO=new Set(["*","+","?","}"]);function oO(e){const t=hp(e);if(t!==null)return`RTDB refuses it at deploy (${t})`;let n=!1,r=0;for(let s=0;s<e.length;s++){const i=e[s],o=e[s+1];if(i==="\\"&&o!==void 0){const a=lO(o);if(a!==null)return a;s++}else if(n)n=i!=="]";else if(i==="["){if(cO(e,s+1))return"RTDB reads a ] right after [ or [^ as a member of the set";n=!0}else{if(i==="("&&o==="?")return"RTDB reads (? as a literal ?, so lookarounds and (?: groups never match as in JavaScript";if(iO.has(i)&&o==="?")return"RTDB has no lazy quantifier and reads +? as an optional +";if(i==="(")r++;else if(i===")")r--;else{if(i==="|"&&aO(e,s))return"RTDB reads the | of an empty alternative, as in (|a) or a||b, as a literal |";if(i==="|"&&r===0)return"RTDB applies ^, $ and the implied .* to the first and last alternatives only; wrap the alternation in a group"}}}return null}function aO(e,t){const n=e[t-1],r=e[t+1];return n==="("&&e[t-2]!=="\\"||r==="|"||r===")"}function cO(e,t){const n=e[t]==="^"?t+1:t;return e[n]==="]"}function lO(e){return!/^[A-Za-z0-9]$/.test(e)||sO.has(e)?null:e==="b"||e==="B"?`RTDB reads \\${e} as the letter ${e}, not a word boundary`:/^[1-9]$/.test(e)?`RTDB reads \\${e} as the digit ${e}, not a backreference`:`RTDB reads the escape \\${e} as the letter ${e}`}function My(e,t){if(!(e instanceof Dl)){const l=e?.constructor?.name??typeof e;throw new Error(`Unsupported Zod schema for RTDB rules: expected ZodObject, got ${l}`)}const n=e._def;if(n.catchall&&!(n.catchall instanceof _v))throw new Error("Unsupported Zod object catchall for RTDB rules");const r=e.shape;if(t){for(const l of Object.keys(t))if(!(l in r))throw new Error(`fieldConstraints: field "${l}" is not in schema.`)}const s=[],i={};for(const[l,u]of Object.entries(r)){Zh("schemaRules",l);const d=u,h=d instanceof Sv,f=h?d.unwrap():d;h||s.push(l);const p=t?.[l];if(f instanceof Dl){const m=My(f);let g=m.validate;p&&p.length>0&&(g=Nn(m.validate,...p)),i[l]={validate:g,children:m.children}}else{const m=Ly(f,l);p&&p.length>0?i[l]={validate:Nn(m,...p)}:i[l]={validate:m}}}n?.unknownKeys==="strict"&&(i.$other={validate:oe("false")});const o=[k_()];for(const l of s)o.push(E_(l));return{validate:Nn(...o),children:i}}function uO(e,t){const n=[oe("newData.isString()")];for(const r of e._def.checks)if(r.kind==="min")n.push(oe(`newData.val().length >= ${Ge(r.value)}`));else if(r.kind==="max")n.push(oe(`newData.val().length <= ${Ge(r.value)}`));else if(r.kind==="length")n.push(oe(`newData.val().length == ${Ge(r.value)}`));else if(r.kind==="regex"){const s=r.regex;if(!_c(s.flags))throw new Error(`Unsupported Zod regex flags "${s.flags}" on field "${t}"; RTDB rules only support the "i" flag`);if(/[\r\n]/.test(s.source))throw new Error(`Unsupported Zod regex with newline on field "${t}"`);const i=oO(s.source);if(i!==null)throw new Error(`Unsupported Zod regex on field "${t}": ${i}`);n.push(oe(`newData.val().matches(/${s.source}/${s.flags})`))}else if(r.kind==="email")n.push(oe(`newData.val().matches(${rO})`));else if(r.kind==="startsWith")n.push(oe(`newData.val().beginsWith(${Ge(r.value)})`));else if(r.kind==="endsWith")n.push(oe(`newData.val().endsWith(${Ge(r.value)})`));else if(r.kind==="includes")n.push(oe(`newData.val().contains(${Ge(r.value)})`));else throw new Error(`Unsupported Zod string check "${String(r.kind)}" for RTDB rules on field "${t}"`);return Nn(...n)}function dO(e,t){const n=[oe("newData.isNumber()")];for(const r of e._def.checks)if(r.kind==="min"){const s=r.inclusive===!1?">":">=";n.push(oe(`newData.val() ${s} ${Ge(r.value)}`))}else if(r.kind==="max"){const s=r.inclusive===!1?"<":"<=";n.push(oe(`newData.val() ${s} ${Ge(r.value)}`))}else if(r.kind==="int")n.push(oe("newData.val() % 1 == 0"));else if(r.kind==="multipleOf")n.push(oe(`newData.val() % ${Ge(r.value)} == 0`));else throw new Error(`Unsupported Zod number check "${String(r.kind)}" for RTDB rules on field "${t}"`);return Nn(...n)}function Ly(e,t){if(e instanceof kv)return uO(e,t);if(e instanceof Ev)return dO(e,t);if(e instanceof jv)return oe("newData.isBoolean()");if(e instanceof Cv){const n=e.options;return Wl(...n.map(r=>oe(`newData.val() == ${Ge(r)}`)))}if(e instanceof Rv){const n=e.value;return oe(`newData.val() == ${Ge(n)}`)}if(e instanceof Nv){const n=e._def.options;return Wl(...n.map(r=>Ly(r,t)))}throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function fO(e){let t;if(typeof e=="function"){const s=[];e({path:(i,o)=>s.push([i,o])}),t=s}else t=Object.entries(e);const n=rl(t);vO(n),n.sort((s,i)=>{const o=Yd(s[0]),a=Yd(i[0]);return o-a||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&hO(r,s);for(const[s,i]of n){const o=sl(r,s);o&&gO(r,o,i,s)}return r}function hO(e,t){const n=t.split("/").filter(Boolean);let r=e;for(let s=0;s<n.length;s++){const i="/"+n.slice(0,s+1).join("/"),o=n.slice(0,s+1).filter(l=>l.startsWith("$"));let a=r.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},r.children.push(a)),r=a}}function La(e,t,n){const r=e.validate?Nn(oe(e.validate.raw),t):t;e.validate=Ua(r,"validate",n)}function Uy(e,t,n){for(const[r,s]of Object.entries(t)){const i=By(`${e.path}/${r}`),o=r.startsWith("$")?[...n,r]:n;let a=e.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},e.children.push(a)),La(a,s.validate,o),s.children&&Uy(a,s.children,o)}}const pO={read:0,write:0,validate:0,schema:0,fieldConstraints:0,indexOn:0,children:0},Ro=Object.keys(pO);function mO(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`The rules for "${e}" must be a path definition object, got ${JSON.stringify(t)}.`);for(const n of Object.keys(t)){if(Ro.includes(n))continue;const r=Zv(n,Ro),s=r===null?`; the keys are ${Ro.map(i=>`'${i}'`).join(", ")}.`:`; did you mean '${r}'?`;throw new Error(`Unknown key '${n}' in the rules for "${e}"${s}`)}}function yO(e){rl(Object.entries(e))}function No(e,t,n){if(n!==void 0){if(typeof n=="boolean")return oe(String(n));if(typeof n=="string"&&n.trim().length>0)return n;throw new Error(`The ${t} rule for "${e}" must be a non-empty expression or a boolean, got ${JSON.stringify(n)}.`)}}function gO(e,t,n,r){const s=r.split("/").filter(Boolean),i=s.filter(u=>u.startsWith("$"));if(n.fieldConstraints&&!n.schema)throw new Error(`fieldConstraints on "${r}" requires a schema.`);const o=No(r,"read",n.read),a=No(r,"write",n.write),l=No(r,"validate",n.validate);if(o!==void 0&&(t.read=Ua(o,"read",i)),a!==void 0&&(t.write=Ua(a,"write",i)),l!==void 0&&La(t,l,i),n.schema){const u=My(n.schema,n.fieldConstraints);La(t,u.validate,i),Uy(t,u.children,i)}if(n.indexOn){const u=bO(e,t,s);if(u){if(!u.indexOn)u.indexOn=[...n.indexOn];else if(!wO(u.indexOn,n.indexOn))throw new Error(`Conflicting indexOn declarations for "${u.path}": ${JSON.stringify(u.indexOn)} vs ${JSON.stringify(n.indexOn)}`)}}}function bO(e,t,n){if(n[n.length-1]?.startsWith("$")){const s="/"+n.slice(0,-1).join("/");return sl(e,s)}return t}function wO(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function By(e){return"/"+e.split("/").filter(Boolean).join("/")}function Yd(e){return e.split("/").filter(Boolean).length}function vO(e){const t=new Set;for(const[n]of e){if(t.has(n))throw new Error(`Duplicate ruleset path declaration for "${n}"`);t.add(n)}}function rl(e){const t=[];for(const[n,r]of e){const s=By(n),i=typeof r=="boolean"?{validate:oe(String(r))}:r;mO(s,i);const{children:o,...a}=i;if(t.push([s,a]),o){const l=Object.entries(o).map(([u,d])=>[`${s}/${u}`,d]);t.push(...rl(l))}}return t}function Ua(e,t,n){return Dp(String(e),t,n)}function sl(e,t){if(e.path===t)return e;for(const n of e.children){const r=sl(n,t);if(r)return r}return null}function xO(e){if(e==null)return null;if(typeof e=="string")return{uid:e,token:{}};const t={uid:e.uid,token:e.token??{}};return e.tenant!==void 0&&(t.tenant=e.tenant),t}function _O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.__type==="serverTimestamp"}function gi(e){if(_O(e))return{".sv":"timestamp"};if(Array.isArray(e))return e.map(gi);if(typeof e=="object"&&e!==null){const t={};for(const[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:gi(r),enumerable:!0,writable:!0,configurable:!0});return t}return e}function Fy(e){const t={operation:e.operation,path:e.path,auth:xO(e.auth),mockData:e.mockData??e.data??{}};return e.newData!==void 0&&(t.newData=gi(e.newData)),e.now!==void 0&&(t.now=e.now),e.updates!==void 0&&(t.updates=e.updates.map(n=>({path:n.path,value:gi(n.value)}))),e.query!==void 0&&(t.query=e.query),t}function Io(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Ba(e,t){const n=[...Io(e.path,".read",e.read,t),...Io(e.path,".write",e.write,t),...Io(e.path,".validate",e.validate,t),...(e.structure??[]).filter(r=>r.severity===(t==="errors"?"error":"warning")).map(r=>({path:r.path,rule:"ruleset",code:r.code,message:r.message}))];for(const r of e.children)n.push(...Ba(r,t));return n}function qy(e){let t;try{t=e()}catch(s){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:s instanceof Error?s.message:String(s)}],warnings:[]}}const n=Ba(t,"errors"),r=Ba(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}function Vy(e){const t={};e.read&&(t[".read"]=e.read.raw),e.write&&(t[".write"]=e.write.raw),e.validate&&(t[".validate"]=e.validate.raw),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const r of e.children){const s=r.path.slice(r.path.lastIndexOf("/")+1);t[s]={},Vy(r)}const n=Xh(e.path,t);return n.length>0&&(e.structure=n),e}class SO{definition;compiled;constructor(t){this.definition=t}compile(){return this.compiled??=Vy(fO(this.definition.paths)),this.compiled}toJSON(){return xk(this.compile())}check(){return qy(()=>this.compile())}simulate(t){return Oc(this.compile(),Fy(t))}}function kO(e){return typeof e.paths=="object"&&e.paths!==null&&yO(e.paths),new SO(e)}function bi(e){return e.split("/").filter(Boolean)}function Fa(e){return`/${bi(e).join("/")}`}function EO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jO(e){if(typeof e!="object"||e===null)return!1;const t=e.path;return typeof t=="string"&&t.length>0&&t.startsWith("/")}function Wy(e){const t=e.map(Fa),n=t.find((r,s)=>t.indexOf(r)!==s);return n!==void 0?`update failed: values argument contains a path ${n} that is ancestor of another path ${n}`:Or(()=>pS(Object.fromEntries(e.map(r=>[r,null])),bi))}function CO(e){if(e.operation==="read")return null;const t=e.operation==="update"?"update":"set";return Or(()=>dS(t,e.path))}function RO(e){return e.query===void 0?null:e.operation!=="read"?`a query applies to a 'read' case, and this case is '${e.operation}'.`:Rp(e.query)}function NO(e){if(e.updates===void 0)return null;if(e.operation!=="write"&&e.operation!=="validate")return`'updates' applies to a 'write' or 'validate' case, and this case is '${e.operation}'.`;const t=e.updates;if(!Array.isArray(t))return"'updates' must be an array of { path, value } entries.";if(!t.every(jO))return"each 'updates' entry needs an absolute 'path' starting with '/'.";const n=Wy(t.map(s=>s.path));if(n!==null)return n;const r=t.find(s=>Fa(s.path)===Fa(e.path));return r===void 0?`'updates' must list the case's path '${e.path}': the case evaluates that path's rules as one of the paths written. Use an 'update' case for the verdict on the whole update.`:e.newData!==void 0&&!ba(e.newData,r.value)?`newData differs from the value 'updates' writes at '${e.path}'. Give one value, or omit newData.`:null}function IO(e){if(e.operation!=="update")return null;if(!EO(e.newData))return"an 'update' case needs newData to be an object keyed by the paths it writes.";const t=Object.keys(e.newData);return t.length===0?"an 'update' case needs newData to name at least one path.":Wy(t)}function AO(e){const t=e.path;return typeof t!="string"?"a case needs 'path' to be a string, such as '/users/alice'.":Or(()=>mS(t,!1))??CO(e)??RO(e)??NO(e)??IO(e)}function il(e){return{success:!1,error:{code:"INVALID_INPUT",message:e,recoverable:!0}}}function OO(e){return`/${e.join("/")}`}function zy(e){const t={operation:e.operation==="update"?"write":e.operation,path:e.path,auth:e.auth??null};return e.data!==void 0&&(t.data=e.data),e.newData!==void 0&&(t.newData=e.newData),e.now!==void 0&&(t.now=e.now),t}function $O(e,t){const n=bi(t.path),r=Object.entries(t.newData).map(([u,d])=>({path:OO([...n,...bi(u)]),value:d}));let s,i;const o=[];let a=[];for(const u of r){const d=zy(t);d.path=u.path,d.newData=u.value,d.updates=r;const h=e.simulate(d);if(!h.success)return h;const f=h.data.trace.filter(m=>m.kind==="write"),p=h.data.trace.filter(m=>m.kind==="validate");if(o.push(...f),!h.data.allowed||h.data.unsupported===!0){if(p.length===0)return{success:!0,data:{...h.data,trace:o}};i??={result:h,validates:p};continue}a=p,s??=h}return i?{success:!0,data:{...i.result.data,trace:[...o,...i.validates]}}:{success:!0,data:{...s.data,trace:[...o,...a]}}}function PO(e,t){const n=AO(t);if(n!==null)return il(n);if(t.operation==="update")return $O(e,t);const r=zy(t);return t.query!==void 0&&(r.query={...t.query}),t.updates!==void 0&&(r.updates=t.updates),e.simulate(r)}function qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DO(e){if(!qa(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]==="instances"&&qa(e.instances)}function Qd(e,t,n){if(typeof e!="string")return{problem:'instance must be a string naming a database instance, such as "my-app-default-rtdb".'};try{const r=X_(e)?.name;return{name:r===void 0||vp(r,n)?t:r}}catch(r){const s=r instanceof Error?r.message.trim():String(r);return{problem:`"${e}" is not a database instance name: ${s}`}}}function Va(e){return[...e].map(t=>`"${t}"`).join(", ")}function Hy(e,t,n){if(e.kind==="every-instance")return e.rules;const r=e.instances.get(t);if(r!==void 0)return r;const s=e.instances.size===0?"it declares no instances":`it holds rules for ${Va(e.instances.keys())}`;return{problem:`this ruleset has no rules for ${n?`database instance "${t}"`:`the default instance "${t}"`}; ${s}.`}}function TO(e,t){const n=e.kind==="per-instance",r=n?e.defaultInstance:bp,s=n?e.projectId:void 0;let i;if(t.instance!==void 0){const d=Qd(t.instance,r,s);if("problem"in d)return d;i=d.name}else n&&(i=r);const o=d=>i===void 0?d:{...d,instance:i},a=Hy(e,i??r,t.instance!==void 0);if("problem"in a)return o(a);const l={...t};if(i!==void 0&&DO(t.data)){const d=new Map;for(const[f,p]of Object.entries(t.data.instances)){const m=Qd(f,r,s);if("problem"in m)return o({problem:`data.instances: ${m.problem}`});if(!qa(p))return o({problem:`data.instances["${f}"] must be an object: the tree of database instance "${m.name}".`});if(d.has(m.name))return o({problem:`data.instances names database instance "${m.name}" more than once (key "${f}" repeats an earlier key); name each instance once, so the verdict does not depend on key order.`});d.set(m.name,p)}if(e.kind==="per-instance"){const f=[...d.keys()].filter(p=>!e.instances.has(p));if(f.length>0)return o({problem:`data.instances names ${Va(f)}, which this ruleset does not declare; it holds rules for ${Va(e.instances.keys())}.`})}const h=d.get(i);h===void 0?delete l.data:l.data=h}return o({rules:a,evaluated:l})}const tn="rtdbRules.fromFirebaseJson";function MO(){const e=globalThis.process?.getBuiltinModule,t=typeof e=="function"?e.call(process,"node:fs"):void 0,n=typeof e=="function"?e.call(process,"node:path"):void 0;if(t===void 0||n===void 0)throw new Error(`${tn} reads files, which needs Node.js 20.16 or later, Bun or Deno. Without a file system, pass each instance's rules text to rtdbRules.`);return{fs:t,path:n}}function Ao(e,t){try{return e.readFileSync(t,"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}}function Xd(e,t){try{return JSON.parse(e)}catch(n){throw new Error(`${tn}: ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function LO(e,t={}){const{fs:n,path:r}=MO(),s=r.resolve(e),i=r.dirname(s),o=Ao(n,s);if(o===null)throw new Error(`${tn}: there is no firebase.json at ${s}.`);const a=Xd(o,s);let l;const u=()=>{if(l!==void 0)return l;const m=r.resolve(i,".firebaserc"),g=Ao(n,m);return l=g===null?null:Xd(g,m),l};let d=t.projectId===""?void 0:t.projectId;if(d===void 0){const m=u()?.projects?.default;typeof m=="string"&&m!==""&&(d=m)}let h;try{h=yE(a?.database,{...d===void 0?{}:{projectId:d},targetInstances:m=>d===void 0?void 0:u()?.targets?.[d]?.database?.[m],resolveFile:m=>r.resolve(i,m)})}catch(m){throw new Error(`${tn}: ${m instanceof Error?m.message:String(m)}`)}const[f]=h.unresolved;if(f!==void 0){const m=d===void 0?"no project id is set: pass { projectId } or set projects.default in .firebaserc":`.firebaserc maps it to no instance for project "${d}" (firebase target:apply database ${f.target} <instance>)`;throw new Error(`${tn}: ${f.label} deploys to target "${f.target}", and ${m}.`)}const p=new Map;for(const m of h.targets){const g=p.get(m.file);if(g!==void 0){g.instances.push(m.instance);continue}const b=Ao(n,m.file);if(!(b===null&&!m.configured)){if(b===null)throw new Error(`${tn}: ${m.file} does not exist, and ${m.label} deploys it to database instance "${m.instance}".`);p.set(m.file,{file:m.configuredFile,path:m.file,text:b,instances:[m.instance]})}}if(p.size===0)throw new Error(`${tn}: ${s} deploys no Realtime Database rules.`);return{defaultInstance:h.defaultInstance,...d===void 0?{}:{projectId:d},files:[...p.values()]}}class Ky{text;pos=0;line=1;lineStart=0;constructor(t){this.text=t}parseDocument(){try{this.skipTrivia();const t=this.parseValue();return this.skipTrivia(),this.pos<this.text.length?void 0:t}catch{return}}newline(){this.line++,this.lineStart=this.pos}skipTrivia(){const t=this.text;for(;this.pos<t.length;){const n=t[this.pos];if(n===`
135
+ `)this.pos++,this.newline();else if(n==="\r")this.pos++,t[this.pos]===`
136
+ `&&this.pos++,this.newline();else if(n===" "||n===" "||n==="\uFEFF")this.pos++;else if(n==="/"&&t[this.pos+1]==="/")for(;this.pos<t.length&&t[this.pos]!==`
137
+ `&&t[this.pos]!=="\r";)this.pos++;else if(n==="/"&&t[this.pos+1]==="*")for(this.pos+=2;;){if(this.pos>=t.length)throw new Error("unterminated comment");const r=t[this.pos];if(r==="*"&&t[this.pos+1]==="/"){this.pos+=2;break}this.pos++,r===`
138
+ `?this.newline():r==="\r"&&(t[this.pos]===`
139
+ `&&this.pos++,this.newline())}else return}}parseValue(){const t=this.text[this.pos];return t==="{"?this.parseObject():t==="["?(this.parseArray(),null):t==='"'?(this.parseString(),null):(this.parseLiteral(),null)}parseObject(){const t=new Map;if(this.pos++,this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t;for(;;){if(this.skipTrivia(),this.text[this.pos]!=='"')throw new Error("expected key");const n={line:this.line,column:this.pos-this.lineStart+1},r=this.parseString();if(this.skipTrivia(),this.text[this.pos]!==":")throw new Error("expected colon");this.pos++,this.skipTrivia();const s=this.parseValue();t.set(r,{location:n,value:s}),this.skipTrivia();const i=this.text[this.pos++];if(i==="}")return t;if(i!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t}}parseArray(){if(this.pos++,this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}for(;;){this.skipTrivia(),this.parseValue(),this.skipTrivia();const t=this.text[this.pos++];if(t==="]")return;if(t!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}}}parseString(){const t=this.text,n=this.pos;for(this.pos++;;){if(this.pos>=t.length)throw new Error("unterminated string");const s=t[this.pos];if(s==="\\"){if(this.pos+1>=t.length||t.charCodeAt(this.pos+1)<32)throw new Error("invalid escape");this.pos+=2}else if(s==='"'){this.pos++;break}else s===`
140
+ `?(this.pos++,this.newline()):s==="\r"?(this.pos++,t[this.pos]===`
141
+ `&&this.pos++,this.newline()):this.pos++}const r=t.slice(n,this.pos).replace(/[\u0000-\u001f]/g,s=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`);return JSON.parse(r)}parseLiteral(){const t=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(this.text.slice(this.pos,this.pos+64));if(!t)throw new Error("unexpected token");this.pos+=t[0].length}}function Gy(e,t,n){let r=e.get("rules")?.value??null;for(const s of t.split("/").filter(i=>i.length>0))r=r?.get(s)?.value??null;return r?.get(n)?.location??null}function UO(e,t,n){const r=new Ky(e).parseDocument();return r?Gy(r,t,n):null}function Jy(e,t){const n=new Ky(e).parseDocument();return t.map(r=>{const s=n?Gy(n,r.path,`.${r.kind}`):null;return s?{...r,line:s.line}:{...r}})}const Zd=["read","write","validate","indexOn"];function Oo(e,t){return`${e}\0${t}`}function BO(e){const t=["allow","deny","error"].filter(n=>e[n]>0);return t.length>1?"mixed":t.length===1?t[0]:e.unsupported>0?"unsupported":"never-evaluated"}class FO{compiled;rows=new Map;missing=new Map;constructor(t){this.compiled=t,this.collect(t)}collect(t){for(const n of Zd){let r;n==="indexOn"?t.indexOn!==void 0&&(r=JSON.stringify(t.indexOn)):r=t[n]?.raw,r!==void 0&&this.rows.set(Oo(t.path,n),{path:t.path,kind:n,expression:r,counts:{allow:0,deny:0,error:0,unsupported:0}})}for(const n of t.children)this.collect(n)}record(t){for(const n of t??[]){const r=this.rows.get(Oo(n.path,n.kind));r!==void 0&&(n.verdict==="ALLOW"?r.counts.allow++:n.verdict==="DENY"?r.counts.deny++:n.verdict==="ERROR"?r.counts.error++:r.counts.unsupported++)}}recordQuery(t,n){if(n===void 0)return;let r=null;if(n.orderByValue===!0)r=".value";else if(typeof n.orderByChild=="string"){const o=n.orderByChild.split("/").filter(Boolean).join("/");o!==""&&(r=o)}if(r===null)return;const s=t.split("/").filter(Boolean),i=Lp(this.compiled,s,r);for(const o of i){const a=this.rows.get(Oo(o.path,"indexOn"));a!==void 0&&a.counts.allow++}if(i.length===0){const o=`/${s.join("/")}`;this.missing.set(`${o}\0${r}`,{path:o,index:r})}}summarize(t={}){const n=[];for(const a of this.rows.values()){const{allow:l,deny:u,error:d,unsupported:h}=a.counts,f={path:a.path,kind:a.kind,expression:a.expression,evaluated:l+u+d,allow:l,deny:u,error:d,unsupported:h,status:BO(a.counts)};n.push(f)}const r=t.source===void 0?n:Jy(t.source,n),s=Object.fromEntries(Zd.map(a=>[a,{total:0,covered:0,unsupported:0}]));let i=0,o=0;for(const a of r)s[a.kind].total++,a.evaluated>0?(s[a.kind].covered++,i++):a.status==="unsupported"&&(s[a.kind].unsupported++,o++);return{rules:r,uncovered:r.filter(a=>a.status==="never-evaluated").map(a=>`${a.path} .${a.kind}`),missingIndexes:[...this.missing.values()],files:[{file:t.file??null,total:r.length,covered:i,neverEvaluated:r.filter(a=>a.status==="never-evaluated").length,unsupported:o,byKind:s}]}}}function qO(e){const t={rules:[],uncovered:[],missingIndexes:[],files:[]};for(const n of e){const r=n.files[0]?.file??"rules";t.rules.push(...n.rules.map(s=>({file:r,...s}))),t.uncovered.push(...n.uncovered.map(s=>`${r} ${s}`)),t.missingIndexes.push(...n.missingIndexes.map(s=>({...s,file:r}))),t.files.push(...n.files)}return t}const zr=Symbol("non-null"),VO=/^auth(\s*\.\s*token)?$/;function WO(e,t){if(t!=="any"){if(e.startsWith("$"))return zr;if(e==="auth")return t==="signed-out"?null:zr}}function zO(e,t,n){if(VO.test(e.sourceString))return n==="signed-out"?null:n==="signed-in"&&t==="uid"&&e.sourceString==="auth"?zr:void 0}const HO=new Set(["exists","isString","isNumber","isBoolean","hasChild","hasChildren"]);function An(e){return e===!1||e==="exists-false"||e==="delete-guard"}function ef(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function KO(e){const t=e.newDataRelPath();return t!==void 0&&t.length===0}function tf(e,t,n){const r=this.args.acc;(e.newDataRelPath()?.join("/")===".val()"&&n.constIn("any")===null||n.newDataRelPath()?.join("/")===".val()"&&e.constIn("any")===null)&&r.newDataExistsCalls++,e.collect(r),n.collect(r)}function _s(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(typeof s!="number"||typeof i!="number")return;const o=e(s,i);return o!==void 0&&Number.isFinite(o)?o:void 0}}function Ss(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(typeof s=="number"&&typeof i=="number"||typeof s=="string"&&typeof i=="string")return e===">"?s>i:e===">="?s>=i:e==="<"?s<i:s<=i}}function ks(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(!(s===void 0||i===void 0))return s===zr||i===zr?s!==null&&i!==null?void 0:!e:e?s===i:s!==i}}function Es(e,t,n){const r=this.args.relSegments;return e.evalOnDelete(r)===null||n.evalOnDelete(r)===null?!1:this.constIn("any")}function nf(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);if(s===null&&i===null&&e.constIn("any")===null!=(n.constIn("any")===null))return"delete-guard";if(s!==void 0&&i!==void 0)return s===i;if(s===null&&e.constIn("any")!==null||i===null&&n.constIn("any")!==null)return!1}function rf(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);return s!==void 0&&i!==void 0?s!==i:void 0}function js(e,t,n,r){let s=n(e);for(const i of t.children)s=r(s,()=>n(i));return s}function GO(e,t){if(e===!1)return!1;if(e!==!0)return;const n=t();return typeof n=="boolean"?n:void 0}function JO(e,t){if(e===!0)return!0;if(e!==!1)return;const n=t();return typeof n=="boolean"?n:void 0}function YO(e,t){const n=t();return e===!1||e==="exists-false"||n===!1||n==="exists-false"?!1:e==="delete-guard"||n==="delete-guard"?"delete-guard":e===!0&&n===!0?!0:void 0}function QO(e,t){if(e===!0)return!0;const n=t();return An(e)&&An(n)?e==="delete-guard"||n==="delete-guard"?"delete-guard":!1:An(e)&&n===!0?!0:void 0}let $o;function XO(){if($o)return $o;const e=rs();return e.addOperation("newDataRelPath",{_nonterminal(...t){return t.length===1?t[0].newDataRelPath():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.newDataRelPath()},ident(t,n,r){return this.sourceString==="newData"?[]:void 0},CallExpr_methodCall(t,n,r,s,i,o){const a=t.newDataRelPath();if(a===void 0||a[0]===".val()")return;const l=r.sourceString;if(l==="val"&&a.length===0&&i.asIteration().children.length===0)return[".val()"];if(l==="child"){const u=i.asIteration().children,d=u.length===1?u[0].constIn("any"):void 0;return typeof d=="string"?[...a,...d.split("/").filter(Boolean)]:void 0}return l==="parent"&&a.length>0?a.slice(0,-1):void 0}}),e.addOperation("collect(acc)",{_nonterminal(...t){t.forEach(n=>n.collect(this.args.acc))},_iter(...t){t.forEach(n=>n.collect(this.args.acc))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.acc;if(KO(t)){const l=r.sourceString;l==="exists"&&a.newDataExistsCalls++,l==="parent"&&a.newDataEscapes++,(l==="hasChild"||l==="child")&&(a.checksNamedChildren=!0),l==="hasChildren"&&i.asIteration().children.length>0&&(a.checksNamedChildren=!0)}t.collect(a),i.asIteration().children.forEach(l=>l.collect(a))},Equality_strictNeq:tf,Equality_looseNeq:tf,CallExpr_memberAccess(t,n,r){t.collect(this.args.acc)},ident(t,n,r){const s=this.args.acc,i=this.sourceString;i==="auth"?s.readsAuth=!0:i==="data"?s.readsData=!0:i==="root"?s.readsRoot=!0:i==="newData"&&s.newDataReads++}}),e.addOperation("constIn(world)",{_nonterminal(...t){return t.length===1?t[0].constIn(this.args.world):void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.constIn(this.args.world)},ident(t,n,r){return WO(this.sourceString,this.args.world)},CallExpr_memberAccess(t,n,r){return zO(t,r.sourceString,this.args.world)},bool_true(t){return!0},bool_false(t){return!1},null(t){return null},number(t){const n=Number(this.sourceString);return Number.isFinite(n)?n:void 0},string_single(t,n,r){return Rr(this.sourceString)?void 0:Nr(this.sourceString)},string_double(t,n,r){return Rr(this.sourceString)?void 0:Nr(this.sourceString)},UnaryExpr_not(t,n){const r=n.constIn(this.args.world);return typeof r=="boolean"?!r:void 0},UnaryExpr_neg(t,n){const r=n.constIn(this.args.world);return typeof r=="number"&&Number.isFinite(-r)?-r:void 0},Multiplicative_mul:_s((t,n)=>t*n),Multiplicative_div:_s((t,n)=>n===0?void 0:t/n),Multiplicative_mod:_s((t,n)=>n===0?void 0:t%n),Additive_sub:_s((t,n)=>t-n),Additive_add(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);return typeof s=="number"&&typeof i=="number"?Number.isFinite(s+i)?s+i:void 0:typeof s=="string"&&typeof i=="string"?s+i:void 0},Comparison_gt:Ss(">"),Comparison_gte:Ss(">="),Comparison_lt:Ss("<"),Comparison_lte:Ss("<="),Equality_strictEq:ks(!0),Equality_looseEq:ks(!0),Equality_strictNeq:ks(!1),Equality_looseNeq:ks(!1),LogicalAnd_and(t,n,r){return js(t,r,s=>s.constIn(this.args.world),GO)},LogicalOr_or(t,n,r){return js(t,r,s=>s.constIn(this.args.world),JO)},Ternary_ternary(t,n,r,s,i){const o=t.constIn(this.args.world);if(o===!0)return r.constIn(this.args.world);if(o===!1)return i.constIn(this.args.world)}}),e.addOperation("constant(world)",{_nonterminal(){const t=this.constIn(this.args.world);return typeof t=="boolean"?t:void 0},_iter(){},_terminal(){}}),e.addOperation("evalOnDelete(relSegments)",{_nonterminal(...t){const n=this.constIn("any");return n!==void 0?n:t.length===1?t[0].evalOnDelete(this.args.relSegments):void 0},_iter(){},_terminal(){return this.constIn("any")},Primary_paren(t,n,r){return n.evalOnDelete(this.args.relSegments)},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.relSegments,l=t.newDataRelPath(),u=r.sourceString;if(l!==void 0&&l[0]!==".val()"){if(ef(l,a)){if(u==="exists")return"exists-false";if(HO.has(u))return!1;if(u==="val"||u==="getPriority")return null}const d=i.asIteration().children;let h=[];u==="hasChild"&&d.length===1?h=[d[0]]:u==="hasChildren"&&d.length===1&&d[0].ctorName==="Array"&&(h=d[0].children[1].asIteration().children);for(const f of h){const p=f.constIn("any");if(typeof p=="string"&&ef([...l,...p.split("/").filter(Boolean)],a))return!1}}return t.evalOnDelete(a)===null?!1:void 0},CallExpr_memberAccess(t,n,r){return t.evalOnDelete(this.args.relSegments)===null?!1:void 0},UnaryExpr_not(t,n){const r=n.evalOnDelete(this.args.relSegments);return r==="exists-false"?"delete-guard":r==="delete-guard"?!1:typeof r=="boolean"?!r:void 0},Comparison_gt:Es,Comparison_gte:Es,Comparison_lt:Es,Comparison_lte:Es,Equality_strictEq:nf,Equality_looseEq:nf,Equality_strictNeq:rf,Equality_looseNeq:rf,LogicalAnd_and(t,n,r){const s=this.args.relSegments;return js(t,r,i=>i.evalOnDelete(s),YO)},LogicalOr_or(t,n,r){const s=this.args.relSegments;return js(t,r,i=>i.evalOnDelete(s),QO)},Ternary_ternary(t,n,r,s,i){const o=this.args.relSegments,a=t.evalOnDelete(o);if(a===!0)return r.evalOnDelete(o);if(a===!1||a==="exists-false")return i.evalOnDelete(o);if(An(r.evalOnDelete(o))&&An(i.evalOnDelete(o)))return!1}}),$o=e,e}function Po(e){if(e===void 0||!e.parsed.valid||e.parsed.errors.length>0)return;const t=ns(e.raw);if(!t.ok)return;const n=XO()(t.match),r={readsAuth:!1,readsData:!1,readsRoot:!1,newDataReads:0,newDataEscapes:0,newDataExistsCalls:0,checksNamedChildren:!1};n.collect(r);const s=n.constant("signed-out"),i=n.constant("signed-in"),o=s!==void 0&&s===i?s:void 0;return{constant:o,signedOut:s,signedIn:i,...r,canGrantOnDelete:a=>o!==!1&&!An(n.evalOnDelete(a))}}function sf(e,t){const n=e.split("/").filter(Boolean);return t.split("/").filter(Boolean).slice(n.length)}function Yy(e){return{node:e,read:Po(e.read),write:Po(e.write),validate:Po(e.validate),children:e.children.map(Yy)}}function Cs(e){return e!==void 0&&e.constant!==!1}function ZO(e){const t=e.validate;return t===void 0||t.constant!==void 0?!1:t.newDataReads-t.newDataEscapes>t.newDataExistsCalls}function Sr(e){if(ZO(e))return!0;if(e.children.length===0)return!1;const t=e.children.filter(n=>!Wa(n));return e.children.some(Sr)&&t.every(Sr)}function Qy(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??""}function Wa(e){return Qy(e.node.path).startsWith("$")}function vt(e){const t=e.raw.trim();return t.length<=80?t:`${t.slice(0,77)}...`}function e$(e){return e.raw.trim()==="true"?"true":`"${vt(e)}"`}function t$(e){return e.raw.trim()==="false"?"is false":`"${vt(e)}" is false for every request`}function Do(e){return e.raw.trim()==="true"?"is true":`"${vt(e)}" is true for every request`}function To(e){return e==="/"?"the database":e}function n$(e){const t=[];return Xy(Yy(e),{ancestors:[],unboundedAbove:!1},t),t}function Xy(e,t,n){const r=e.node.path,s=e.write,i=e.read;if(s?.constant===!0&&n.push({code:"RTDB-SEC-1",severity:"critical",path:r,rule:".write",message:`${r} .write ${Do(e.node.write)}: anyone, signed in or not, can write, replace or delete any value under ${To(r)}.`,fix:`Replace ${r} .write ${e$(e.node.write)} with a condition on auth that a signed-out client fails, such as "auth != null && auth.uid == $uid" on the node each user owns.`}),i?.constant===!0){const p=r==="/";n.push({code:"RTDB-SEC-2",severity:p?"critical":"medium",path:r,rule:".read",message:p?`/ .read ${Do(e.node.read)}: anyone, signed in or not, can read the entire database.`:`${r} .read ${Do(e.node.read)}: anyone, signed in or not, can read everything under ${r}.`,fix:p?"Remove .read from the root and grant .read on the subtrees clients need, with a condition on auth.":`Require auth in ${r} .read ("auth != null"), or keep ${r} only if every value under it is meant to be public.`})}s!==void 0&&s.constant===void 0&&!s.readsAuth&&n.push({code:"RTDB-SEC-3",severity:"high",path:r,rule:".write",message:`${r} .write does not read auth: a signed-out client can write under ${To(r)} whenever "${vt(e.node.write)}" holds.`,fix:`Add an auth condition to ${r} .write, such as "auth != null && (${vt(e.node.write)})".`});for(const p of["read","write"]){const m=e[p];if(m===void 0)continue;const g=p==="read"?".read":".write",b=t.ancestors.find(S=>{const k=S[p];return Cs(k)?k.constant===!0?m.constant!==!0:m.constant===!1||k.signedIn===!0&&m.signedOut===!1:!1});if(b===void 0)continue;const w=b.node.path,x=b.node[p],v=e.node[p];let _;b[p].constant===!0?_=`${r} ${g} never restricts access: ${w} ${g} is true and grants ${p} on every path under it, and a deeper rule cannot revoke an ancestor's grant.`:m.constant===!1?_=`${r} ${g} ${t$(e.node[p])} and does not revoke ${w} ${g}: whenever "${vt(x)}" holds, ${w} grants ${p} on every path under it, including ${r}.`:_=`${r} ${g} "${vt(v)}" restricts nothing: ${w} ${g} "${vt(x)}" already grants every signed-in client ${p} on every path under it, including ${r}, and a deeper rule cannot revoke an ancestor's grant.`,n.push({code:"RTDB-SEC-4",severity:"high",path:r,rule:g,message:_,fix:`Move the grant from ${w} ${g} down to the children that need it, so that no ancestor of ${r} grants ${p}.`})}const o=e.validate;if(o!==void 0&&o.constant===void 0&&(o.readsData||o.readsRoot||o.newDataExistsCalls>0)){const p=[...t.ancestors,e].find(m=>Cs(m.write)&&m.write.canGrantOnDelete(sf(m.node.path,r)));if(p!==void 0){const m=p.node.path,g=sf(m,r),b=g.length>0&&g.every(w=>!w.startsWith("$"))?`newData.child('${g.join("/")}').exists()`:"newData.exists()";n.push({code:"RTDB-SEC-5",severity:"high",path:r,rule:".validate",message:`${r} .validate does not run when ${r} is deleted: .validate runs only on a non-null new value, and ${m} .write grants without requiring ${b}, so a client it admits can delete ${r} (write null at ${m}) and bypass "${vt(e.node.validate)}".`,fix:`Add "${b}" to ${m} .write to refuse deletes, or write the delete condition there, such as "${b} || <who may delete>".`})}}let a=t.unboundedAbove;!a&&Cs(s)&&s.newDataReads===s.newDataExistsCalls&&!Sr(e)&&(a=!0,n.push({code:"RTDB-SEC-6",severity:"high",path:r,rule:".write",message:`${r} .write accepts any value: no .validate rule at or below ${r} checks its own new value, and the .write rule does not check newData, so a client it admits can store data of any shape and size under ${To(r)}.`,fix:`Add .validate rules under ${r} that fix the shape and bound sizes, such as "newData.isString() && newData.val().length <= 100", and "$other": { ".validate": false } for keys you do not name.`}));const l=e.children.filter(p=>!Wa(p)&&Sr(p)).map(p=>Qy(p.node.path)),u=l.length>0||o?.checksNamedChildren===!0,d=e.children.some(p=>Wa(p)&&(p.validate?.constant===!1||Sr(p))),h=[...t.ancestors,e].some(p=>Cs(p.write));if(u&&!d&&h){const p=l.length>0?`names ${l.join(", ")} with .validate rules`:"checks named children in .validate";n.push({code:"RTDB-SEC-7",severity:"medium",path:r,rule:".validate",message:`${r} ${p} but has no $other rule: a write at or above ${r} can add any other key under it, and no .validate rule checks that key.`,fix:`Add "$other": { ".validate": false } under ${r} to reject keys it does not name.`})}const f={ancestors:[...t.ancestors,e],unboundedAbove:a};for(const p of e.children)Xy(p,f,n)}function r$(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function s$(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class Zy{placement;constructor(t){this.placement=t}get doc(){if(this.placement.kind!=="every-instance")throw new Error("per-instance rules hold one ruleset per instance");return this.placement.rules.doc}lint(){return this.placement.kind==="every-instance"?of(this.doc):[...new Set(this.placement.instances.values())].flatMap(t=>of(t.doc).map(n=>t.file===void 0?n:{...n,file:t.file}))}runOne(t){const n=TO(this.placement,t),r=n.instance,s={case:t,...t.description!==void 0?{description:t.description}:{},...r!==void 0?{instance:r}:{}},i="problem"in n?il(n.problem):PO(n.rules.doc,n.evaluated);if(!i.success)return{...s,expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:"",reason:i.error.message,trace:[]};const o=i.data,a=o.unsupported===!0,l=a?"UNSUPPORTED":o.allowed?"ALLOW":"DENY",u=!a&&l===t.expectation;return{...s,expectation:t.expectation,decision:l,passed:u,unsupported:a,matchedPath:o.matchedPath,matchedRule:o.matchedRule,reason:o.reason,trace:r===void 0?o.trace:o.trace.map(d=>({...d,instance:r}))}}simulate(t){const n=t.map(o=>this.runOne(o));let r=0,s=0,i=0;for(const o of n)o.unsupported?i++:o.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n,coverage:this.coverage(n)}}coverage(t,n){if(this.placement.kind==="every-instance")return af(this.doc,t,n);const{defaultInstance:r,instances:s}=this.placement,o=[...new Set(s.values())].map(a=>{const l=t.filter(u=>s.get(u.instance??r)===a);return af(a.doc,l,{...a.file===void 0?{}:{file:a.file},...a.source===void 0?{}:{source:a.source}})});return o.length===1?o[0]:qO(o)}explain(t){const n=this.runOne(t);return{...n.instance!==void 0?{instance:n.instance}:{},decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason,trace:n.trace}}toJSON(){if(this.placement.kind==="every-instance")return this.doc.toJSON();const t=Hy(this.placement,this.placement.defaultInstance,!1);if("problem"in t)throw new Error(t.problem);return t.doc.toJSON()}}function of(e){const t=e.check(),n=[...t.errors.map(r=>Jd(r,"error")),...t.warnings.map(r=>Jd(r,"warning"))];return t.errors.some(r=>r.code==="COMPILE_ERROR")?n:[...n,...n$(e.compile()).map(tO)]}function i$(e){try{return e.compile()}catch{return Ac({rules:{}})}}function af(e,t,n){const r=new FO(i$(e));for(const s of t){r.record(s.trace);const i=s.unsupported&&s.trace.length===0;s.case.operation==="read"&&!i&&r.recordQuery(s.case.path,s.case.query)}return r.summarize(n)}function Mo(e){return new Zy({kind:"every-instance",rules:{doc:e}})}class eg{json;compiled;compileError;constructor(t){this.json=t}toJSON(){return this.json}compile(){if(this.compileError!==void 0)throw this.compileError;try{this.compiled??=Ac(this.json)}catch(t){throw this.compileError=t,t}return this.compiled}check(){return qy(()=>this.compile())}simulate(t){let n;try{n=this.compile()}catch(r){return il(`the ruleset does not compile: ${r instanceof Error?r.message:String(r)}`)}return Oc(n,Fy(t))}}function tg(e){let t;try{t=JSON.parse(eR(e))}catch(s){const i=s instanceof Error?s.message:String(s);throw cf(`Realtime Database rules text is not valid JSON: ${i}`)}const n=t?.rules;if(!(typeof n=="object"&&n!==null&&!Array.isArray(n)))throw cf('Realtime Database rules text has no top-level "rules" object');return t}function cf(e){return new Ma(e,[{code:"PARSE_ERROR",severity:"error",message:e,origin:"parse"}])}function o$(e){return typeof e=="string"&&(e=tg(e)),r$(e)?Mo(e):s$(e)?Mo(new eg(e)):Mo(kO(e))}function a$(e,t={}){const n=LO(e,t),r=new Map;for(const s of n.files){let i;try{i=tg(s.text)}catch(a){throw a instanceof Ma?new Ma(`${s.path}: ${a.message}`,a.issues):a}const o={doc:new eg(i),file:s.file,source:s.text};for(const a of s.instances)r.set(a,o)}return new Zy({kind:"per-instance",defaultInstance:n.defaultInstance,...n.projectId===void 0?{}:{projectId:n.projectId},instances:r})}const c$=Object.assign(o$,{fromFirebaseJson:a$});function ng(e){return e&&typeof e=="object"&&Na in e?ZN(e).backend:Jk(e)}function rg(e){return ng(e).getActiveRules()}function lf(e){return ng(e).snapshotState()}function l$(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function uf(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function u$(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function d$(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object"||Array.isArray(n))return null;n=n[r]}return n??null}function sg(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:uf(e)};const i=Object.entries(e).sort(([h],[f])=>h.localeCompare(f)),o={},a=[];for(const[h,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?a.push([h,f]):o[h]=uf(f);const l=n>=r&&a.length>0,u=i.length>s,d=n>=r?[]:a.slice(0,s).map(([h,f])=>sg(f,l$(t,h),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:o}}function f$(e,t={}){const n=u$(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return sg(d$(e,n),n,0,r,s)}function ig(e){return e.children.reduce((t,n)=>t+1+ig(n),0)}const Lo={anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]};function h$(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, update, or validate operation against the RTDB rules and data currently loaded in the local sandbox. newData may be any JSON value, such as 5 or true; for update it is the patch keyed by the paths written, relative to path. A read may carry a query so query.* rules evaluate. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","update","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{},query:{type:"object",properties:{orderByChild:{type:"string"},orderByKey:{type:"boolean",enum:[!0]},orderByValue:{type:"boolean",enum:[!0]},equalTo:Lo,startAt:Lo,endAt:Lo,limitToFirst:{type:"integer"},limitToLast:{type:"integer"}},additionalProperties:!1},now:{type:"number"}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=rg(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=lf(r),o=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{};let a=n.now;a===void 0&&(a=De(r).now());let l=null;if(n.auth){const h=Dy(n.auth.uid,n.auth.tenant,n.auth.claims);l={uid:h.uid,token:h.token}}const u={expectation:"ALLOW",operation:n.operation,path:n.path,auth:l,data:o,now:a};n.newData!==void 0&&(u.newData=n.newData),n.query!==void 0&&(u.query=n.query);const d=c$(s).simulate([u]).cases[0];return{ok:!d.unsupported,summary:d.unsupported?`Simulation unsupported: ${d.reason}`:`Simulation: ${d.decision.toLowerCase()}`,data:{decision:d.decision,allowed:d.decision==="ALLOW",unsupported:d.unsupported,matchedPath:d.matchedPath,matchedRule:d.matchedRule,reason:d.reason,trace:d.trace}}}},{name:"rtdb_crawl_structure",description:"Describe the structure of the RTDB data currently loaded in the local sandbox without returning leaf values or contacting a production database.",parameters:{type:"object",properties:{path:{type:"string",description:"Root-relative path to inspect. Defaults to /."},maxDepth:{type:"number",minimum:0,description:"Maximum object depth to return. Defaults to 10."},maxChildren:{type:"number",minimum:1,description:"Maximum object children to return per node. Defaults to 100."}}},async execute(t){const n=t,r=await e.resolveSandbox(),s=f$(lf(r),n);return{ok:!0,summary:`Crawled ${ig(s)} object paths from ${s.path}`,data:s}}}]}function ir(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,claims:{...e.customClaims},providers:e.providerUserInfo.map(t=>t.providerId),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,tenantId:e.tenantId,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}function p$(e,t){const n=JSON.stringify(t?{uid:e,claims:t}:{uid:e}),r=new TextEncoder().encode(n);let s="";for(const i of r)s+=String.fromCharCode(i);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Dt(e,t){return{ok:!1,summary:t,data:{code:e}}}function or(e){const t=typeof e?.code=="string"?e.code:"auth/internal-error";return Dt(t,e instanceof Error?e.message:String(e))}function qs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function At(e){return qs(e)?e:{}}function Rs(e,t){const n=e.uid;return typeof n!="string"||n.length===0?Dt("auth/argument-error",`${t}: uid must be a non-empty string.`):n}function og(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>({providerId:t}))}function df(e){return{uid:e.uid,email:e.email,password:e.password,displayName:e.displayName,phoneNumber:e.phoneNumber,customClaims:e.claims,disabled:e.disabled,emailVerified:e.emailVerified,providerUserInfo:og(e.providers)}}const za={type:"object",description:"Custom claims. Rules read them as request.auth.token.<name>."},m$={type:"array",items:{type:"string"},description:"Provider ids to link, for example google.com. A user created under a dotted provider id and no password is assigned a generated photoUrl."},Ha={email:{type:"string"},password:{type:"string",description:"At least six characters. Never returned."},displayName:{type:"string"},phoneNumber:{type:"string"},claims:za,providers:m$,disabled:{type:"boolean"},emailVerified:{type:"boolean"}},y$={type:"object",properties:{uid:{type:"string",description:"Generated when omitted."},...Ha},required:["email"]},ff="Users land in the one pool the application, Studio, and rules evaluation share. Creating a user does not sign anyone in, and a password is never returned. A user created under a dotted provider id with no password is assigned a generated photoUrl; password, phone, and anonymous users keep photoUrl null.";function g$(e){const t=async()=>Mc(await e.resolveSandbox());return[{name:"auth_create_user",description:`Create one user in the connected sandbox's user store. ${ff}`,parameters:{type:"object",properties:{uid:{type:"string",description:"User id. Generated when omitted."},...Ha}},async execute(n){const r=At(n),s=await t();try{const i=ve.createUser(s,df(r));return{ok:!0,summary:`Created user ${i.uid}`,data:{user:ir(i)}}}catch(i){return or(i)}}},{name:"auth_import_users",description:`Create many users in order, reporting each failure without stopping. ${ff}`,parameters:{type:"object",properties:{users:{type:"array",items:y$,description:"Users to create, in order. Each requires an email."}},required:["users"]},async execute(n){const s=At(n).users;if(!Array.isArray(s))return Dt("auth/argument-error","auth_import_users: users must be an array.");const i=await t(),o=[],a=[];s.forEach((u,d)=>{const h=qs(u)?u:{};if(typeof h.email!="string"||h.email.length===0){a.push({index:d,...h.uid?{uid:h.uid}:{},email:String(h.email??""),code:"auth/argument-error",message:`auth_import_users: users[${d}].email is required.`});return}try{o.push(ve.createUser(i,df(h)).uid)}catch(f){const p=or(f).data;a.push({index:d,...h.uid?{uid:h.uid}:{},email:h.email,code:p.code,message:f instanceof Error?f.message:String(f)})}});const l=a.length===0?`Imported ${o.length} of ${s.length} users`:`Imported ${o.length} of ${s.length} users; ${a.length} failed`;return{ok:a.length===0,summary:l,data:{created:o,errors:a}}}},{name:"auth_get_user",description:"Read one user of the connected sandbox's user store by uid, or by email when uid is omitted.",parameters:{type:"object",properties:{uid:{type:"string"},email:{type:"string",description:"Matched case-insensitively. Used when uid is omitted."}}},async execute(n){const{uid:r,email:s}=At(n);if(typeof r!="string"&&typeof s!="string")return Dt("auth/argument-error","auth_get_user: uid or email is required.");const i=ve.listUsers(await t()),o=typeof r=="string"?i.find(a=>a.uid===r):i.find(a=>a.email?.toLowerCase()===s.toLowerCase());return o?{ok:!0,summary:`Got user ${o.uid}`,data:{user:ir(o)}}:Dt("auth/user-not-found",typeof r=="string"?`No user found for uid ${r}.`:`No user found for email ${s}.`)}},{name:"auth_list_users",description:"Read every user of the connected sandbox's user store.",parameters:{type:"object",properties:{limit:{type:"number",description:"Return at most this many users."}}},async execute(n){const{limit:r}=At(n);if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<0))return Dt("auth/argument-error","auth_list_users: limit must be a non-negative number.");const s=ve.listUsers(await t()),i=(r!==void 0?s.slice(0,r):s).map(ir);return{ok:!0,summary:`${i.length} of ${s.length} users`,data:{users:i,total:s.length}}}},{name:"auth_update_user",description:"Change one user. Every supplied field replaces what is stored; claims replaces the whole claims map. Omitted fields are left alone.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},...Ha},required:["uid"]},async execute(n){const r=At(n),s=Rs(r,"auth_update_user");if(typeof s!="string")return s;const i=r,o={...i.email!==void 0?{email:i.email}:{},...i.password!==void 0?{password:i.password}:{},...i.displayName!==void 0?{displayName:i.displayName}:{},...i.phoneNumber!==void 0?{phoneNumber:i.phoneNumber}:{},...i.disabled!==void 0?{disabled:i.disabled}:{},...i.emailVerified!==void 0?{emailVerified:i.emailVerified}:{},...i.claims!==void 0?{customClaims:i.claims}:{},...i.providers!==void 0?{providerUserInfo:og(i.providers)}:{}};try{const a=ve.updateUser(await t(),s,o);return{ok:!0,summary:`Updated user ${s}`,data:{user:ir(a)}}}catch(a){return or(a)}}},{name:"auth_delete_user",description:"Remove one user from the connected sandbox's user store.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to remove."}},required:["uid"]},async execute(n){const r=At(n),s=Rs(r,"auth_delete_user");if(typeof s!="string")return s;try{return ve.deleteUser(await t(),s),{ok:!0,summary:`Deleted user ${s}`,data:{uid:s}}}catch(i){return or(i)}}},{name:"auth_set_claims",description:"Replace one user's custom claims. Rules read them as request.auth.token.<name> on the next sign-in or token refresh. An empty object clears them.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},claims:za},required:["uid","claims"]},async execute(n){const r=At(n),s=Rs(r,"auth_set_claims");if(typeof s!="string")return s;if(!qs(r.claims))return Dt("auth/argument-error","auth_set_claims: claims must be an object.");const i=r.claims;try{const o=ve.updateUser(await t(),s,{customClaims:i});return{ok:!0,summary:`Set claims on user ${s}`,data:{user:ir(o)}}}catch(o){return or(o)}}},{name:"auth_custom_token",description:"Mint a custom token for a uid that the sandbox's signInWithCustomToken accepts. The sandbox has no signing key, so the token is unsigned and is only good against this sandbox.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user the token signs in."},claims:za},required:["uid"]},async execute(n){const r=At(n),s=Rs(r,"auth_custom_token");if(typeof s!="string")return s;const i=r.claims;return i!==void 0&&!qs(i)?Dt("auth/argument-error","auth_custom_token: claims must be an object."):{ok:!0,summary:`Minted custom token for ${s}`,data:{uid:s,claims:i??{},token:p$(s,i)}}}}]}const b$={"firestore-simulator":({env:e})=>Ix({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>$R({resolveDb:e}),"firestore-inspect":({sandbox:e})=>PR({resolveSandbox:()=>e}),"messaging-inspection":({sandbox:e})=>Z0(()=>e),"rtdb-inspection":({sandbox:e})=>h$({resolveSandbox:()=>e}),"auth-users":({sandbox:e})=>g$({resolveSandbox:()=>e})};function w$(e,t){return t==="admin"?vc(e):Js(e.withAuth(Dy(t.uid,t.tenant,t.claims)))}function v$(e,t){return t===void 0||t.mode==="app-session"||t.mode==="admin"?vc(e):t.mode==="anon"?Js(e.withAuth(null)):Js(e.withAuth({uid:t.uid,...t.token!==void 0?{token:t.token}:{},...t.tenant!==void 0?{tenant:t.tenant}:{}}))}function x$(e,t){const n={sandbox:e,env:Xr(e),resolveDb:r=>r!==void 0?w$(e,r):v$(e,t)};return Ty("forwarded").flatMap(r=>b$[r.key](n))}function _$(e){return e===void 0||e.mode==="app-session"?"app-session":e.mode==="admin"||e.mode==="anon"?e.mode:JSON.stringify([e.uid,e.tenant??null,e.token??null])}const S$=16;function k$(e){const t=new Map;function n(r){const s=_$(r),i=t.get(s);if(i)return i;const o=x$(e,r);F0("sandbox dispatcher tools",o.map(l=>l.name),ag);const a=new Map(o.map(l=>[l.name,l]));if(t.size>=S$)for(const l of[...t.keys()])l!=="app-session"&&t.delete(l);return t.set(s,a),a}return n(void 0),async(r,s,i)=>{const o=n(i).get(r);if(!o)throw new j$(r);const a={signal:new AbortController().signal},l=await o.execute(s,a);return{ok:l.ok,summary:l.summary,data:l.data}}}const hf=new WeakMap;async function E$(e,t,n,r){let s=hf.get(e);return s||(s=k$(e),hf.set(e,s)),s(t,n,r)}const ag=Ty("forwarded").flatMap(e=>Object.keys(e.tools));class j$ extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}function C$(e){if(e!==void 0&&e.length>0)return e;if(typeof window<"u"){const r=window;if("__PYRIC_BRIDGE_URL__"in r){const l=r.__PYRIC_BRIDGE_URL__;if(typeof l=="string"&&l.length>0)return l}const i=r.location.hostname||"localhost";return`${r.location.protocol==="https:"?"wss:":"ws:"}//${i}:${xd}${_d}`}return`ws://localhost:${xd}${_d}`}function R$(e){try{const t=new URL(e),n=t.protocol==="wss:";return t.protocol=n?"https:":"http:",[`${t.origin}/__pyric/health`,`${t.origin}/health`]}catch{return[]}}const N$={op:!0,sub:!0,unsub:!0,disconnect:!0,appConfig:!0,"clock-subscribe":!0,tool:!0};function Dn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function I$(e){return!Dn(e)||!(typeof e.t=="string"&&Object.hasOwn(N$,e.t))?!1:e.t==="op"||e.t==="tool"||e.t==="disconnect"?typeof e.id=="string":e.t==="sub"||e.t==="unsub"?typeof e.subId=="string":!0}function A$(e){return Dn(e)?typeof e.method=="string":!1}function O$(e){if(!Dn(e))return!1;const n=typeof e.target=="string",r=Dn(e.target);return n||r}function pf(e){if(!Dn(e))return!1;switch(e.mode){case"admin":case"anon":case"app-session":return!0;case"as":try{return Iv(e),!0}catch{return!1}default:return!1}}function mf(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function $$(e){if("clientSessionId"in e&&e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return"Invalid bridge client session ID.";switch(e.type){case"hello":{const n=!mf(e.tools),r=typeof e.sandboxId!="string",s=e.capabilities===void 0||mf(e.capabilities);return n||r||!s?"Invalid sandbox peer handshake.":void 0}case"hello-ack":return typeof e.bridgeVersion!="string"?"Invalid sandbox peer acknowledgement.":void 0;case"tool-call":{const n=typeof e.id=="string",r=typeof e.name=="string",s=Dn(e.args),i=e.callerId===void 0||typeof e.callerId=="string",o=e.actAs===void 0||pf(e.actAs);return!n||!r||!s||!i||!o?"Invalid sandbox tool call envelope.":void 0}case"worker-client-disconnect":case"worker-client-interrupted":return typeof e.clientSessionId=="string"?void 0:"Invalid bridge client session ID.";case"ping":case"pong":return typeof e.id!="string"?"Invalid bridge heartbeat ID.":void 0;case"remote-set-lens":{const n=typeof e.clientSessionId=="string",r=e.id===void 0||typeof e.id=="string",s=pf(e.lens);return!n||!r||!s?"Invalid remote identity lens envelope.":void 0}case"worker-message":return I$(e.message)?void 0:"Invalid worker message envelope.";case"worker-op":{const n=typeof e.id=="string",r=A$(e.op);return!n||!r?"Invalid worker relay operation envelope.":void 0}case"worker-sub":{const n=typeof e.subId=="string",r=O$(e.sub);return!n||!r?"Invalid worker relay subscription envelope.":void 0}case"worker-unsub":return typeof e.subId!="string"?"Invalid worker relay unsubscribe envelope.":void 0;default:return}}const P$=new Set(["hello-ack","tool-call","worker-op","worker-sub","worker-unsub","worker-client-disconnect","ping"]),D$=new TextEncoder,T$=500,M$=3e4,L$=2e3,U$=.5,B$=3;function F$(e,t={}){const n=C$(t.url),r=t.sandboxId??q$(),s=t.dispatcher??E$,i=t.toolNames??[...ag],o=t.initialReconnectDelayMs??T$,a=t.maxReconnectDelayMs??M$,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??L$,h=t.fetchImpl??(I=>fetch(I)),f=t.workerRelay??null;let p=null,m=!1,g=0,b=null,w=null,x=0,v={kind:"connecting"};const _=new Map;function S(){for(const I of _.values())try{I()}catch{}_.clear()}function k(I){v=I;try{u(I)}catch{}}function R(I){const M=p;if(M!==null&&M.readyState===WebSocket.OPEN)try{const F=Py(I);if(F===void 0){M.close(Da,Wr);return}M.send(F)}catch{}}function O(){if(m)return;k({kind:"connecting"});let I;try{I=new WebSocket(n)}catch(M){const F=M instanceof Error?M.message:String(M);N(`failed to open WebSocket: ${F}`);return}p=I,I.onopen=()=>{g=0;const M={type:"hello",protocol:1,tools:i,sandboxId:r};f!==null&&(M.capabilities=[yN]),R(M)},I.onmessage=M=>{const T=M.data,F=typeof T=="string";if(F&&D$.encode(T).byteLength>Ur){I.close(Da,Wr);return}let V;try{V=JSON.parse(F?T:"")}catch{I.close(4002,"Invalid bridge message JSON.");return}const B=V;if(!qm(B)){I.close(4002,"Unrecognized bridge message envelope.");return}if(!P$.has(B.type))return;const Rt=$$(B);if(Rt!==void 0){I.close(4002,Rt);return}if(B.type==="hello-ack"){if(B.protocol!==1){const we="Unsupported bridge protocol. Expected version 1.";m=!0,k({kind:"disconnected",reason:we}),I.close(1e3,we);return}k({kind:"connected",bridgeVersion:B.bridgeVersion});return}if(B.type==="tool-call"){P(B);return}if(B.type==="worker-op"){A(B);return}if(B.type==="worker-sub"){E(B);return}if(B.type==="worker-unsub"){const be=_.get(B.subId);if(be!==void 0){_.delete(B.subId);try{be()}catch{}}return}if(B.type==="worker-client-disconnect"){f?.disconnect?.(B.clientSessionId);return}if(B.type==="ping"){R({type:"pong",id:B.id});return}},I.onclose=M=>{const T=M.reason||`closed (code ${M.code})`;if(p=null,S(),M.code===mN){m=!0,console.error(`[pyric] ${T}`),k({kind:"disconnected",reason:T});return}if(M.code===pN){j();return}N(T)},I.onerror=()=>{}}async function P(I){let M;try{const T=await s(e,I.name,I.args??{},I.actAs,I.callerId);M={type:"tool-result",id:I.id,ok:!0,result:T}}catch(T){const F=T instanceof Error;M={type:"tool-result",id:I.id,ok:!1,error:{code:F?T.name:"Error",message:F?T.message:String(T)}}}R(M)}async function A(I){if(f!==null)try{const T=await f.op(I.op,I.clientSessionId);kd(`op '${I.op.method}'`,T),R({type:"worker-res",id:I.id,clientSessionId:I.clientSessionId,ok:!0,value:T})}catch(T){const F=T.denialContext,U=T instanceof Error,V={code:T.code??"unknown",message:U?T.message:String(T)};F!==void 0&&(V.denialContext=F),R({type:"worker-res",id:I.id,clientSessionId:I.clientSessionId,ok:!1,error:V})}}function E(I){if(!(f===null||_.has(I.subId)))try{const F=f.subscribe(I.sub,U=>{try{kd(`subscription '${I.subId}'`,U)}catch(V){const B=V instanceof Error;R({type:"worker-snap",subId:I.subId,clientSessionId:I.clientSessionId,value:{__error:{code:V.code??"invalid-argument",message:B?V.message:String(V)}}});return}R({type:"worker-snap",subId:I.subId,clientSessionId:I.clientSessionId,value:U})},I.clientSessionId);_.set(I.subId,F)}catch(F){const U=F.denialContext,V=F instanceof Error,B={code:F.code??"unknown",message:V?F.message:String(F)};U!==void 0&&(B.denialContext=U),R({type:"worker-snap",subId:I.subId,clientSessionId:I.clientSessionId,value:{__error:B}})}}function j(){if(!m){if(l){k({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,x=0,k({kind:"standby"}),$()}}function $(){if(m)return;const I=d*(1+Math.random()*U$);w=setTimeout(()=>{w=null,C()},I)}async function C(){if(m)return;let I=null;for(const U of R$(n))try{const V=await h(U);if(!V.ok)continue;const _e=await V.json();if(typeof _e.sandboxConnected=="boolean"){I=!_e.sandboxConnected;break}}catch{}if(m)return;if(I===!0){O();return}if(I===!1){x=0,$();return}if(x+=1,x>=B$){N("standby health poll unreachable");return}$()}function N(I){if(m)return;if(l){k({kind:"disconnected",reason:I});return}g+=1;const M=Math.min(o*2**(g-1),a);k({kind:"reconnecting",attempt:g,delayMs:M}),b=setTimeout(()=>{b=null,O()},M)}return O(),{disconnect(){m=!0,S();const I=b;I!==null&&(clearTimeout(I),b=null);const T=w;T!==null&&(clearTimeout(T),w=null);const U=p;if(U!==null){try{U.close()}catch{}p=null}k({kind:"disconnected",reason:"client closed"})},state(){return v}}}function q$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function cg(e,t,n="bridge-port"){try{const r=new URL(e,t.href),s=new URL(t.href),i=t.protocol==="https:"?"wss:":"ws:",o=s.port.length>0,a=r.port.length>0,d=n==="bridge-port"&&o&&a?`${s.hostname}:${r.port}`:s.host;return`${i}//${d}${r.pathname}`}catch{return e}}function V$(e,t){return{url:t,dispatcher:(n,r,s,i)=>mI(e,r,s,i),workerRelay:{op:n=>yI(e,n),subscribe:(n,r)=>gI(e,n,r)}}}async function W$(e,t={}){const n=t.baseUrl??"",r=t.fetchImpl??(typeof fetch<"u"?fetch:null),s=u=>t.onStateChange?.({kind:"disconnected",reason:u});if(!r)return s("no fetch available"),null;let i;try{const u=await r(`${n}/__pyric/init.json`);if(!u.ok)return s("not served"),null;i=(await u.json()).bridgeUrl??null}catch{return s("not served"),null}if(!i)return s("bridge off"),null;const o=t.locationLike??(typeof window<"u"?window.location:null),a=o?cg(i,o):i,l=F$(null,{...V$(e,a),...t.onStateChange?{onStateChange:t.onStateChange}:{},...t.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:t.initialReconnectDelayMs}:{},...t.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:t.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",a),l}const z$={};function H$(){return!1}function K$(){let e={kind:"connecting"};const t=new Set;return{get:()=>e,subscribe(n){return t.add(n),()=>t.delete(n)},set(n){e=n;for(const r of t)r()}}}function G$(e,t={}){if(e==="local"){const r=t.baseUrl??"",s=H$(),o=t.persistence==="memory"||s?Av():qR(r),l=t.disableLive===!0?null:C0(t.workerUrl),d=l!==null&&l.runtime.getSnapshot().mode!=="hosted"?K$():null;let h=!1,f=null;l!==null&&d!==null&&W$(l.db,{baseUrl:r,onStateChange:x=>d.set(x)}).then(x=>{h?x?.disconnect():f=x});const m={mode:e,projects:s?zR():BR(r),persistence:o,dispose(){h=!0,f?.disconnect(),l?.dispose()}},g=l!==null,b=d!==null;return g&&(m.live=l),b&&(m.bridge=d),!s&&(m.workspace=Mm(r)),m}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const lg=y.createContext(null),J$={status:"pending",env:null,error:null};function Y$(e){try{return{status:"ready",env:G$(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function Q$({mode:e="local",children:t}){const[n,r]=y.useState(null);y.useEffect(()=>{const i=Y$(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:J$;return c.jsx(lg.Provider,{value:s,children:t})}function ot(){const e=y.useContext(lg);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const X$="pyric-studio:theme",Vs="dark";function Z$(){return Vs}function eP(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const tP=y.createContext(null);function nP({children:e}){const[t,n]=y.useState(Z$);y.useEffect(()=>{eP();try{localStorage.setItem(X$,Vs)}catch{}},[t]);const r="dark",s=y.useCallback(a=>n(Vs),[]),i=y.useCallback(()=>n(Vs),[]),o=y.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return c.jsx(tP.Provider,{value:o,children:e})}function qi(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function rP(e){const t={};for(const n of e.replace(/^\?/,"").split("&")){if(!n)continue;const r=n.indexOf("="),s=r===-1?n:n.slice(0,r),i=r===-1?"":n.slice(r+1);s&&(t[decodeURIComponent(s)]=decodeURIComponent(i))}return t}function ol(e,t="",n=qi()){let r=e;const s=n.replace(/\/$/,"");n!=="/"&&(e===s||e.startsWith(n))&&(r=e.slice(s.length));const i=r.split("/").filter(Boolean).map(l=>decodeURIComponent(l)),[o="",...a]=i;return{tab:o,rest:a,query:rP(t)}}function sP(e,t=qi()){const n=[e.tab,...e.rest??[]].filter(s=>s!=null&&s!=="").map(s=>encodeURIComponent(s)).join("/"),r=Object.entries(e.query??{}).filter(([,s])=>s!=null&&s!=="").map(([s,i])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(i))}`).join("&");return`${t}${n}${r?`?${r}`:""}`}const ug="studio",iP=[{id:"home",label:"Studio",description:"What is happening in the sandbox, and where to go next."},{id:"firestore",label:"Firestore",description:"Browse and edit collections, documents, and references."},{id:"auth",label:"Auth",description:"View and edit users, claims, providers, and account state."},{id:"rtdb",label:"RTDB",description:"Browse and edit RTDB data in the shared sandbox."},{id:"storage",label:"Storage",description:"Browse buckets, inspect objects, upload, and delete files."},{id:"traffic",label:"Traffic",description:"Watch sandbox requests, listener activity, and rule decisions."},{id:"assurance",label:"Assurance",description:"Compare intended access with qualified local sandbox behavior."},{id:"settings",label:"Settings",description:"Configure models, keys, theme, sandbox maintenance, and diagnostics."}];function oP({assuranceEnabled:e=!1}={}){return iP.filter(t=>t.id!=="assurance"||e)}const un=oP({assuranceEnabled:!1}),aP=un.map(e=>e.id);function cP(e){return un.find(t=>t.id===e)??un[0]}const Ka="pyric:studio:navigated",lP={tab:"",rest:[],query:{}};function al(){return typeof window<"u"?window.location.pathname+window.location.search:""}function uP(e){return e===""||e===ug?"home":e}function He(){if(typeof window>"u")return lP;const e=ol(window.location.pathname,window.location.search);return{...e,tab:uP(e.tab)}}function dP(e){return e.tab==="home"?{...e,tab:ug}:e}function kt(e){return sP(dP(e))}function dg(){typeof window<"u"&&window.dispatchEvent(new Event(Ka))}function Ie(e){if(typeof window>"u")return;const t=kt(e);al()!==t&&(window.history.pushState(null,"",t),dg())}function Hr(e){typeof window>"u"||(window.history.replaceState(null,"",kt(e)),dg())}function Kt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Ka,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Ka,e)})}function fP(e,t){const n=y.useCallback(i=>e.includes(i)?i:t,[e,t]),r=y.useSyncExternalStore(Kt,()=>n(He().tab),()=>t);y.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const a=i.slice(1),l=a.indexOf("?"),u=ol(`/${l===-1?a:a.slice(0,l)}`,l===-1?"":a.slice(l),"/");if(e.includes(u.tab)){Hr(u);return}}const o=He();e.includes(o.tab)||Hr({tab:n(o.tab)})},[n]);const s=y.useCallback(i=>{const o=n(i);o!==r&&Ie({tab:o})},[n,r]);return[r,s]}let Ga=null;function hP(e){Ga=e}function pP(){return Ga?(Ga(),!0):!1}function mP(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function yP(e,t){const n=e.toLowerCase(),r=t.toLowerCase();let s=0;for(const i of r)if(i===n[s]&&s++,s===n.length)return!0;return s===n.length}const gP=7;function bP(e,t){const n=e.trim();if(!n)return[];const r=t.filter(h=>h.id!=="settings"),s=[],i=[],o=[],[a="",...l]=n.split(/\s+/),u=l.join(" ");for(const h of r){const f={id:`tab:${h.id}`,label:`Go to ${h.label}`,hint:h.description,target:{tab:h.id}},p=h.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):yP(n,h.label)&&i.push(f),u&&(p===a.toLowerCase()||p.startsWith(a.toLowerCase()))){const m=u.split("/").filter(Boolean);h.id==="firestore"||h.id==="storage"?o.push({id:`deep:${h.id}:${u}`,label:`Open /${m.join("/")} in ${h.label}`,hint:h.id==="firestore"?"Firestore path":"Storage object path",target:{tab:h.id,rest:m}}):h.id==="auth"?o.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):h.id==="traffic"&&o.push({id:`deep:traffic:${u}`,label:`Open ${u} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:u}}})}}const d=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(d){const h=d[1].split("/").filter(Boolean);o.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:h}})}else if(n.includes("/")&&!n.includes(" ")){const h=n.split("/").filter(Boolean);h.length&&o.push({id:`deep:firestore:${n}`,label:`Open /${h.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:h}})}return[...s,...o,...i].slice(0,gP)}function Ja(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const Ya={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function wP(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let o=0;for(;i.length&&s.length<n&&o<r;){o++;const a=await t(i.shift());for(const l of a.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...a.prefixes)}return s}async function vP(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const o=[],a=[],l=[...e];let u=0;for(;l.length&&o.length<r&&u<s;){const d=l.shift();u++;let h=[];try{h=await t(d)}catch{continue}for(const f of h){if(o.length>=r)break;const p=`${d}/${f}`;o.push(p);try{const m=await n(p,i);for(const g of m.slice(0,i))a.push(g),l.push(g)}catch{}}}return{subcollections:o,documents:a}}const xP=5;function wi(e,t){const n=e.toLowerCase(),r=t.toLowerCase();if(!n||!r)return 0;if(r===n)return 1e3;if(r.startsWith(n))return 900-Math.min(r.length-n.length,100);const s=r.indexOf(n);if(s!==-1)return 700-Math.min(s,100);let i=0,o=-1,a=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(o===-1&&(o=u),a=u,i++);if(i!==n.length)return 0;const l=a-o+1;return Math.max(1,400-(l-n.length)*10-Math.min(o,50))}const _P={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},SP=["collection","document","subcollection","user","object","rtdb-key"];function kP(e){switch(e.kind){case"collection":return"Firestore collection";case"document":return"Firestore document";case"subcollection":return e.alt?`Subcollection of /${e.alt}`:"Subcollection";case"user":return e.alt?`Auth user · uid ${e.alt}`:"Auth user";case"object":return"Storage object";case"rtdb-key":return"RTDB top-level key"}}function fg(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function EP(e,t){const{base:n,trailing:r}=fg(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const o=s.length-1;for(let a=0;a<o;a++)if(s[a].toLowerCase()!==i[a].toLowerCase())return 0;return r?s[o].toLowerCase()===i[o].toLowerCase()?850:0:wi(s[o],i[o])}function jP(e,t){const{base:n,trailing:r}=fg(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:wi(n,s)}function yf(e,t,n,r=xP){const s=e.trim();if(!s)return[];const i=[],o=bP(e,t);o.length&&i.push({kind:"navigate",title:"Go to",results:o});for(const a of SP){const l=a==="document"||a==="subcollection",u=a==="collection"||a==="subcollection",d=new Map;for(const f of n)f.kind===a&&d.set(Ja(f),f);const h=[...d.values()].map(f=>({entry:f,score:Math.max(wi(s,f.label),f.alt?wi(s,f.alt):0,l?EP(s,f.label):0,u?jP(s,f.label):0)})).filter(f=>f.score>0).sort((f,p)=>p.score-f.score||f.entry.label.localeCompare(p.entry.label)).slice(0,r);h.length&&i.push({kind:a,title:_P[a],results:h.map(({entry:f})=>({id:Ja(f),label:f.label,hint:kP(f),target:f.target}))})}return i}function gf(e){return e.flatMap(t=>t.results)}function CP(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function bf(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function RP(e){const t=e.split("/").filter(Boolean),n=t.slice(0,-1).join("/");return{kind:"subcollection",label:e,alt:n||void 0,target:{tab:"firestore",rest:t}}}function NP(e){return e.email?{kind:"user",label:e.email,alt:e.uid,target:{tab:"auth",rest:[e.uid]}}:{kind:"user",label:e.uid,target:{tab:"auth",rest:[e.uid]}}}function IP(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function AP(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function OP(e,t={},n){const r={...Ya,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},o=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(CP));const h=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const m=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);h.push(...m),i(m.map(bf))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await vP(h,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(RP)),i(p.map(bf))}catch{}})(),a=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(NP))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(IP))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(AP))}catch{}})();return await Promise.allSettled([o,a,l,u]),s}function $P(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return rN(r,e),r}const PP=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function DP(e){return $h(e.withAuth(null),PP)}const TP="pyric-studio";function hg(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let MP=0;function LP(e){const t=$P(e,{projectId:"pyric-studio"},`pyric-studio-${MP++}`),n=Xr(e),r=DP(e);return{sandbox:e,app:t,firestore:Js(e),adminFirestore:vc(r),auth:Mc(e),storage:nj(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>hg(n,s)}}function UP(e,t){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useMemo(()=>Qv(),[]),a=y.useMemo(()=>{try{return LP(o)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[o]);return y.useEffect(()=>{let u=!1;if(!e){r(!1);return}return o.enablePersistence({key:TP,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[o,e]),s?{status:"error",handles:null,error:s}:a?e!=null&&n||t==="ready"?{status:"ready",handles:a}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function BP(e){const t=Xr(e.sandbox);return{sandbox:e.sandbox,app:e.app,firestore:e.firestore,adminFirestore:e.adminFirestore,auth:e.auth,storage:e.storage,listRootCollections:()=>t.listRootCollections(),listSubcollections:n=>t.listSubcollections(n),listDocuments:n=>hg(t,n)}}function Ct(){const e=Ht(),t=ot(),n=t.status==="ready"?t.env.persistence:void 0,r=UP(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=FP(s);return y.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:BP(e.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:e.error};case"disabled":{if(s&&r.status==="ready"){const o=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:o,adminFirestore:o,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:a=>s.listSubcollections(a),listDocuments:a=>s.listDocuments(a)}}}return r}}},[e,r,s,i])}function FP(e){const[t,n]=y.useState([]);return y.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(o=>{r&&n(o)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}function qP(e){let t=!0;return n=>{const r=t;t=!1,e(s=>WP(s,n,r))}}function VP(e){const t=new Map;for(const n of e)t.set(Ja(n),n);return[...t.values()]}function WP(e,t,n){return VP(n?t:[...e??[],...t])}const zP=3e4;function pg(){const e=Ct(),t=ot(),[n,r]=y.useState(null),[s,i]=y.useState(!1),o=y.useRef(!1),a=y.useRef(e);a.current=e;const l=t.status==="ready"?t.env.live:void 0,u=y.useRef(l);u.current=l;const d=y.useRef(null),h=y.useRef(0),f=y.useRef(null),p=y.useRef(0),m=y.useCallback(b=>{const w=a.current;if(w.status!=="ready")return;const x=++h.current;o.current=!0,i(!0);const v=w.handles,_=v.adminFirestore,S=w.firestoreApi?.collection??pr,k=w.firestoreApi?.query??pi,R=w.firestoreApi?.getDocs??hi,O=w.firestoreApi?.limit??mi,P=w.storageApi?.ref??Pr,A=w.storageApi?.listAll??Gc,E=w.authApi?.listUsers??ve.listUsers,j={listRootCollections:()=>v.listRootCollections(),listDocumentPaths:async(C,N)=>(await R(k(S(_,C),O(N)))).docs.slice(0,N).map(M=>`${C}/${M.id}`),listSubcollections:C=>Promise.resolve(v.listSubcollections(C)),listUsers:async C=>(await Promise.resolve(E(v.auth))).slice(0,C).map(I=>({uid:I.uid,email:I.email??null})),listStorageObjectPaths:C=>wP(P(v.storage,""),A,{maxObjects:C,maxListCalls:Ya.storageListCalls}),listRtdbTopLevelKeys:async()=>{const C=u.current;if(!C)return[];const N=Date.now()-p.current<zP;if(f.current!==null&&N&&!b?.rtdbLikely)return f.current;const I=await C.readRtdbState(),M=I===null||typeof I!="object"||Array.isArray(I)?[]:Object.keys(I);return f.current=M,p.current=Date.now(),M}},$=qP(C=>r(C));OP(j,Ya,C=>{x===h.current&&$(C)}).catch(()=>{}).finally(()=>{if(x===h.current&&(o.current=!1,i(!1),r(C=>C??[]),d.current)){const C=d.current;d.current=null,m(C)}})},[]),g=y.useCallback(b=>{if(a.current.status==="ready"){if(o.current){d.current={...d.current,...b};return}m(b)}},[m]);return y.useEffect(()=>{e.status==="ready"&&n===null&&!o.current&&m()},[e,n,m]),{entries:n,building:s,ensure:g}}const HP=150;function KP(e){return e.startsWith("/")||/rtdb/i.test(e)}function mg({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=y.useState(""),[o,a]=y.useState(""),[l,u]=y.useState(0),[d,h]=y.useState(!1),f=y.useRef(null),{entries:p,building:m,ensure:g}=pg();y.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),y.useEffect(()=>{e&&f.current?.focus()},[e]),y.useEffect(()=>{const S=setTimeout(()=>a(s),HP);return()=>clearTimeout(S)},[s]);const b=y.useMemo(()=>yf(o,un,p??[]),[o,p]),w=y.useMemo(()=>gf(b),[b]);y.useEffect(()=>{u(S=>w.length===0?0:Math.min(S,w.length-1))},[w.length]);const x=S=>{S&&(i(""),a(""),h(!1),Ie(S.target),t?.(S.target))},v=()=>{if(s===o){x(w[l]??w[0]);return}const S=gf(yf(s,un,p??[]));x(S[0])};let _=0;return c.jsxs("div",{className:"studio-home__command",children:[c.jsx("div",{className:"studio-home__command-row",children:c.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&w.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),h(!0)},onBlur:()=>h(!1),onChange:S=>{const k=S.target.value;i(k),h(!0),KP(k)&&g({rtdbLikely:!0})},onKeyDown:S=>{if(S.key==="ArrowDown")S.preventDefault(),u(k=>Math.min(k+1,Math.max(w.length-1,0)));else if(S.key==="ArrowUp")S.preventDefault(),u(k=>Math.max(k-1,0));else if(S.key==="Enter")v();else if(S.key==="Escape"){if(n){n();return}i(""),a(""),h(!1)}}})}),d&&!b.length&&m&&p===null?c.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:c.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&b.length?c.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:S=>S.preventDefault(),children:b.map(S=>{const k=_;return _+=S.results.length,c.jsxs("div",{className:"studio-home__command-group",children:[c.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:S.title}),c.jsx("ul",{className:"studio-home__command-group-list",children:S.results.map((R,O)=>{const P=k+O;return c.jsx("li",{children:c.jsxs("button",{type:"button",role:"option","aria-selected":P===l,className:"studio-home__command-result","data-active":P===l?"true":void 0,onMouseEnter:()=>u(P),onClick:()=>x(R),children:[c.jsx("span",{className:"studio-home__command-label",children:R.label}),c.jsx("span",{className:"studio-home__command-sub",children:R.hint})]})},R.id)})})]},S.kind)})}):null]})}function GP({onClose:e}){const t=y.useRef(null);return y.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),y.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),c.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:c.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:c.jsx(mg,{autoFocus:!0,onEscape:e,onNavigated:e})})})}function cl(e){if(e.result==="allow")return!1;const t=e.queryProof?.kind;return t==="unsupported-predicate"||t==="unsupported-path"}function JP(e){if(e.kind==="listener")return e.phase==="errored"&&(e.result==="deny"||e.result==="unsupported"||e.result==="allow"||e.error?.code==="PERMISSION_DENIED");const t=zh(e);return t?t.rules.kind==="evaluated":!1}function YP(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function QP(e){if(!("request"in e))return;const t=e.request;if(t){if("resourceData"in t&&t.resourceData!==void 0)return t.resourceData;if("data"in t)return t.data}}function XP(e){if(!("request"in e)||!e.request)return;const n=e.request.updateMask;return Array.isArray(n)&&n.every(s=>Array.isArray(s)&&s.every(i=>typeof i=="string"))?n:void 0}function ZP(e,t){const n=[];for(const r of e){if(r.origin==="listener"&&!r.rules){let s;for(const i of t)if(i.kind==="operation"&&i.method==="listen"&&i.path===r.path&&i.rules){s=i;break}s&&(s.rules&&(r.rules=s.rules),s.reasons&&r.reasons.length===0&&(r.reasons=s.reasons))}n.push(r)}return n}function eD(e){const t=[];for(const r of e)JP(r)&&t.push(tD(r));return ZP(t,e).sort((r,s)=>s.at-r.at)}function tD(e){let t="listen",n="(service)",r="listener";e.kind==="request"||e.kind==="operation"?(t=e.method,e.path!==void 0&&(n=e.path),r=e.origin):e.kind==="listener"&&(t="listen",e.target.path!==void 0&&(n=e.target.path),r="listener");let s="deny";e.result==="allow"?s="allow":e.result==="unsupported"&&(s="unsupported");const i={id:e.id,at:e.at,result:s,method:t,service:YP(e),path:n,auth:e.auth,reasons:e.reasons??[],origin:r,unsupported:s==="unsupported"};"matchedRule"in e&&e.matchedRule&&(i.matchedRule=e.matchedRule),"evaluatedRule"in e&&e.evaluatedRule&&(i.evaluatedRule=e.evaluatedRule),"queryProof"in e&&e.queryProof&&(i.queryProof=e.queryProof),"rules"in e&&e.rules&&(i.rules=e.rules);const o=QP(e);o!==void 0&&(i.resourceData=o);const a=XP(e);return a!==void 0&&(i.updateMask=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const wf=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function nD(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function rD(e){return e==="Validation rule evaluated to false"||!!e?.startsWith("Validation rule at '")}function yg(e){if(rD(e.rules?.reason))return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function sD(e,t){const n=e.rules?.matchedPath;if(!(!t||!n||e.rules?.errorCode==="NO_MATCHING_RULE"))return UO(t,n,`.${yg(e)}`)?.line}function ll(e){if(e.result!=="allow")return e.queryProof?.failures.find(t=>t.kind===e.queryProof?.kind)}function iD(e){const t=nD(e),n=e.reasons.filter(i=>wf.test(i)),r=e.reasons.filter(i=>!wf.test(i)),s=ll(e);if(s)return{headline:cl(e)?`Query proof unsupported: Pyric could not prove ${e.method} ${e.path} safe. This does not establish Firebase's decision.`:`The query constraints do not satisfy the list rule for ${e.path}.`,engine:t,ruleNode:s.rule?.citation??"list rule",ruleExpression:s.rule?.expression,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${e.method} ${e.path}.`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.result==="allow"){if(t==="firestore"&&e.matchedRule){const o=e.matchedRule,a=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`;return{headline:`${a} allowed ${e.method} on ${e.path}.`,engine:t,ruleNode:a,ruleLines:n,otherLines:r,implicitDeny:!1}}return!e.matchedRule&&!e.rules&&!e.evaluatedRule&&n.length===0?{headline:`This ${e.method} on ${e.path} succeeded, but no rules evaluation was recorded for it — rules likely never ran (an admin/bypass operation from a worker that didn't stamp its lens, or a pre-provenance event).`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${e.method} on ${e.path}.`,engine:t,...e.rules?.matchedRule?{ruleExpression:e.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return t==="rtdb"?aD(e,n,r):t==="storage"?cD(e,n,r):oD(e,n,r)}function oD(e,t,n){const r=!e.matchedRule;let s,i;if(r)s=`No rule allowed ${e.method} on ${e.path}: implicit deny (no matching \`allow\`).`;else{const o=e.matchedRule;i=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function aD(e,t,n){const r=e.rules,s=yg(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",o=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let a,l;return i?a=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,a=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,a=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:a,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:o,ruleLines:t,otherLines:n,implicitDeny:i}}function cD(e,t,n){const r=e.reasons.find(a=>/^match\s/.test(a)),i=e.reasons.some(a=>/^no rule matches/.test(a))||!r;return{headline:i?`No \`match\` block allowed ${e.method} on ${e.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${e.method} on ${e.path}.`,engine:"storage",ruleNode:i?void 0:r,ruleLines:t,otherLines:n,implicitDeny:i}}function lD(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function uD(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:lD(s),...s.value!==void 0?{value:s.value}:{},...s.error!==void 0?{error:s.error}:{},...s.letBinding?{letBinding:s.letBinding.name}:{},...s.inlinedFrom?{inlinedFrom:s.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return t.forEach((s,i)=>{s.parent===null||s.parent===void 0||!n[s.parent]?r.push(n[i]):(n[i].depth=n[s.parent].depth+1,n[s.parent].children.push(n[i]))}),r}const dD={ALLOW:"true",DENY:"false",ERROR:"error",UNSUPPORTED:"unsupported"};function fD(e,t){const n=e.rules?.rtdbTrace;return!n||n.length===0?[]:(t===void 0?[...n]:Jy(t,n)).map(s=>{const i={source:s.conditionText,outcome:dD[s.verdict],...s.verdict==="ALLOW"||s.verdict==="DENY"?{value:s.verdict==="ALLOW"}:{},...s.message!==void 0?{error:s.message}:{},depth:0,children:[]},o={path:s.path,kind:s.kind,verdict:s.verdict,step:i,bindings:s.pathVariableBindings};return s.line!==void 0&&(o.line=s.line),o})}function hD(e){const t=[{name:"request.auth",present:e.auth!==null,value:e.auth,...e.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:e.method},{name:"request.path",present:!0,value:e.path}],n=e.method==="get"||e.method==="list"||e.method==="listen";return t.push({name:"request.resource.data",present:e.resourceData!==void 0,value:e.resourceData??null,...e.resourceData===void 0?{absentNote:n?"A read carries no proposed write, so request.resource.data is absent.":"No proposed write payload was captured for this denial."}:{}}),t.push({name:"resource",present:e.resourceBefore!==void 0,value:e.resourceBefore?{data:e.resourceBefore.data,exists:e.resourceBefore.exists}:null,...e.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),t}const kr=500;function Uo(e,t){if(e.length<=kr)return e;const n=e.slice(-kr);if(t==="recent")return n;const r=new Set(kc(e).map(i=>i.id));return[...e.slice(0,-kr).filter(i=>(i.kind==="listener_attach"||i.kind==="listener"&&i.phase==="attach")&&r.has(i.listenerId)),...n]}function Gt(e="recent"){const t=Ht(),n=ot(),r=n.status==="ready"?n.env.live?.feed:void 0,s=t.status==="ready",[i,o]=y.useState([]);y.useEffect(()=>{if(s||!r){o([]);return}return o(Uo(r.history(),e)),r.subscribe(u=>o(d=>Uo(MR(d,u),e)))},[s,r,e]);const a=y.useMemo(()=>s?Uo(t.events,e):[],[s,t,e]);return s?a:i}function pD(e){return Ov(e)}function mD(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function yD(e){const t=zh(e);if(!t)throw new Error("Studio traffic adapter received a non-operation event");if(e.kind==="request")return{...e,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const a=e.error;a!==void 0&&mD(a.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let o=[];if(e.reasons!==void 0)o=e.reasons;else{const a=e.error;a!==void 0&&a.reasons!==void 0&&(o=a.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:o,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}let n="(service)";e.path!==void 0&&(n=e.path);let r=[];return e.reasons!==void 0&&(r=e.reasons),{kind:"operation",service:e.service,id:e.id,at:e.at,durationMs:e.durationMs,method:e.method,path:n,auth:e.auth,result:e.result,reasons:r,request:e.request,resourceBefore:e.resourceBefore,resourceAfter:e.resourceAfter,origin:e.origin,groupId:e.groupId,groupKind:e.groupKind,triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}function gD(){const e=Gt();return y.useMemo(()=>e.filter(pD).map(yD),[e])}function bD(){const e=Gt();return y.useMemo(()=>eD(e),[e])}const wD={status:"loading",payload:null},Ns={status:"absent",payload:null};let vi=wD,vf=!1;const Qa=new Set;function Is(e){vi=e;for(const t of Qa)t()}function vD(){if(!vf){if(vf=!0,typeof fetch>"u"){vi=Ns;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Is(Ns);const n=await e.json();Is({status:"ready",payload:n})}).catch(()=>Is(Ns))}}function xD(e){return Qa.add(e),vD(),()=>Qa.delete(e)}function fs(){return y.useSyncExternalStore(xD,()=>vi,()=>vi)}function _D(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function SD(e,t){if(e!==200||typeof t!="object"||t===null)return{kind:"absent"};const n=t.sandboxConnected;return typeof n!="boolean"?{kind:"absent"}:{kind:"json",sandboxConnected:n}}async function kD(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?SD(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function ED(e=5e3){const[t,n]=y.useState("checking");return y.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=_D(await kD(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},o=()=>typeof document>"u"||document.visibilityState!=="hidden",a=()=>{s||(s=setInterval(()=>{o()&&i()},e))},l=()=>{o()&&i()};return i().then(u=>{r&&u!=="absent"&&a()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const jD="Only pages in this browser profile, on this origin, connected to this shared sandbox worker. Other profiles, incognito windows, origins, or worker names are not visible.";function CD(e,t){const n=Math.max(0,t-e);return n<5e3?"just now":n<6e4?`${Math.floor(n/1e3)}s ago`:n<36e5?`${Math.floor(n/6e4)}m ago`:`${Math.floor(n/36e5)}h ago`}function RD(e){return e==="studio"?"Studio":"App"}function ND(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(o=>({clientId:o.clientId,kindLabel:RD(o.kind),route:o.route||"/",visibilityLabel:o.visibility==="hidden"?"Hidden":"Visible",isThisPage:o.clientId===t,freshnessLabel:CD(o.lastSeen,n)}));s.sort((o,a)=>o.isThisPage!==a.isThisPage?o.isThisPage?-1:1:o.kindLabel!==a.kindLabel?o.kindLabel==="Studio"?-1:1:o.route.localeCompare(a.route));const i=s.filter(o=>!o.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:jD,otherCount:i}}function ID(){const e=ot(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=y.useState(null);return y.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(ND(i,s))})},[t]),n}const AD=new Set(["flutter","swift","ios","kotlin","android"]);function OD(e){const t=(e.platform||"").toLowerCase();return AD.has(t)}function $D(){const e=fs(),[t,n]=y.useState([]),[r,s]=y.useState(!1),i=y.useRef(null),o=y.useRef(new Map);return y.useEffect(()=>{if(e.status!=="ready"||!e.payload.bridgeUrl){s(!1),n([]);return}let l=!1,u=null,d=1e3;const h=typeof window<"u"?window.location:null,f=h?cg(e.payload.bridgeUrl,h):e.payload.bridgeUrl;function p(){if(!l)try{const m=new WebSocket(f);i.current=m,m.onopen=()=>{if(l){m.close();return}s(!0),d=1e3;try{m.send(JSON.stringify({type:"attach",protocol:1,clientInfo:{platform:"studio",deviceLabel:"Desktop Studio"}}))}catch{}},m.onmessage=g=>{if(!l)try{const b=JSON.parse(g.data);if(b.type==="consumer-presence"){const x=(b.consumers||[]).filter(OD);n(x)}else if(b.type==="remote-set-lens-ack"){const w=b;if(w.id&&o.current.has(w.id)){const x=o.current.get(w.id);o.current.delete(w.id),x?.(w.ok)}}}catch{}},m.onclose=()=>{i.current=null,!l&&(s(!1),u=setTimeout(()=>{d=Math.min(d*1.5,1e4),p()},d))},m.onerror=()=>{}}catch{s(!1)}}return p(),()=>{if(l=!0,u&&clearTimeout(u),i.current){try{i.current.close()}catch{}i.current=null}for(const m of o.current.values())m(!1);o.current.clear(),s(!1)}},[e]),{consumers:t,connected:r,setLens:async(l,u)=>{n(f=>f.map(p=>p.clientSessionId===l?{...p,activeLens:u,lastSeen:Date.now()}:p));const d=i.current;if(!d||d.readyState!==WebSocket.OPEN)return!1;const h=`lens-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;return new Promise(f=>{const p=setTimeout(()=>{o.current.delete(h),f(!0)},5e3);o.current.set(h,m=>{clearTimeout(p),f(m)});try{d.send(JSON.stringify({type:"remote-set-lens",id:h,clientSessionId:l,lens:u}))}catch{clearTimeout(p),o.current.delete(h),f(!1)}})}}}const PD={listUsers:ve.listUsers,subscribeUsers:ve.subscribeUsers,createUser:ve.createUser,updateUser:ve.updateUser,deleteUser:ve.deleteUser,clearUsers:ve.clearUsers,getAuthProviderConfig:ve.getAuthProviderConfig,setAuthProviderConfig:ve.setAuthProviderConfig,subscribeAuthProviderConfig:ve.subscribeAuthProviderConfig},gg=y.createContext(PD);function DD(){return y.useContext(gg)}function bg({value:e,children:t}){return y.createElement(gg.Provider,{value:e},t)}function TD(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Vi(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:o}=DD(),[a,l]=y.useState([]),[u,d]=y.useState(!0),[h,f]=y.useState(void 0),[p,m]=y.useState(""),g=y.useCallback(k=>{l(k),f(void 0),d(!1)},[]);y.useEffect(()=>{let k=!1;d(!0),f(void 0);const R=E=>{k||g(E)},O=E=>{k||(l([]),f(E instanceof Error?E:new Error(String(E))),d(!1))},P=()=>{try{const E=t(e);E&&typeof E.then=="function"?E.then(R).catch(O):R(E)}catch(E){O(E)}};let A;try{P(),A=n(e,P)}catch(E){O(E)}return()=>{k=!0,A?.()}},[e,t,n,g]);const b=y.useMemo(()=>{const k=p.trim().toLowerCase();return k?a.filter(R=>TD(R,k)):a},[a,p]),w=y.useCallback(k=>r(e,k),[e,r]),x=y.useCallback((k,R)=>s(e,k,R),[e,s]),v=y.useCallback(k=>i(e,k),[e,i]),_=y.useCallback(()=>o(e),[e,o]),S=y.useCallback(()=>{const k=t(e);k&&typeof k.then=="function"?k.then(g).catch(()=>{}):g(k)},[e,t,g]);return{users:b,totalCount:a.length,isLoading:u,error:h,filter:p,setFilter:m,createUser:w,updateUser:x,deleteUser:v,clearUsers:_,refresh:S}}const MD=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],LD=1e3;function wg(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>LD)return{ok:!1,message:"Custom claims length must not exceed 1000 characters"};let n;try{n=JSON.parse(t)}catch{return{ok:!1,message:"Custom claims must be a valid JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,message:"Custom claims must be a valid JSON object"};for(const r of MD)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const UD={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},BD=new Set(["password","anonymous","phone"]),FD=/^[^@]+@[^@]+\.[^@]+$/,xf=6;function qD(e){return e?{email:e.email??"",password:"",displayName:e.displayName??"",phoneNumber:e.phoneNumber??"",photoUrl:e.photoUrl??"",emailVerified:e.emailVerified,disabled:e.disabled,claimsText:Object.keys(e.customClaims).length?JSON.stringify(e.customClaims,null,2):"",providerIds:e.providerUserInfo.map(t=>t.providerId).filter(t=>!BD.has(t))}:{...UD}}function VD(e){const t=qD(e);return{fields:t,initial:{...t}}}function WD(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function zD(e){const t={},n=e.email.trim(),r=e.password;n&&!FD.test(n)&&(t.email="Invalid email"),r&&r.length<xf&&(t.password=`Password should be at least ${xf} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=wg(e.claimsText);return s.ok||(t.claims=s.message),t}function HD(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!vg(t.providerIds,n.providerIds):t[r]!==n[r])}function vg(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function xg(e){const t=wg(e.claimsText);return t.ok?t.claims:void 0}function KD(e){const t=e.fields,n={emailVerified:t.emailVerified,disabled:t.disabled};t.email.trim()&&(n.email=t.email.trim()),t.password&&(n.password=t.password),t.displayName.trim()&&(n.displayName=t.displayName.trim()),t.phoneNumber.trim()&&(n.phoneNumber=t.phoneNumber.trim()),t.photoUrl.trim()&&(n.photoUrl=t.photoUrl.trim());const r=xg(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function GD(e){const{fields:t,initial:n}=e,r={};return t.email.trim()!==n.email&&t.email.trim()&&(r.email=t.email.trim()),t.password&&t.password!==n.password&&(r.password=t.password),t.displayName.trim()!==n.displayName&&(r.displayName=t.displayName.trim()||null),t.emailVerified!==n.emailVerified&&(r.emailVerified=t.emailVerified),t.disabled!==n.disabled&&(r.disabled=t.disabled),t.claimsText!==n.claimsText&&(r.customClaims=xg(t)??{}),vg(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function _g(e={}){const[t,n]=y.useReducer(WD,e.initial,VD),r=y.useMemo(()=>zD(t.fields),[t.fields]),s=y.useMemo(()=>HD(t),[t]),i=y.useCallback((a,l)=>n({type:"setField",field:a,value:l}),[]),o=y.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:o,toCreateRequest:()=>KD(t),toUpdateRequest:()=>GD(t),dispatch:n}}const JD={"google.com":"Google","apple.com":"Apple","gc.apple.com":"Game Center","facebook.com":"Facebook","github.com":"GitHub","microsoft.com":"Microsoft","playgames.google.com":"Play Games","twitter.com":"Twitter","yahoo.com":"Yahoo",password:"Email/Password",phone:"Phone",anonymous:"Anonymous",oidc:"OIDC",saml:"SAML"};function xi(e){return JD[e]??e}var ul=Xv();function bn(e,t,n){let r=n.initialDeps??[],s,i=!0;function o(){var a,l,u;let d;n.key&&((a=n.debug)!=null&&a.call(n))&&(d=Date.now());const h=e();if(!(h.length!==r.length||h.some((m,g)=>r[g]!==m)))return s;r=h;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...h),n.key&&((u=n.debug)!=null&&u.call(n))){const m=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-p)*100)/100,b=g/16,w=(x,v)=>{for(x=String(x);x.length<v;)x=" "+x;return x};console.info(`%c⏱ ${w(g,5)} /${w(m,5)} ms`,`
142
+ font-size: .6rem;
143
+ font-weight: bold;
144
+ color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return o.updateDeps=a=>{r=a},o}function _f(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const YD=(e,t)=>Math.abs(e-t)<1.01,QD=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},Sf=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},XD=e=>e,ZD=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let s=t;s<=n;s++)r.push(s);return r},eT=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(s(Sf(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(Sf(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},kf={passive:!0},Ef=typeof window>"u"?!0:"onscrollend"in window,tT=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&Ef?()=>{}:QD(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:h,isRtl:f}=e.options;s=h?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},a=o(!0),l=o(!1);n.addEventListener("scroll",a,kf);const u=e.options.useScrollendEvent&&Ef;return u&&n.addEventListener("scrollend",l,kf),()=>{n.removeEventListener("scroll",a),u&&n.removeEventListener("scrollend",l)}},nT=(e,t,n)=>{if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},rT=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const o=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class sT{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(i=>{const o=()=>{const a=i.target,l=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(a,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var i;return(i=r())==null?void 0:i.observe(s,{box:"border-box"})},unobserve:s=>{var i;return(i=r())==null?void 0:i.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:XD,rangeExtractor:ZD,onChange:()=>{},measureElement:nT,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=bn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,i)=>{this.scrollAdjustments=0,this.scrollDirection=i?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=i,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,i=new Map;for(let o=r-1;o>=0;o--){const a=n[o];if(s.has(a.lane))continue;const l=i.get(a.lane);if(l==null||a.end>l.end?i.set(a.lane,a):a.end<l.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,a)=>o.end===a.end?o.index-a.index:o.end-a.end)[0]:void 0},this.getMeasurementOptions=bn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,i,o,a,l)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=bn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l},u)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const p of this.laneAssignments.keys())p>=n&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const h=this.measurementsCache.slice(0,d),f=new Array(a).fill(void 0);for(let p=0;p<d;p++){const m=h[p];m&&(f[m.lane]=p)}for(let p=d;p<n;p++){const m=i(p),g=this.laneAssignments.get(p);let b,w;const x=l==="estimate"||u.has(m);if(g!==void 0&&this.options.lanes>1){b=g;const k=f[b],R=k!==void 0?h[k]:void 0;w=R?R.end+this.options.gap:r+s}else{const k=this.options.lanes===1?h[p-1]:this.getFurthestMeasurement(h,p);w=k?k.end+this.options.gap:r+s,b=k?k.lane:p%this.options.lanes,this.options.lanes>1&&x&&this.laneAssignments.set(p,b)}const v=u.get(m),_=typeof v=="number"?v:this.options.estimateSize(p),S=w+_;h[p]={index:p,start:w,size:_,end:S,key:m,lane:b},f[b]=p}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=bn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?iT({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=bn(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,i,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,s-i),a=Math.min(this.options.count-1,s+i);return n>=o&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,a)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(a))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),i=this.elementsCache.get(s);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s;const i=this.measurementsCache[n];if(!i)return;const o=this.itemSizeCache.get(i.key)??i.size,a=r-o;a!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,a,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=bn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,o=n.length;i<o;i++){const a=n[i],l=r[a];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return _f(r[Sg(0,r.length-1,s=>_f(r[s]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),i=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[o,a]=i,l=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const i=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&i.some(a=>a===null);){const a=r[o];i[a.lane]===null&&(i[a.lane]=a.end),o--}s=Math.max(...i.filter(a=>a!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,i=1,o=s!==this.scrollState.lastTargetOffset;if(!o&&YD(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Sg=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,i=n(s);if(i<r)e=s+1;else if(i>r)t=s-1;else return s}return e>0?e-1:0};function iT({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:s};let o=Sg(0,s,i,n),a=o;if(r===1)for(;a<s&&e[a].end<n+t;)a++;else if(r>1){const l=Array(r).fill(0);for(;a<s&&l.some(d=>d<n+t);){const d=e[a];l[d.lane]=d.end,a++}const u=Array(r).fill(n+t);for(;o>=0&&u.some(d=>d>=n);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:o,endIndex:a}}const jf=typeof document<"u"?y.useLayoutEffect:y.useEffect;function oT({useFlushSync:e=!0,...t}){const n=y.useReducer(()=>({}),{})[1],r={...t,onChange:(i,o)=>{var a;e&&o?ul.flushSync(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[s]=y.useState(()=>new sT(r));return s.setOptions(r),jf(()=>s._didMount(),[]),jf(()=>s._willUpdate()),s}function aT(e){return oT({observeElementRect:eT,observeElementOffset:tT,scrollToFn:rT,...e})}function dl({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:o}){const a=y.useRef(null),l=typeof t=="function"?t:()=>t,u=aT({count:e.length,getScrollElement:()=>a.current,estimateSize:l,overscan:r});return c.jsx("div",{ref:a,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:c.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const h=e[d.index],f=o?o(h,d.index):d.key;return c.jsx("div",{"data-pyric-virtual-row":!0,"data-index":d.index,ref:u.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${d.start}px)`},children:n(h,d.index)},f)})})})}function Cf(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function cT(e){return e.isAnonymous&&e.providerUserInfo.length===0?c.jsx("span",{"data-pyric-provider-id":"anonymous",children:xi("anonymous")}):e.providerUserInfo.map(t=>c.jsx("span",{"data-pyric-provider-id":t.providerId,children:xi(t.providerId)},t.providerId))}function Rf(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function kg({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:o,renderSelection:a,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:h=Rf,formatLastLoginAt:f=Rf,emptyState:p,noResultsState:m,className:g,virtualizeThreshold:b=100,rowHeight:w=44,virtualizedHeight:x="60vh"}){if(n)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const S=!!r?.trim();return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":S?"":void 0,children:S?m??"No results":p??"No users for this project yet"})}const v=e.length>b,_=S=>c.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":S.uid,"data-pyric-user-disabled":S.disabled?"":void 0,children:[a?c.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:a(S)}):null,c.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?c.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(S),children:i?i(S):Cf(S)}):(i??Cf)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(o??cT)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:h(S.createdAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(S.lastLoginAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:S.uid}),u?c.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(S)}):null]},S.uid);return c.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":v?"":void 0,"data-pyric-selection":a?"":void 0,"data-pyric-actions":u?"":void 0,children:[c.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[a?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,c.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),v?c.jsx(dl,{items:e,estimateSize:w,height:x,getItemKey:S=>S.uid,renderItem:_}):c.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(_)})]})}function lT({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return c.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[c.jsx("textarea",{"data-pyric-field":"claims","data-pyric-claims-invalid":n!=null?"":void 0,"aria-label":"Custom claims (optional)","aria-invalid":n!=null||void 0,placeholder:s,value:e,onChange:o=>t(o.target.value)}),n!=null&&c.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&c.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function uT({selected:e,onChange:t}){return c.jsx("div",{"data-pyric-provider-checklist":!0,children:Cc.map(n=>c.jsxs("label",{"data-pyric-provider-option":n,children:[c.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),c.jsx("span",{"data-pyric-provider-option-label":!0,children:xi(n)}),c.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Eg({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:o,renderField:a}){const l=_g({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),h=(m,g,b,w,x=null)=>({name:m,label:g,input:w,error:x,kind:b,defaultRender:()=>b==="checkbox"?c.jsxs("label",{"data-pyric-field-label":m,children:[w,c.jsx("span",{"data-pyric-label-text":!0,children:g})]},m):b==="group"?c.jsxs("fieldset",{"data-pyric-field-label":m,children:[c.jsx("legend",{"data-pyric-label-text":!0,children:g}),w]},m):c.jsxs("label",{"data-pyric-field-label":m,children:[c.jsx("span",{"data-pyric-label-text":!0,children:g}),w,x!=null&&c.jsx("p",{role:"alert","data-pyric-field-error":m,children:x})]},m)}),f=[h("email","Email","text",c.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:m=>l.setField("email",m.target.value)}),l.errors.email??null),h("password","Password","text",c.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:m=>l.setField("password",m.target.value)}),l.errors.password??null),h("display-name","Display name","text",c.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:m=>l.setField("displayName",m.target.value)})),h("phone-number","Phone number","text",c.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:m=>l.setField("phoneNumber",m.target.value)})),h("photo-url","Photo URL","text",c.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:m=>l.setField("photoUrl",m.target.value)})),...u==="create"?[h("providers","Sign-in providers","group",c.jsx(uT,{selected:l.fields.providerIds,onChange:m=>l.setField("providerIds",m)}))]:[],h("email-verified","Verified email","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:m=>l.setField("emailVerified",m.target.checked)})),h("disabled","Disabled (sign-in attempts are rejected)","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:m=>l.setField("disabled",m.target.checked)}))],p=m=>{m.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return c.jsxs("form",{className:o,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":l.isDirty?"":void 0,"data-pyric-is-valid":l.isValid?"":void 0,onSubmit:p,children:[f.map(m=>a?c.jsx(y.Fragment,{children:a(m)},m.name):m.defaultRender()),c.jsx(lT,{value:l.fields.claimsText,onChange:m=>l.setField("claimsText",m),error:l.errors.claims}),i,c.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?c.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,c.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}const jg=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex^="-"])'].join(", ");function dT(e){return Array.from(e.querySelectorAll(jg)).filter(t=>{if(t.disabled||t.hasAttribute("disabled")||t.getAttribute("aria-hidden")==="true"||t.tabIndex<0)return!1;if(typeof window<"u"&&typeof window.getComputedStyle=="function")try{const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!0})}function fT(e,t,n){const r=y.useRef(n);r.current=n,y.useEffect(()=>{if(!t)return;const s=i=>{if(i.key==="Escape"){i.stopPropagation(),r.current();return}if(i.key!=="Tab")return;const o=e.current;if(!o)return;const a=dT(o);if(a.length===0){i.preventDefault(),o.focus();return}const l=a[0],u=a[a.length-1],d=document.activeElement;let h=a.indexOf(d);if(h===-1&&d&&o.contains(d)){const f=d.closest?.(jg);f&&(h=a.indexOf(f))}if(i.preventDefault(),h===-1){i.shiftKey?u.focus():l.focus();return}i.shiftKey?h<=0?u.focus():a[h-1].focus():h>=a.length-1?l.focus():a[h+1].focus()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function hT({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:o="Cancel",onConfirm:a,className:l}){const u=y.useRef(null),d=y.useRef(null),h=y.useRef(null);return fT(u,e,()=>t(!1)),y.useEffect(()=>{if(e)return h.current=document.activeElement,d.current?.focus(),()=>{h.current?.focus?.()}},[e]),!e||typeof document>"u"?null:ul.createPortal(c.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:f=>{f.target===f.currentTarget&&t(!1)},children:[c.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),c.jsxs("div",{ref:u,role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:l,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[c.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?c.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,c.jsxs("div",{"data-pyric-confirm-actions":!0,children:[c.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:o}),c.jsx("button",{ref:d,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:a,children:i})]})]})]}),document.body)}const Cg=y.createContext(null);function Hn(){const e=y.useContext(Cg);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function fl({children:e,dialogClassName:t}){const[n,r]=y.useState(null),s=y.useRef(!1),i=y.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),o=y.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),a=y.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=y.useMemo(()=>i,[i]);return c.jsxs(Cg.Provider,{value:l,children:[e,n?c.jsx(hT,{open:!0,onOpenChange:a,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:o,className:t}):null]})}function pT(e){return e.email??e.phoneNumber??e.displayName??e.uid}function mT({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:o}){const a=Hn(),l=async()=>{await a({title:n,body:r??`This will permanently delete ${pT(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?c.jsx(c.Fragment,{children:i({onClick:l})}):c.jsx("button",{type:"button",className:o,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function yT(e,t=Date.now()){const n=Math.max(0,t-e);return n<5e3?"just now":n<6e4?`${Math.floor(n/1e3)}s ago`:n<36e5?`${Math.floor(n/6e4)}m ago`:`${Math.floor(n/36e5)}h ago`}function gT(e){const t=e.toLowerCase();return t==="flutter"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--flutter",children:"Flutter"}):t==="swift"||t==="ios"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--swift",children:"iOS Swift"}):t==="kotlin"||t==="android"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--kotlin",children:"Android Kotlin"}):c.jsx("span",{className:"studio-remote-client__badge",children:e})}function bT(e){if(!e||e.mode==="app-session")return"App Session";if(e.mode==="admin")return"Admin Bypass";if(e.mode==="anon")return"Anonymous";if(e.mode==="as"){const t=e.token?" +claims":"",n=e.tenant?` @${e.tenant}`:"";return`User: ${e.uid}${t}${n}`}return"Unknown"}function wT({auth:e,onSelectUser:t}){const{users:n,isLoading:r}=Vi(e);return c.jsxs("select",{className:"studio-remote-client__select",defaultValue:"",disabled:r||n.length===0,onChange:s=>{const i=n.find(o=>o.uid===s.target.value);i&&(t(i),s.target.value="")},children:[c.jsx("option",{value:"",disabled:!0,children:r?"Loading sandbox users…":n.length===0?"No sandbox users found":"Impersonate sandbox user…"}),n.map(s=>c.jsx("option",{value:s.uid,children:s.email?`${s.email} (${s.uid.slice(0,6)}…)`:s.uid},s.uid))]})}function vT({isOpen:e,onClose:t,consumers:n,onSetLens:r,triggerRef:s,auth:i}){const[o,a]=y.useState(""),[l,u]=y.useState(""),[d,h]=y.useState(""),[f,p]=y.useState(!1),[m,g]=y.useState("");if(y.useEffect(()=>{if(!e)return;const x=v=>{v.key==="Escape"&&(t(),s?.current?.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[e,t,s]),!e)return null;const b=i,w=(x,v)=>{let _;if(l.trim())try{_=JSON.parse(l)}catch{alert("Invalid JSON for custom claims");return}const S=d.trim()||void 0;r(x,{mode:"as",uid:v,token:_,tenant:S})};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-remote-clients__backdrop",onMouseDown:t}),c.jsxs("div",{id:"studio-remote-clients-panel",className:"studio-remote-clients__panel",role:"dialog","aria-label":"Remote Mobile Clients",children:[c.jsxs("div",{className:"studio-remote-clients__header",children:[c.jsx("h3",{className:"studio-remote-clients__title",children:"Remote Mobile Clients"}),c.jsxs("span",{className:"studio-remote-clients__count",children:[n.length," connected"]})]}),n.length===0?c.jsx("p",{className:"studio-remote-clients__empty",children:"No remote mobile clients connected over the bridge. Connect your Flutter, iOS, or Android app to control its identity remotely."}):c.jsx("ul",{className:"studio-remote-clients__list",children:n.map(x=>c.jsxs("li",{className:"studio-remote-clients__item",children:[c.jsxs("div",{className:"studio-remote-clients__item-top",children:[c.jsxs("div",{className:"studio-remote-clients__item-info",children:[gT(x.platform),c.jsx("span",{className:"studio-remote-clients__device",children:x.deviceLabel||"Mobile Device"})]}),c.jsx("span",{className:"studio-remote-clients__freshness",children:yT(x.lastSeen)})]}),c.jsxs("div",{className:"studio-remote-clients__session",children:["Session: ",c.jsxs("code",{children:[x.clientSessionId.slice(0,10),"…"]})]}),c.jsxs("div",{className:"studio-remote-clients__current-lens",children:[c.jsx("span",{className:"studio-remote-clients__lens-label",children:"Active Lens:"}),c.jsx("span",{className:"studio-remote-clients__lens-pill",children:bT(x.activeLens)})]}),c.jsxs("div",{className:"studio-remote-clients__actions",children:[c.jsxs("div",{className:"studio-remote-clients__btn-group",children:[c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="app-session"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"app-session"}),children:"App Session"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="admin"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"admin"}),children:"Admin"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="anon"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"anon"}),children:"Anon"})]}),c.jsx("div",{className:"studio-remote-clients__switcher",children:b?c.jsx(wT,{auth:b,onSelectUser:v=>w(x.clientSessionId,v.uid)}):c.jsxs("div",{className:"studio-remote-clients__manual-row",children:[c.jsx("input",{type:"text",placeholder:"Impersonate UID…",className:"studio-remote-client__input",value:o===x.clientSessionId?m:"",onChange:v=>{a(x.clientSessionId),g(v.target.value)}}),c.jsx("button",{type:"button",className:"studio-remote-btn studio-remote-btn--primary",disabled:!m.trim(),onClick:()=>{w(x.clientSessionId,m.trim()),g("")},children:"Switch"})]})}),c.jsxs("div",{className:"studio-remote-clients__advanced",children:[c.jsx("button",{type:"button",className:"studio-remote-clients__advanced-toggle",onClick:()=>p(!f),children:f?"▲ Hide Claims & Tenant":"▼ Custom Claims / Tenant"}),f?c.jsxs("div",{className:"studio-remote-clients__advanced-inputs",children:[c.jsx("input",{type:"text",placeholder:"Custom Claims JSON, e.g. { role: 'admin' }",className:"studio-remote-client__input",value:l,onChange:v=>u(v.target.value)}),c.jsx("input",{type:"text",placeholder:"Tenant ID (optional)",className:"studio-remote-client__input",value:d,onChange:v=>h(v.target.value)})]}):null]})]})]},x.clientSessionId))})]})]})}const xT={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},_T=()=>()=>{},Nf=()=>xT;function ST(){const e=ot(),t=fs(),n=Gt(),[r,s]=y.useState(!1),i=n.some(H=>H.kind==="runtime_error"&&H.error.code==="persistence-unhealthy"),o=t.status==="ready"&&t.payload.persistenceUnhealthy===!0;y.useEffect(()=>{(i||o)&&s(!0)},[i,o]);const a=ED(),l=ID(),[u,d]=y.useState(!1),h=y.useRef(null),{consumers:f,setLens:p}=$D(),[m,g]=y.useState(!1),b=y.useRef(null),w=Ct(),v=w.status==="ready"?w.handles?.auth:void 0,S=e.status==="ready"?e.env.live?.runtime:void 0,k=y.useSyncExternalStore(S?.subscribe??_T,S?.getSnapshot??Nf,S?.getSnapshot??Nf),O=t.status==="ready"&&e.status==="ready"&&!e.env.live,P=e.status==="error",A="mode"in k&&k.mode==="hosted",E=A?k.error:"worker update failed",j=k.error!==null;let $=null;O&&($="worker unreachable"),P&&($="backend error"),j&&($=E),r&&($="persistence failed — writes blocked");let C="Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.";P&&(C=e.error.message),j&&(C=k.error??C),r&&(C="Reads may include unsaved changes. Repair the hosted store and restart the host.");const N=!j,I=A?N:a==="available",M=!A||N;y.useEffect(()=>{if(!u)return;const H=Jn=>{Jn.key==="Escape"&&(d(!1),h.current?.focus())};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[u]);const T=k.updateAvailable,U=k.updating?"updating worker…":"update worker",V=$!==null,B=M&&l!==null&&l.count>0,ye=l?.prominent===!0?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger",Rt=l!==null&&l.otherCount>0,Gn=l?.otherCount===1?"":"s";let yn=`${l?.chipLabel}. Expand for details.`;Rt&&(yn=`${l.chipLabel}. ${l.otherCount} other page${Gn} can keep the worker alive.`),A&&(yn=`${l?.chipLabel}. These pages share the Node host.`);const D=A?"Data is shared by every client connected to this host.":l?.boundaryCopy;let ae=l?.count===1?"This page is the only connection to the shared sandbox worker.":`${l?.count} pages share this sandbox worker. Closing this page alone will not restart it.`;A&&(ae="These pages share the Node-hosted sandbox. Closing a page does not stop the host.");const Y=M&&f.length>0,ge=f.length===1,be=ge?"":"s",we=ge?"1 remote client":`${f.length} remote clients`;return c.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[T&&c.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:k.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void S?.update().catch(()=>{}),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),U]}),V&&c.jsxs("a",{className:"studio-chip studio-chip--warn",href:kt({tab:"settings"}),title:C,onClick:H=>{H.preventDefault(),Ie({tab:"settings"})},children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),$]}),B&&c.jsxs("span",{className:"studio-presence",children:[c.jsxs("button",{ref:h,type:"button",className:ye,"aria-haspopup":"dialog","aria-expanded":u,"aria-controls":"studio-presence-panel",title:yn,onClick:()=>d(H=>!H),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.chipLabel]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>d(!1)}),c.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[c.jsx("p",{className:"studio-presence__lead",children:ae}),c.jsx("ul",{className:"studio-presence__list",children:l.clients.map(H=>c.jsxs("li",{className:"studio-presence__item",children:[c.jsxs("div",{className:"studio-presence__item-head",children:[c.jsx("span",{className:"studio-presence__kind",children:H.kindLabel}),H.isThisPage?c.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),c.jsx("div",{className:"studio-presence__route",title:H.route,children:H.route}),c.jsxs("div",{className:"studio-presence__meta",children:[H.visibilityLabel," · ",H.freshnessLabel]})]},H.clientId))}),c.jsx("p",{className:"studio-presence__boundary",children:D})]})]})]}),Y&&c.jsxs("span",{className:"studio-remote-clients",children:[c.jsxs("button",{ref:b,type:"button",className:"studio-chip studio-chip--live studio-remote-clients__trigger","aria-haspopup":"dialog","aria-expanded":m,"aria-controls":"studio-remote-clients-panel",title:`${f.length} remote client${be} connected over the bridge. Click to control identity.`,onClick:()=>g(H=>!H),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),we]}),c.jsx(vT,{isOpen:m,onClose:()=>g(!1),consumers:f,onSetLens:p,triggerRef:b,auth:v})]}),I&&c.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]})]})}function kT(e,t){const n=e.triggeredBy,r=t.triggeredBy;return!n&&!r?!0:!n||!r?!1:n.method===r.method&&n.path===r.path}function If(e,t,n){let r=0;for(const s of n)s.result==="deny"&&r++;return{type:"group",kind:e,key:t,events:n,count:n.length,denies:r}}function ET({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return y.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let o=s+1;for(;o<e.length&&e[o].groupId===i.groupId;)o++;const a=e.slice(s,o),l=i.origin==="transaction"?"transaction":"batch";r.push(If(l,i.groupId,a)),s=o;continue}if(n&&i.origin==="listener"){let o=s+1;for(;o<e.length&&e[o].origin==="listener"&&!e[o].groupId&&kT(e[o],i);)o++;const a=e.slice(s,o);if(a.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(If("listener-run",`listener-run:${l}:${s}`,a))}else r.push({type:"single",event:i});s=o;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const jT={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function CT({events:e,window:t,bucketCount:n=30}){return y.useMemo(()=>RT(e,t,n),[e,t.start,t.end,n])}function RT(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return jT;const s=r/n,i=new Array(n).fill(0),o=new Array(n).fill(0);let a=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let m=Math.floor((p-t.start)/s);m>=n&&(m=n-1),i[m]++,a++,f.result==="deny"&&(o[m]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const m=o[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:m,allows:f-m,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:m/d}}),total:a,denies:l,maxCount:d,outOfWindow:u}}const NT=new Set(["get","list"]),IT=new Set(["create","update","set"]),AT=new Set(["delete","remove"]),OT=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],$T=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Wi(e){return e.origin==="admin"}function PT(e,t=Wi){return e.result==="allow"||t(e)?NT.has(e.method)?"reads":IT.has(e.method)?"writes":AT.has(e.method)?"deletes":null:null}function DT(e,t=Wi){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const TT=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Rg(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return TT(r);const o=i/n,a=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),l=new Map(r.map(f=>[f.key,0]));for(const f of e){const p=f.at;if(p<t.start||p>=t.end)continue;const m=s(f);if(m==null)continue;let g=Math.floor((p-t.start)/o);g>=n&&(g=n-1);const b=a.get(m);b[g]++,l.set(m,(l.get(m)??0)+1)}let u=0;for(const f of a.values())for(const p of f)p>u&&(u=p);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*o,end:t.start+(f+1)*o};const h=r.map(f=>({key:f.key,label:f.label,values:a.get(f.key),total:l.get(f.key)??0}));return{points:d,series:h,maxValue:u}}function MT(e,t,n=24,r=Wi){return Rg(e,t,n,OT,s=>PT(s,r))}function LT(e,t,n=24,r=Wi){return Rg(e,t,n,$T,s=>DT(s,r))}function UT({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>MT(e,t,n,r),[e,t.start,t.end,n,r])}function BT({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>LT(e,t,n,r),[e,t.start,t.end,n,r])}function Xa({children:e,kind:t,className:n,ariaLabel:r}){return c.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?c.jsx("span",{"aria-hidden":"true",children:e}):e})}function Kr(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Ng({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Kr,className:i}){return c.jsxs("button",{type:"button",onClick:()=>n?.(e),className:i,"data-pyric-traffic-row":"","data-pyric-result":e.result,"data-pyric-origin":e.origin,"data-pyric-method":e.method,"data-pyric-selected":t?"":void 0,children:[c.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),c.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),c.jsx(Xa,{kind:e.method,children:e.method}),c.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}const FT={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function qT({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:o}){const[a,l]=y.useState(t);return c.jsxs("div",{className:o,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":a?"":void 0,children:[c.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":a,children:[c.jsx("span",{"data-pyric-group-kind-label":"",children:FT[e.kind]}),c.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?c.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),a?c.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>c.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:c.jsx(Ng,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function VT(e){return e<0?0:e>1?1:e}function Bo(e,t){const n=t.end-t.start;return n<=0?0:VT((e-t.start)/n)}function Ig({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:o,liveAt:a,header:l,axis:u,emptyState:d,className:h}){const f=y.useId(),[p,m]=y.useState(null),[g,b]=y.useState(null),w=CT({events:e??[],window:n,bucketCount:r}),x=t??w,{buckets:v,total:_}=x,S=p??g,k=S===null?null:v.find(j=>j.index===S)??null,R=k!==null&&s?.start===k.start&&s.end===k.end;if(v.length===0)return c.jsx("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const O=_===0,P=a===void 0?n.end:a,A=P==null?null:Bo(P,n),E=typeof u=="function"?u(n):u;return c.jsxs("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":O?"":void 0,children:[l!==void 0&&c.jsx("div",{"data-pyric-timeline-header":"",children:l}),c.jsxs("div",{"data-pyric-timeline-chart":"",children:[c.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:v.map(j=>c.jsx(WT,{bucket:j,window:n,onBrush:i,onHover:o?m:void 0,onFocus:o?b:void 0,summaryId:o&&!R&&k?.index===j.index?f:void 0,selected:s?.start===j.start&&s.end===j.end},j.index))}),k&&o&&!R?c.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(k.index+.5)/Math.max(v.length,1)},children:o(k)}):null,s&&c.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Bo(s.start,n),"--pyric-brush-right":1-Bo(s.end,n)}}),A!=null&&c.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":A}})]}),E!=null&&c.jsx("div",{"data-pyric-timeline-axis":"",children:E})]})}function WT({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:o}){const a=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return c.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":e.index,"data-pyric-bucket-count":e.count,"data-pyric-bucket-denies":e.denies,"data-pyric-has-denies":e.denies>0?"":void 0,"data-pyric-bucket-selected":o?"":void 0,disabled:!a,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":a?o:void 0,onPointerEnter:r?()=>r(e.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(e.index):void 0,onBlur:s?()=>s(null):void 0,onClick:a?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[c.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const zT=e=>String(e);function hl({series:e,visible:t,onToggle:n,formatValue:r=zT,className:s}){const i=t!==void 0&&n!==void 0;return c.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((o,a)=>{const l=t?t.has(o.key):!0,u=c.jsxs(c.Fragment,{children:[c.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-metric-label":"",children:o.label}),c.jsx("span",{"data-pyric-metric-value":"",children:r(o.total)})]});return i?c.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,"data-pyric-metric-hidden":l?void 0:"",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(o.key),"data-pyric-metric-checkbox":""}),u]},o.key):c.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,children:u},o.key)})})}const HT=e=>String(e),KT=e=>new Date(e).toLocaleTimeString();function Ag({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=HT,formatTime:i=KT,emptyState:o,className:a}){const[l,u]=y.useState(null);if(e.length===0)return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:o});const d=t.filter(w=>(!n||n.has(w.key))&&(!r||w.total>0));let h=0;for(const w of d)for(const x of w.values)x>h&&(h=x);const f=h===0?1:h,p=e.length,m=w=>p===1?50:w/(p-1)*100,g=w=>100-w/f*100,b=l!=null?e[l]:null;return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart",children:c.jsxs("div",{"data-pyric-chart-svg":"",children:[c.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(w=>{const x=t.indexOf(w);if(!((!n||n.has(w.key))&&(!r||w.total>0)))return null;const _=w.values.map((S,k)=>`${k===0?"M":"L"}${m(k)},${g(S)}`).join(" ");return c.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":w.key,"data-pyric-series-index":x,d:_,fill:"none",vectorEffect:"non-scaling-stroke"},w.key)})}),c.jsx("div",{"data-pyric-chart-hits":"",children:e.map((w,x)=>c.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":x,onMouseEnter:()=>u(x),onFocus:()=>u(x),onMouseLeave:()=>u(v=>v===x?null:v),onBlur:()=>u(v=>v===x?null:v),"aria-label":`${i(w.start)} to ${i(w.end)}`},w.index))}),b&&c.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":m(b.index)},children:[c.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(b.start)," – ",i(b.end)]}),d.map(w=>c.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":w.key,"data-pyric-series-index":t.indexOf(w),children:[c.jsx("span",{"data-pyric-tooltip-label":"",children:w.label}),c.jsx("span",{"data-pyric-tooltip-value":"",children:s(w.values[b.index])})]},w.key))]})]})})}function Og(e={}){const[t]=y.useState(()=>(e.captureOwnerStack,void 0)),[n,r]=y.useState(void 0),s=y.useCallback(o=>{o!==null&&r(o)},[]);return{owner:y.useMemo(()=>{if(t!==void 0)return n===void 0?t:{...t,element:n}},[t,n]),ref:s}}function GT(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);if(e&&typeof e=="object"){const t=e,n=typeof t.message=="string"?t.message:null,r=typeof t.code=="string"?t.code:null;if(n&&r)return new Error(`[${r}] ${n}`);if(n)return new Error(n);if(r)return new Error(r);try{return new Error(JSON.stringify(e))}catch{return new Error(Object.prototype.toString.call(e))}}return new Error(String(e))}const JT={addDoc:Jh,collection:pr,deleteDoc:Zo,doc:tt,getDoc:km,getDocs:hi,limit:mi,onSnapshot:CR,query:pi,setDoc:Gs,startAfter:jR},$g=y.createContext(JT);function pl(){return y.useContext($g)}function YT({value:e,children:t}){return y.createElement($g.Provider,{value:e},t)}function QT(e){const{onSnapshot:t}=pl(),{owner:n}=Og(),[r,s]=y.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return y.useEffect(()=>{if(!e){s({data:void 0,error:void 0,isLoading:!1});return}return s(o=>({data:o.data,error:void 0,isLoading:!0})),t(e,{owner:n},o=>s({data:o,error:void 0,isLoading:!1}),o=>s({data:void 0,error:GT(o),isLoading:!1}))},[t,n,e]),r}function zi(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&pn(e)!==null?"vector":Array.isArray(e)?"array":e instanceof Ft?"timestamp":e instanceof $n?"geopoint":e instanceof rn?"bytes":typeof e=="object"&&Pg(e)?"timestamp":typeof e=="object"&&Tg(e)?"geopoint":typeof e=="object"&&Dg(e)?"bytes":typeof e=="object"&&XT(e)?"reference":typeof e=="object"?"map":"null"}function Pg(e){const t=e;return Object.keys(t).length!==2?!1:typeof t.seconds=="number"&&typeof t.nanoseconds=="number"||typeof t._seconds=="number"&&typeof t._nanoseconds=="number"}function Dg(e){const t=e,n=Object.keys(t);return n.length===1?t.bytes instanceof Uint8Array:n.length===2&&t.type==="firestore/bytes/1.0"&&typeof t.bytes=="string"}function ml(e){if(e instanceof rn)return e;const t=e;return typeof t.bytes=="string"?rn.fromBase64String(t.bytes):rn.fromUint8Array(t.bytes)}function Tg(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function XT(e){const t=e;if(typeof t.path!="string"||typeof t.id!="string")return!1;const n=typeof t.firestore=="object"&&t.firestore!==null,r=typeof t.env=="object"&&t.env!==null,s=t.type==="document";return n||r||s}function pn(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&As(t.value)||t.__type__==="__vector__"&&As(t.value))return Os(t.value);if(As(t._values))return Os(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(As(n))return Os(n)}catch{}return null}function As(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Os(e){const t=e.slice();return{values:t,dimension:t.length}}const Af=4;function Mg(e){const t=e.values.slice(0,Af).join(", "),n=e.values.length>Af?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function _i(e){const t=pn(e);if(t)return Mg(t);if(Array.isArray(e))return e.map(_i);if(e&&typeof e=="object"){const n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null){const r={};for(const[s,i]of Object.entries(e))r[s]=_i(i);return r}}return e}function Lg(){return crypto.randomUUID()}function ZT(e){const t=Lg(),n={rootId:t,nodes:{[t]:{id:t,parentId:null,key:null,type:"map",value:void 0}},childIds:{[t]:[]}};for(const[r,s]of Object.entries(e))Za(n,t,r,s);return n}function Za(e,t,n,r){const s=zi(r),i=Lg(),o={id:i,parentId:t,key:n,type:s,value:eM(s)?void 0:r};if(e.nodes[i]=o,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[a,l]of Object.entries(r))Za(e,i,a,l);else if(s==="array"&&Array.isArray(r))for(const a of r)Za(e,i,null,a);return i}function eM(e){return e==="map"||e==="array"}function Ug(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return ec(e,e.rootId)}function ec(e,t){const n=e.nodes[t];if(!n)throw new Error(`serializeNode: missing node ${t}`);switch(n.type){case"map":{const r={};for(const s of e.childIds[t]??[]){const i=e.nodes[s];i&&i.key!=null&&(r[i.key]=ec(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(ec(e,s));return r}default:return n.value}}function tc(e){const t={};for(const[r,s]of Object.entries(e.nodes))t[r]={...s};const n={};for(const[r,s]of Object.entries(e.childIds))n[r]=[...s];return{rootId:e.rootId,nodes:t,childIds:n}}function Bg(e,t){const n=[t],r=[t];for(;r.length;){const s=r.shift();for(const i of e.childIds[s]??[])n.push(i),r.push(i)}return n}function Fg(e,t){switch(e){case"string":return typeof t=="string"?void 0:"Expected a string";case"number":return typeof t!="number"?"Expected a number":Number.isFinite(t)?void 0:"Number must be finite";case"boolean":return typeof t=="boolean"?void 0:"Expected a boolean";case"null":return t==null?void 0:"Expected null";case"timestamp":return t instanceof Ft?void 0:"Expected a Timestamp";case"geopoint":return t instanceof $n?t.latitude<-90||t.latitude>90?"Latitude must be between -90 and 90":t.longitude<-180||t.longitude>180?"Longitude must be between -180 and 180":void 0:"Expected a GeoPoint";case"reference":if(t===null||typeof t!="object")return"Expected a DocumentReference";const n=t;return typeof n.path!="string"?"Reference missing `path`":n.path?n.path.split("/").filter(Boolean).length%2!==0?"Reference path must have an even segment count":void 0:"Reference path is empty";case"bytes":return t instanceof rn?void 0:"Expected a Bytes value";case"vector":return pn(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function qg(e){const t={};let n=0;for(const[r,s]of Object.entries(e.nodes))t[r]={...s,error:void 0};for(const r of Object.values(t)){if(r.type==="map"||r.type==="array")continue;const s=Fg(r.type,r.value);s&&(t[r.id].error=s,n++)}for(const[r,s]of Object.entries(t)){if(s.type!=="map")continue;const i=e.childIds[r]??[],o=new Map;for(const a of i){const l=t[a];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[a].error=t[a].error??"Field name is required");const d=o.get(u)??[];d.push(a),o.set(u,d)}for(const[a,l]of o)if(a&&l.length>1)for(const u of l)t[u].error||n++,t[u].error=t[u].error??"Field name must be unique"}return{tree:{rootId:e.rootId,nodes:t,childIds:e.childIds},errorCount:n}}function yl(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return Ft.now();case"geopoint":return new $n(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return rn.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function nc(e){if(e===null||typeof e!="object"||pn(e)!==null)return e;if(Pg(e)){const n=e;return new Ft(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Tg(e)){const n=e;return new $n(n.latitude,n.longitude)}if(Dg(e))return ml(e);if(Array.isArray(e))return e.map(nc);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=nc(s);return n}return e}function Vg(e){const t=ZT(nc(e)),{tree:n,errorCount:r}=qg(t);return{tree:n,initial:n,errorCount:r}}function tM(e,t){switch(t.type){case"setValue":return wn(e,n=>rM(n,t.nodeId,t.value));case"setType":return wn(e,n=>sM(n,t.nodeId,t.newType));case"setKey":return wn(e,n=>iM(n,t.nodeId,t.key));case"addMapEntry":return wn(e,n=>oM(n,t.parentId,t.key,t.childType));case"addArrayEntry":return wn(e,n=>aM(n,t.parentId,t.childType));case"remove":return wn(e,n=>cM(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:nM(e.initial)};case"replaceData":return Vg(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=tc(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=tc(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function wn(e,t){const n=t(tc(e.tree)),{tree:r,errorCount:s}=qg(n);return{...e,tree:r,errorCount:s}}function nM(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function rM(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function sM(e,t,n){const r=e.nodes[t];if(!r||r.id===e.rootId&&n!=="map"||r.type===n)return e;if(r.type==="map"||r.type==="array"){const i=(e.childIds[t]??[]).slice();for(const o of i)for(const a of Bg(e,o))delete e.nodes[a],delete e.childIds[a];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:yl(n);return e.nodes[t]={...r,type:n,value:s},e}function iM(e,t,n){const r=e.nodes[t];if(!r||r.parentId==null)return e;const s=e.nodes[r.parentId];return!s||s.type!=="map"||(e.nodes[t]={...r,key:n}),e}function oM(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),o=r==="map"||r==="array"?void 0:yl(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:o},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function aM(e,t,n){const r=e.nodes[t];if(!r||r.type!=="array"||n==="array")return e;const s=crypto.randomUUID(),i=n==="map"?void 0:yl(n);return e.nodes[s]={id:s,parentId:t,key:null,type:n,value:i},e.childIds[s]=[],e.childIds[t]=[...e.childIds[t]??[],s],e}function cM(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Bg(e,t);for(const s of r)delete e.nodes[s],delete e.childIds[s];return n.parentId!=null&&(e.childIds[n.parentId]=(e.childIds[n.parentId]??[]).filter(s=>s!==t)),e}function Wg(e={}){const t=e.initial??{},n=y.useRef(null);n.current==null&&(n.current=Vg(t));const[r,s]=y.useReducer(tM,n.current),i=y.useCallback((x,v)=>s({type:"setValue",nodeId:x,value:v}),[]),o=y.useCallback((x,v)=>s({type:"setType",nodeId:x,newType:v}),[]),a=y.useCallback((x,v)=>s({type:"setKey",nodeId:x,key:v}),[]),l=y.useCallback((x,v,_)=>s({type:"addMapEntry",parentId:x,key:v,childType:_}),[]),u=y.useCallback((x,v)=>s({type:"addArrayEntry",parentId:x,childType:v}),[]),d=y.useCallback(x=>s({type:"remove",nodeId:x}),[]),h=y.useCallback(()=>s({type:"reset"}),[]),f=y.useCallback(x=>s({type:"replaceData",data:x}),[]),p=y.useCallback(x=>s({type:"touch",nodeId:x}),[]),m=y.useCallback(()=>s({type:"touchAll"}),[]),g=y.useCallback(()=>Ug(r.tree),[r.tree]),b=r.tree!==r.initial,w=r.errorCount===0;return y.useMemo(()=>({...r,isDirty:b,isValid:w,dispatch:s,setValue:i,setType:o,setKey:a,addMapEntry:l,addArrayEntry:u,remove:d,reset:h,replaceData:f,touch:p,touchAll:m,toData:g}),[r,b,w,i,o,a,l,u,d,h,f,p,m,g])}function lM({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=y.useState([]),[o,a]=y.useState(!0),[l,u]=y.useState(void 0),[d,h]=y.useState(!1),[f,p]=y.useState(0),[m,g]=y.useState(n),b=y.useRef(0),[w,x]=y.useState(0),{addDoc:v,deleteDoc:_,doc:S,getDoc:k,getDocs:R,limit:O,onSnapshot:P,query:A,setDoc:E,startAfter:j}=pl(),{owner:$}=Og();y.useEffect(()=>{g(n)},[e,r,n,t]),y.useEffect(()=>{let T=!1;r==="paged"&&i([]),h(!1),a(!0),u(void 0);const F=t??e,U=r==="live"?m:n,V=A(F,O(U)),B=ye=>{T||(i([...ye.docs]),h(ye.docs.length===U),a(!1))},_e=ye=>{T||(u(ye instanceof Error?ye:new Error(String(ye))),a(!1))};if(r==="live"){const ye=++b.current,Rt=P(V,{owner:$},mn=>{x(ye),B(mn)},_e);return()=>{T=!0,Rt()}}return R(V).then(ye=>{B(ye)}).catch(_e),()=>{T=!0}},[e,R,O,r,P,$,n,t,A,m,f]);const C=y.useCallback(()=>{if(!d||o)return;if(r==="live"){a(!0),g(V=>V+n);return}const T=s[s.length-1];if(!T)return;a(!0);const U=A(t??e,j(T),O(n));R(U).then(V=>{i(B=>[...B,...V.docs]),h(V.docs.length===n),a(!1)}).catch(V=>{u(V instanceof Error?V:new Error(String(V))),a(!1)})},[e,s,R,d,o,O,r,n,t,A,j]),N=y.useCallback(async(T,F,U)=>{if(T==null){const B=await v(e,F);return r==="paged"&&p(_e=>_e+1),B}const V=S(e,T);if(U?.onExisting==="fail"){const B=await k(V);if(typeof B.exists=="function"?B.exists():!!B.exists){const ye=new Error(`Document "${T}" already exists.`);throw ye.code="already-exists",ye}}return await E(V,F),r==="paged"&&p(B=>B+1),V},[v,e,S,k,r,E]),I=y.useCallback(async T=>{await _(T),r==="paged"&&p(F=>F+1)},[_,r]),M=y.useCallback(()=>p(T=>T+1),[]);return{documents:s,isLoading:o,error:l,subscriptionGeneration:w,hasMore:d,loadMore:C,createDocument:N,deleteDocument:I,refresh:M}}function uM({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=y.useState([]),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(n);u.current=n;const d=t?.path;return y.useEffect(()=>{if(!t){s([]),o(!1),l(void 0);return}let h=!1;return o(!0),l(void 0),u.current(e,t).then(f=>{h||(s(f),o(!1))}).catch(f=>{h||(l(f instanceof Error?f:new Error(String(f))),o(!1))}),()=>{h=!0}},[e,d]),{subcollections:r,isLoading:i,error:a}}function Of(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function $f(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Si(e,t){if(Object.is(e,t))return!0;if(Of(e))return e.isEqual(t);if(Of(t))return t.isEqual(e);if(e instanceof Uint8Array||t instanceof Uint8Array)return!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length?!1:e.every((s,i)=>s===t[i]);if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,i)=>Si(s,t[i]));if(!$f(e)||!$f(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&Si(e[s],t[s]))}function dM({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function fM({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const hM={type:"string",Display:dM,Edit:fM};function pM({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function mM({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,o=i===""?Number.NaN:parseFloat(i);t(o)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const yM={type:"number",Display:pM,Edit:mM};function gM({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function bM({value:e,onChange:t,path:n}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:c.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]})})}const wM={type:"boolean",Display:gM,Edit:bM};function vM({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function xM({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const _M={type:"null",Display:vM,Edit:xM};function gl(e){if(e instanceof Ft)return e.toDate();const t=e,n=t?t.seconds??t._seconds:void 0,r=t?t.nanoseconds??t._nanoseconds??0:0;return typeof n=="number"?new Date(n*1e3+Math.floor(r/1e6)):new Date(NaN)}function SM(e){const t=e;return new Ft(t.seconds??t._seconds??0,t.nanoseconds??t._nanoseconds??0)}function kM(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const r=gl(t);return!Number.isNaN(r.getTime())&&r.getTime()===n.getTime()?t instanceof Ft?t:SM(t):Ft.fromDate(n)}function EM({value:e,path:t}){const n=gl(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return c.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function jM({value:e,onChange:t,error:n,path:r}){const s=gl(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),o=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,23);return c.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"datetime-local",step:"0.001",value:o,onChange:a=>{const l=a.target.value;if(!l)return;const u=kM(l,e);u&&t(u)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const CM={type:"timestamp",Display:EM,Edit:jM};function RM({value:e,path:t}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":t,"data-lat":String(e.latitude),"data-lng":String(e.longitude),children:[e.latitude,", ",e.longitude]})}function NM({value:e,onChange:t,error:n,path:r}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new $n(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new $n(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const IM={type:"geopoint",Display:RM,Edit:NM},zg=y.createContext({});zg.Provider;function AM(){return y.useContext(zg)}function OM({value:e,path:t}){const{onReferenceClick:n}=AM();return n?c.jsx("button",{type:"button",onClick:()=>n(e),"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,"data-pyric-clickable":"",children:e.path}):c.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function $M({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,o=i.split("/").filter(Boolean),a=o[o.length-1]??"",l=e.firestore??{};t({path:i,id:a,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const PM={type:"reference",Display:OM,Edit:$M};function DM({value:e,path:t}){const n=ml(e),r=n.toBase64();return c.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(n.toUint8Array().byteLength),children:r})}function TM({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("textarea",{value:ml(e).toBase64(),onChange:s=>{try{t(rn.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const MM={type:"bytes",Display:DM,Edit:TM};function rc({value:e,path:t,fieldEditors:n}){const r=zi(e),s=n[r];if(!s)return null;const{Display:i}=s;return c.jsx(i,{value:e,path:t,fieldEditors:n})}function Hg({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=zi(t),o=i==="map"||i==="array",[a,l]=y.useState(!0),u=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},d=s==="key"?{"data-field-name":e}:{"data-field-index":e};return o?c.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[c.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":a,onClick:()=>l(h=>!h),children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),c.jsx("span",{...u,children:e})]}),a?c.jsx(rc,{value:t,path:n,fieldEditors:r}):null]}):c.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),c.jsx("span",{...u,children:e}),c.jsx(rc,{value:t,path:n,fieldEditors:r})]})}function LM({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return c.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>c.jsx(Hg,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const UM={type:"map",Display:LM};function BM({value:e,path:t,fieldEditors:n}){return c.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>c.jsx(Hg,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const FM={type:"array",Display:BM},Pf=4;function qM(e){return e.length<=Pf?`[${e.join(", ")}]`:`[${e.slice(0,Pf).join(", ")}, …]`}function VM({value:e,path:t}){const n=pn(e);return n?c.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),c.jsx("span",{"data-pyric-vector-preview":!0,children:qM(n.values)})]}):c.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function WM(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"Invalid JSON"}}return!Array.isArray(t)||!t.every(n=>typeof n=="number")?{ok:!1,error:"Expected a JSON array of numbers"}:{ok:!0,value:{__type__:"__vector__",value:t}}}function zM({value:e,onChange:t,error:n,path:r}){const s=pn(e),i=s?JSON.stringify(s.values):"[]",[o,a]=y.useState(i),[l,u]=y.useState(void 0),d=p=>{a(p);const m=WM(p);if(!m.ok){u(m.error);return}u(void 0),t(m.value)},h=s?s.dimension:0,f=l??n;return c.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(h),"data-pyric-error":f?"":void 0,children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${h}`}),c.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),c.jsx("textarea",{"data-pyric-vector-raw":!0,value:o,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?c.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const HM={type:"vector",Display:VM,Edit:zM},Df={string:hM,number:yM,boolean:wM,null:_M,timestamp:CM,geopoint:IM,reference:PM,bytes:MM,map:UM,array:FM,vector:HM};function Kg(e){return e?{...Df,...e}:Df}function Hi(e={}){const t=y.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=y.useState("wide");return y.useEffect(()=>{const o=t.current;if(!o||typeof ResizeObserver>"u")return;const a=new ResizeObserver(l=>{const u=l[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return a.observe(o),()=>a.disconnect()},[n,r]),{ref:t,size:s}}const Gg=y.createContext(null);function Jt(){const e=y.useContext(Gg);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function KM({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Wg({initial:e}),o=Kg(t),a=y.useRef(n);a.current=n,y.useEffect(()=>{a.current?.(i)},[i]);const{ref:l,size:u}=Hi();return c.jsx(Gg.Provider,{value:{editor:i,fieldEditors:o},children:c.jsx("div",{ref:l,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":i.isValid?"":void 0,"data-pyric-is-dirty":i.isDirty?"":void 0,"data-size":u,children:r})})}function GM(){const{editor:e}=Jt(),t=e.tree.childIds[e.tree.rootId]??[];return c.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>c.jsx(bl,{nodeId:n,path:JM(e,n)},n)),c.jsx(Jg,{parentId:e.tree.rootId})]})}function JM(e,t){const n=[];let r=e.tree.nodes[t];for(;r&&r.parentId!=null;){const s=e.tree.nodes[r.parentId];if(!s)break;if(s.type==="array"){const i=(e.tree.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${i}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,i)=>i.startsWith("[")?`${s}${i}`:s?`${s}.${i}`:i,"")}function bl({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Jt(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return c.jsx(XM,{node:s,path:t});if(s.type==="array")return c.jsx(ZM,{node:s,path:t});const o=r[s.type]?.Edit;if(!o)return null;const a=s.touched?s.error:void 0;return c.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":a?"":void 0,onBlur:()=>n.touch(s.id),children:[c.jsx(wl,{node:s,path:t}),c.jsx(o,{value:s.value,path:t,error:a,onChange:l=>n.setValue(s.id,l)})]})}function wl({node:e,path:t}){const{editor:n}=Jt(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:c.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?c.jsx("input",{type:"text",value:e.key??"",onChange:o=>n.setKey(e.id,o.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,c.jsx(QM,{node:e}),c.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const YM=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function QM({node:e}){const{editor:t}=Jt(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=YM.filter(s=>!(n?.type==="array"&&s==="array"));return c.jsx("select",{value:e.type,onChange:s=>t.setType(e.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>c.jsx("option",{value:s,children:s},s))})}function XM({node:e,path:t}){const{editor:n}=Jt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":e.key??void 0,children:[e.id!==n.tree.rootId?c.jsx(wl,{node:e,path:t}):null,c.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const o=t?`${t}.${i.key??""}`:i.key??"";return c.jsx(bl,{nodeId:s,path:o},s)})}),c.jsx(Jg,{parentId:e.id})]})}function ZM({node:e,path:t}){const{editor:n}=Jt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[c.jsx(wl,{node:e,path:t}),c.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const o=t?`${t}[${i}]`:`[${i}]`;return c.jsx("li",{"data-field-index":String(i),children:c.jsx(bl,{nodeId:s,path:o})},s)})}),c.jsx(eL,{parentId:e.id})]})}function Jg({parentId:e}){const{editor:t}=Jt();return c.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function eL({parentId:e}){const{editor:t}=Jt();return c.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Tf={Root:KM,Fields:GM};function tL({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):c.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(o=>c.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":o.id,children:c.jsx("button",{type:"button",onClick:()=>r?.(o),"data-pyric-collection-select":!0,children:o.id})},o.path))})}const ar=new Map;function vl({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=y.useRef(null),o=y.useRef(new Map),a=y.useRef(new Map),[l,u]=y.useState(ar);return y.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(ar)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(ar);return}const h=new Map;for(const[f,p]of t){const m=d.entries.has(f),g=d.entries.get(f);if(m&&n(g,p))continue;const b=o.current.get(f)===0?1:0;o.current.set(f,b),h.set(f,{kind:m?"modified":"added",cycle:b})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let m=h.size>0;for(const g of f.keys())t.has(g)||(p.delete(g),m=!0);for(const[g,b]of h)p.set(g,b);return m?p.size===0?ar:p:f});for(const[f,p]of h){const m=a.current.get(f);m&&clearTimeout(m);const g=setTimeout(()=>{a.current.delete(f),u(b=>{if(b.get(f)?.cycle!==p.cycle)return b;const w=new Map(b);return w.delete(f),w.size===0?ar:w})},r);a.current.set(f,g)}},[r,t,n,s,e]),y.useEffect(()=>()=>{for(const d of a.current.values())clearTimeout(d);a.current.clear()},[]),l}function cr(e){return e.ref}function nL({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:o,renderRowAction:a,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const m=y.useMemo(()=>new Map(e.map(w=>[cr(w).path,w.data()])),[e]),g=vl({scope:d,entries:m,equals:Si,ready:!t});if(n)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const b=e.length>h;return c.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":b?"":void 0,children:[b?c.jsx(dl,{items:e,estimateSize:f,height:p,getItemKey:w=>cr(w).path,renderItem:w=>{const x=g.get(cr(w).path);return c.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(cr(w)),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]})}}):c.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(w=>{const x=cr(w),v=g.get(x.path);return c.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(x),"data-pyric-document-select":!0,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]},x.path)})}),r&&i?c.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const rL=/^__.*__$/;function Yg(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(rL.test(e))return"Cannot match __.*__ (reserved)";if(iL(e)>1500)return"Cannot exceed 1500 bytes"}function sL(e){return Yg(e)}function iL(e){return new TextEncoder().encode(e).length}function oL(e){return Yg(e)}const Mf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function aL(){let e="";for(let t=0;t<20;t++)e+=Mf.charAt(Math.floor(Math.random()*Mf.length));return e}const cL={ref:Pr,listAll:Gc,getMetadata:KC,getBlob:HC,uploadBytes:WC,uploadBytesResumable:zC,deleteObject:vm},Qg=y.createContext(cL);function Ki(){return y.useContext(Qg)}function lL({value:e,children:t}){return y.createElement(Qg.Provider,{value:e},t)}function Fo(e){return e.replace(/^\/+|\/+$/g,"")}function sc(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function qo(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(sc)}function uL(e,t){const{listAll:n,ref:r}=Ki(),s=Fo(t),[i,o]=y.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[a,l]=y.useState(0),u=y.useRef(new Map);y.useEffect(()=>{if(u.current.clear(),e==null){o({status:"idle",items:[],prefixes:[],error:void 0});return}let m=!1;return o({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{m||o({status:"success",items:[...g.items].sort(sc),prefixes:[...g.prefixes].sort(sc),error:void 0})}).catch(g=>{m||o({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{m=!0}},[e,s,a]);const d=y.useCallback(()=>l(m=>m+1),[]),h=y.useCallback(m=>{if(e==null)return;const g=m.endsWith("/"),b=Fo(m),w=s===""?"":`${s}/`;if(!b.startsWith(w)||b===s)return;const x=b.slice(w.length),v=x.indexOf("/");o(_=>{if(_.status==="idle")return _;if(v===-1)return g?(u.current.set(b,_.prefixes.some(k=>k.fullPath===b)?null:b),{..._,prefixes:qo(_.prefixes,r(e,b))}):(u.current.set(b,_.items.some(k=>k.fullPath===b)?null:b),{..._,items:qo(_.items,r(e,b))});const S=`${w}${x.slice(0,v)}`;return u.current.set(b,_.prefixes.some(k=>k.fullPath===S)?null:S),{..._,prefixes:qo(_.prefixes,r(e,S))}})},[e,s]),f=y.useCallback(m=>{const g=Fo(m),b=u.current.get(g);if(u.current.delete(g),b===null)return;const w=b??g;o(x=>({...x,items:x.items.filter(v=>v.fullPath!==w),prefixes:x.prefixes.filter(v=>v.fullPath!==w)}))},[]),p=y.useMemo(()=>[...i.prefixes.map(m=>({kind:"folder",name:m.name,fullPath:m.fullPath,ref:m})),...i.items.map(m=>({kind:"object",name:m.name,fullPath:m.fullPath,ref:m}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:h,removeItem:f}}function de(e){return e.split("/").filter(Boolean).join("/")}function dL(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,o]=y.useState(()=>de(r)),a=s?de(t):i,l=y.useCallback(p=>{const m=de(p);s||o(m),n?.(m)},[s,n]),u=y.useMemo(()=>a===""?[]:a.split("/"),[a]),d=y.useCallback(p=>{const m=de(p);l(m.includes("/")||a===""?m:`${a}/${m}`)},[a,l]),h=y.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=y.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:a,segments:u,setPath:l,enter:d,up:h,navigateToIndex:f}}const Lf={status:"idle",blob:void 0,url:void 0,error:void 0};function fL(e,t){const{getBlob:n,getMetadata:r,ref:s}=Ki(),i=t==null?null:de(t),o=e!=null&&i!=null&&i!=="",[a,l]=y.useState(()=>({status:o?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=y.useState(Lf),[h,f]=y.useState(0),p=y.useRef(0);y.useEffect(()=>{if(p.current++,d(Lf),!o){l({status:"idle",metadata:void 0,error:void 0});return}let w=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(x=>{w||l({status:"success",metadata:x,error:void 0})}).catch(x=>{w||l({status:"error",metadata:void 0,error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[e,i,h]);const m=u.url;y.useEffect(()=>{if(m!==void 0)return()=>{URL.revokeObjectURL(m)}},[m]);const g=y.useCallback(()=>f(w=>w+1),[]),b=y.useCallback(()=>{if(e==null||i==null||i==="")return;const w=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(x=>{w===p.current&&d({status:"success",blob:x,url:URL.createObjectURL(x),error:void 0})}).catch(x=>{w===p.current&&d({status:"error",blob:void 0,url:void 0,error:x instanceof Error?x:new Error(String(x))})})},[e,i]);return{status:a.status,metadata:a.metadata,error:a.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:b}}function hL(){const[e,t]=y.useState(()=>new Map),n=y.useCallback(u=>e.has(u),[e]),r=y.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const h=new Map(d);return h.set(u.fullPath,u),h})},[]),s=y.useCallback(u=>{t(d=>{if(!d.has(u))return d;const h=new Map(d);return h.delete(u),h})},[]),i=y.useCallback(u=>{t(d=>{const h=new Map(d);return h.has(u.fullPath)?h.delete(u.fullPath):h.set(u.fullPath,u),h})},[]),o=y.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),a=y.useCallback(()=>t(new Map),[]);return{selected:y.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:o,clear:a}}function pL(e,t){const n=Pr(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function mL(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function yL(e){return{async*start(t){const n=e??{listAll:Gc,deleteObject:vm};let r=0;const s=[t],i=[];for(;s.length>0;){const o=s.pop();i.push(o);const a=await n.listAll(o);s.push(...a.prefixes);for(const l of a.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const o of i)try{await n.deleteObject(mL(o))}catch{}yield{deletedCount:r,done:!0}}}}function gL(e,t={}){const n=Ki(),[r,s]=y.useState(0),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(0),d=y.useRef(t);return d.current=t,{deleteEntries:y.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const m={deleted:[],failed:[]};if(e==null||f.length===0)return m;o(!0);const g=d.current.impl??yL(n);let b=0;try{for(const w of f){d.current.list?.removeItem(w.fullPath);try{if(w.kind==="object")await n.deleteObject(n.ref(e,w.fullPath)),b++;else for await(const x of g.start(n.ref(e,w.fullPath))){if(p!==u.current)return m;if(s(b+x.deletedCount),x.done){b+=x.deletedCount;break}}m.deleted.push(w.fullPath),p===u.current&&s(b)}catch(x){const v=x instanceof Error?x:new Error(String(x));m.failed.push({fullPath:w.fullPath,error:v}),d.current.list?.insertItem(w.kind==="folder"?`${w.fullPath}/`:w.fullPath),p===u.current&&m.failed.length===1&&l(v)}}return m}finally{p===u.current&&o(!1)}},[n,e]),progress:r,isRunning:i,error:a}}const bL=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),wL=Object.freeze({read:!1,write:!1,delete:!1,upload:!1,reasons:Object.freeze({read:["No Storage rules configured; default deny."],write:["No Storage rules configured; default deny."]})});function vL(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,o=e==null?null:e[$i],[a,l]=y.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));y.useEffect(()=>{if(o==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const x=typeof r=="string"?pa(r):r;l({status:"ready",rules:x,source:"option",error:void 0})}catch(x){l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}return}let w=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),o.servicePromise.then(x=>{w||l({status:"ready",rules:x.rules,source:x.rules?"sandbox":"none",error:void 0})}).catch(x=>{w||l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[o,r]);const u=s!==void 0?s:o?.context.auth??null,{rules:d,status:h}=a,f=i?.size,p=i?.contentType,m=y.useCallback(w=>{if(d==null)return h==="ready"?wL:bL;const x=de(w),v=o?.bucket??"pyric-default",_=x===""?`b/${v}/o`:`b/${v}/o/${x}`,S=A=>fm(d,{request:{auth:u,method:A,path:_,...A==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),k=S("read"),R=S("create"),O=S("delete"),P=R;return{read:k.allowed,write:P.allowed,delete:O.allowed,upload:R.allowed,reasons:{read:k.allowed?[]:k.reasons,write:P.allowed?[]:P.reasons}}},[d,h,o?.bucket,u,f,p]),g=typeof n=="string"?n:(n??[]).join(`
145
+ `),b=y.useMemo(()=>{const w=typeof n=="string"?[n]:n??[],x={};for(const v of w)x[de(v)]=m(v);return x},[g,m]);return{status:h,source:a.source,advisory:!1,identity:u,verdicts:b,verdictFor:m,error:a.error}}function Uf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function xL(e){return e instanceof Blob?e.size:e.byteLength}function _L(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function SL(e,t={}){const{ref:n,uploadBytes:r}=Ki(),s=de(t.path??""),[i,o]=y.useState([]),a=y.useRef(t);a.current=t;const l=y.useCallback(f=>{o(p=>p.map(m=>m.id===f.id?f:m))},[]),u=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=(Array.isArray(f)?f:[f]).map(g=>{const b=_L(g);return{task:{id:crypto.randomUUID(),fullPath:Uf(s,de(b.path)),status:"running",bytesTransferred:0,totalBytes:xL(b.data)},entry:b}});o(g=>[...g,...m.map(b=>b.task)]);for(const{task:g}of m)a.current.list?.insertItem(g.fullPath),a.current.onProgress?.(g);return Promise.all(m.map(async({task:g,entry:b})=>{try{const w=await r(n(e,g.fullPath),b.data,b.metadata),x={...g,status:"success",bytesTransferred:g.totalBytes,metadata:w.metadata};return l(x),a.current.onProgress?.(x),a.current.onComplete?.(x),x}catch(w){const x={...g,status:"error",error:w instanceof Error?w:new Error(String(w))};return a.current.list?.removeItem(g.fullPath),l(x),a.current.onError?.(x),x}}))},[e,s,l,n,r]),d=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=Uf(s,de(f));if(p==="")throw new Error("createFolder: folder name is empty");a.current.list?.insertItem(`${p}/`);try{await r(pL(e,p),new Blob([]),{contentType:"text/plain"})}catch(m){throw a.current.list?.removeItem(p),m}},[e,s,r]),h=y.useCallback(()=>{o(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:h}}function kL({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=de(e),o=i===""?[]:i.split("/");return c.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:c.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[c.jsx("li",{"data-pyric-breadcrumb-item":!0,children:c.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":o.length===0?"":void 0,"aria-current":o.length===0?"page":void 0,children:n})}),o.map((a,l)=>{const u=l===o.length-1,d=o.slice(0,l+1).join("/");return c.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),c.jsx("button",{type:"button",onClick:()=>t?.(d),"data-pyric-breadcrumb-link":!0,"data-pyric-current":u?"":void 0,"aria-current":u?"page":void 0,children:a})]},d)})]})})}function EL({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:o,renderEntry:a,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:m,size:g}=Hi();if(n)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((t==="loading"||t==="idle")&&e.length===0)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-loading":t==="loading"?"":void 0,"data-pyric-idle":t==="idle"?"":void 0});if(e.length===0)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const b=v=>{if(!o)return{denied:!1};const _=o.verdictFor(v.fullPath);return _.read?{denied:!1}:{denied:!0,reason:_.reasons.read.join("; ")}},w=v=>{const _=v.kind==="object"&&v.fullPath===i;return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:()=>v.kind==="folder"?r?.(v.fullPath):s?.(v.ref),"data-pyric-entry-select":!0,"data-pyric-selected":_?"":void 0,"aria-selected":_||void 0,children:a?a(v):v.name}),l?c.jsx("span",{"data-pyric-storage-action":!0,children:l(v)}):null]})},x=e.length>h;return c.jsx("div",{ref:m,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":x?"":void 0,children:x?c.jsx(dl,{items:e,estimateSize:f,height:p,getItemKey:v=>`${v.kind}:${v.fullPath}`,renderItem:v=>{const _=b(v);return c.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)})}}):c.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(v=>{const _=b(v);return c.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)},`${v.kind}:${v.fullPath}`)})})})}async function Xg(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,o)=>e.file(i,o));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((o,a)=>s.readEntries(o,a));if(i.length===0)break;for(const o of i)await Xg(o,r,n)}}}async function jL(e){const t=[],n=e.items?Array.from(e.items):[];for(const r of n){if(r.kind!=="file")continue;const s=r.webkitGetAsEntry,i=typeof s=="function"?s.call(r):null;if(i)await Xg(i,"",t);else{const o=r.getAsFile?.();o&&t.push({file:o,relativePath:o.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function CL({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,o]=y.useState(!1),a=y.useRef(0),l=y.useCallback(f=>{f.preventDefault(),!n&&(a.current+=1,o(!0))},[n]),u=y.useCallback(f=>{f.preventDefault()},[]),d=y.useCallback(f=>{f.preventDefault(),!n&&(a.current=Math.max(0,a.current-1),a.current===0&&o(!1))},[n]),h=y.useCallback(f=>{if(f.preventDefault(),a.current=0,o(!1),n)return;const p=f.dataTransfer;p&&jL(p).then(m=>{m.length>0&&e(m)})},[n,e]);return c.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":i?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:l,onDragOver:u,onDragLeave:d,onDrop:h,children:t})}function RL(e){const t=e.lastIndexOf(".");return t<=0||t===e.length-1?{stem:e,ext:""}:{stem:e.slice(0,t),ext:e.slice(t)}}function NL(e){const t=/^(.*) \((\d+)\)$/.exec(e);if(!t)return{base:e,counter:null};const n=Number(t[2]);return Number.isSafeInteger(n)?{base:t[1],counter:n}:{base:e,counter:null}}function Bf(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=RL(e),{base:s,counter:i}=NL(n);let o=i===null?1:i+1;for(;;){const a=`${s} (${o})${r}`;if(!t.has(a))return a;o+=1}}function IL(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=Bf(s,n);return n.add(l),l}const o=s.slice(0,i);let a=r.get(o);return a===void 0&&(a=Bf(o,n),n.add(a),r.set(o,a)),`${a}${s.slice(i)}`})}function Ff(e){const t=de(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Zg=[];function AL(e,t){switch(t.type){case"create":{const n=Ff(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Ff(t.path));if(n.size===0)return e;const r=e.filter(s=>!n.has(s));return r.length===e.length?e:r}case"discard":{const n=de(t.path);if(n==="")return e;const r=e.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===e.length?e:r}case"clear":return e.length===0?e:Zg}}function OL(e,t){const n=de(t),r=n===""?"":`${n}/`;return e.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function qf(e,t){return e.includes(de(t))}function $L(e){const t=de(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const PL=256*1024;function ic(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const DL={id:"image",match:e=>ic(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?c.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function TL({blob:e,isJson:t}){const[n,r]=y.useState(void 0);return y.useEffect(()=>{let s=!1;return e.text().then(i=>{if(!s){if(t)try{r(JSON.stringify(JSON.parse(i),null,2));return}catch{}r(i)}}),()=>{s=!0}},[e,t]),n===void 0?null:c.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const ML={id:"text",match:e=>{const t=ic(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:PL,render:({metadata:e,blob:t})=>t?c.jsx(TL,{blob:t,isJson:ic(e)==="application/json"}):null},LL=[DL,ML];function UL(e,t){for(const n of[...t??[],...LL])if(n.match(e))return n}const BL=[{key:"fullPath",label:"Path",value:e=>e.fullPath},{key:"size",label:"Size",value:e=>`${e.size}`},{key:"contentType",label:"Content type",value:e=>e.contentType},{key:"cacheControl",label:"Cache control",value:e=>e.cacheControl},{key:"timeCreated",label:"Created",value:e=>e.timeCreated},{key:"updated",label:"Updated",value:e=>e.updated}];function FL({metadata:e}){return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[BL.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":t,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[c.jsx("dt",{children:t}),c.jsx("dd",{children:n})]},`custom:${t}`))]})}function qL({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:o,size:a}=Hi(),l=fL(e,t),{metadata:u,blobStatus:d,loadBlob:h}=l,f=u?UL(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,m=f?.needsBlob===!0&&!p;if(y.useEffect(()=>{m&&d==="idle"&&h()},[m,d,h]),l.status==="idle")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,b={};return f===void 0?b={"data-pyric-preview-none":""}:p?b={"data-pyric-preview-too-large":""}:m&&d==="loading"?b={"data-pyric-preview-loading":""}:m&&d==="error"?(b={"data-pyric-preview-error":""},g=l.blobError?.message):(!m||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),c.jsxs("div",{ref:o,className:i,"data-pyric-ui":"object-inspector","data-size":a,children:[c.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):c.jsx(FL,{metadata:u}),c.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...b,children:g}),s]})}const eb=y.createContext(null);function VL(){const e=y.useContext(eb);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function WL({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=y.useState([]),o=y.useCallback(u=>{i(d=>d.filter(h=>h.id!==u))},[]),a=y.useCallback(u=>{const d=crypto.randomUUID(),h=u.duration??t;return i(f=>[...f,{id:d,...u}]),h>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},h),d},[t]),l=y.useMemo(()=>({toast:a,dismiss:o,toasts:s}),[a,o,s]);return c.jsxs(eb.Provider,{value:l,children:[e,c.jsx(zL,{toasts:s,dismiss:o,className:n,regionLabel:r})]})}function zL({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=y.useState(!1);return y.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:ul.createPortal(c.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(o=>c.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":o.kind??"info",role:o.kind==="error"?"alert":"status",children:[c.jsx("div",{"data-pyric-toast-title":!0,children:o.title}),o.body?c.jsx("div",{"data-pyric-toast-body":!0,children:o.body}):null,c.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(o.id),children:"×"})]},o.id))}),document.body)}function HL({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:o,confirmLabel:a="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:h}){const f=Hn(),{toast:p}=VL(),{deleteEntries:m,isRunning:g,progress:b}=gL(e,{impl:n,list:r}),w=s?t.map(S=>({entry:S,verdict:s.verdictFor(S.fullPath)})).filter(S=>!S.verdict.delete):[],x=w.length===0?void 0:`Delete denied for ${w[0].entry.fullPath}${w.length>1?` (+${w.length-1} more)`:""}: ${w[0].verdict.reasons.write.join("; ")}`,v=g||t.length===0||e==null||w.length>0,_=async()=>{if(v||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:o??c.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(R=>c.jsxs("li",{"data-pyric-entry-kind":R.kind,children:[R.fullPath,R.kind==="folder"?"/":""]},R.fullPath))}),destructive:!0,confirmLabel:a}))return;const k=await m(t);k.failed.length===0?(p({title:`Deleted ${k.deleted.length} ${k.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(k)):(p({title:`Delete failed for ${k.failed.length} of ${t.length}`,kind:"error",body:c.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:k.failed.map(R=>c.jsxs("li",{children:[R.fullPath,":"," ",R.error.code??R.error.message]},R.fullPath))})}),u?.(k))};return d?c.jsx(c.Fragment,{children:d({onClick:_,isRunning:g,progress:b,disabled:v,deniedReason:x})}):c.jsx("button",{type:"button",onClick:_,className:h,disabled:v,title:x,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":x?"":void 0,"data-pyric-denied-reason":x,children:g?`Deleting… (${b})`:a})}function Gr(e){const t=e.split("/").filter(Boolean),n=[];let r="";return t.forEach((s,i)=>{r=r?`${r}/${s}`:s,n.push({kind:i%2===0?"collection":"document",id:s,path:r})}),n}function tb(e){const t=e.indexOf("?");return ol(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function KL(e){const{tab:t,rest:n,query:r}=tb(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:Gr(s)}:t==="auth"?{view:"auth",uid:n[0]??null}:t==="storage"?s?{view:"storage",kind:r.kind==="prefix"?"prefix":"object",path:s}:{view:"storage",kind:"root"}:null}function nb(e){switch(e.view){case"firestore":{const t=e.path[e.path.length-1];return{tab:"firestore",rest:t?t.path.split("/").filter(Boolean):[]}}case"auth":return{tab:"auth",rest:e.uid?[e.uid]:[]};case"storage":return e.kind==="root"?{tab:"storage"}:{tab:"storage",rest:e.path.split("/").filter(Boolean),...e.kind==="prefix"?{query:{kind:"prefix"}}:{}}}}function rb(e){const{tab:t,query:n}=tb(e),r=KL(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Vf=null,oc=rb("");function GL(){const e=al();return e!==Vf&&(Vf=e,oc=rb(e)),oc}function JL(){return oc}function $s(e){Ie(nb(e))}function YL(e){Ie({tab:"traffic",query:{inspect:e}})}function Gi(){const e=y.useSyncExternalStore(Kt,GL,JL),t=y.useCallback(s=>$s(s),[]),n=y.useCallback(s=>{switch(s.kind){case"user":$s({view:"auth",uid:s.uid});break;case"storage":$s({view:"storage",kind:"object",path:s.objectPath});break;case"document":$s({view:"firestore",path:Gr(s.path)});break}},[]),r=y.useCallback(s=>YL(s),[]);return y.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const QL={narrowBreakpoint:640,mediumBreakpoint:920};function XL(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function ZL(e,t){const n=XL(t),r=Math.min(Math.max(e,1),n),s=Math.max(e-r,0),i=t==="narrow"?0:n-r;return{startIndex:s,visibleCount:r,emptySlots:i}}function Vo({label:e,error:t,hint:n,children:r}){return c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:e}),r,t?c.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?c.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function sb({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=y.useState(""),[o,a]=y.useState(()=>aL()),[l,u]=y.useState(null),[d,h]=y.useState(null),[f,p]=y.useState(!1),m=y.useRef(null),g=e==="collection"&&s?sL(s):void 0,b=o?oL(o):void 0,x=!(e==="collection"&&(!s||g))&&!!o&&!b&&!f;y.useEffect(()=>{const S=k=>{k.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f,r]);const v=async()=>{if(!(!x||!l)){if(!l.isValid){l.touchAll();return}p(!0),h(null);try{await n({collectionId:e==="collection"?s:null,docId:o,data:Ug(l.tree)}),r()}catch(S){h(S instanceof Error?S:new Error(String(S))),p(!1)}}},_=e==="collection"?"Start a collection":"Add a document";return c.jsx("div",{className:"fs-modal-backdrop",onMouseDown:S=>{S.target===S.currentTarget&&!f&&r()},children:c.jsxs("div",{ref:m,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":_,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[c.jsx("h2",{className:"fs-modal__title",children:_}),c.jsx(Vo,{label:"Parent path",children:c.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?c.jsx(Vo,{label:"Collection ID",error:g,children:c.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:S=>i(S.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,c.jsx(Vo,{label:"Document ID",error:o?b:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:c.jsx("input",{autoFocus:e==="document",type:"text",value:o,onChange:S=>a(S.target.value),"data-pyric-field":"doc-id","aria-invalid":b||!o?"true":void 0})}),c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:"Fields"}),c.jsx("div",{className:"fs-modal__fields",children:c.jsx(Tf.Root,{initial:{},onChange:u,children:c.jsx(Tf.Fields,{})})})]}),d?c.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,c.jsxs("div",{className:"fs-modal__actions",children:[c.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),c.jsx("button",{type:"button",className:"fs-editor__save",disabled:!x,onClick:()=>void v(),children:f?"Saving…":"Save"})]})]})})}function ib({items:e,label:t="More actions"}){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useRef(null),a=()=>{if(!n){const l=o.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return y.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),o.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),c.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[c.jsx("button",{ref:o,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:a,children:c.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),c.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>c.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":l.destructive?"":void 0,disabled:l.disabled,onClick:()=>{r(!1),l.onSelect()},children:l.label},l.label))})]}):null]})}function ob(e){return JSON.stringify(e)}function eU(e,t){const n=new Map,r=(s,i)=>{const o=t(s),a=ob(i);if(o==="map"){const l=s,u=Object.keys(l).sort();n.set(a,[o,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(o==="array"){const l=s;n.set(a,[o,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(a,[o,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function ab(e,t){const n=[];let r=e.nodes[t];for(;r&&r.parentId!=null;){const s=e.nodes[r.parentId];if(!s)break;s.type==="array"?n.unshift(["index",(e.childIds[s.id]??[]).indexOf(r.id)]):n.unshift(["field",r.key??""]),r=s}return ob(n)}function tU(e,t){const n=[];let r=e.nodes[t];for(;r&&r.parentId!=null;){const s=e.nodes[r.parentId];if(!s)break;if(s.type==="array"){const i=(e.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${i}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,i)=>i.startsWith("[")?`${s}${i}`:s?`${s}.${i}`:i,"")}function nU(e,t){const n=e.nodes[t],r=n?.parentId!=null?e.nodes[n.parentId]:null;if(r?.type==="array"){const s=(e.childIds[r.id]??[]).indexOf(t);return{label:String(s),isArrayChild:!0}}return{label:n?.key??"",isArrayChild:!1}}function Wf(e,t,n){switch(e.type){case"map":return"{…}";case"array":return"[…]";case"string":return JSON.stringify(e.value);case"null":return"null";case"vector":{const r=t(e.value);return r?n(r):"vector"}default:return String(e.value)}}const rU=42;function sU(e,t,n,r=rU){const s=e.nodes[t],i=e.childIds[t]??[];let o;return s.type==="array"?o=`[${i.slice(0,3).map(l=>Wf(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:o=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${Wf(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,o.length>r?`${o.slice(0,r-1)}…`:o}function iU(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function oU(e){return e.shiftKey===!0}const cb=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],aU=[...cb,"map","array"];function cU({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:o,onStartCollection:a,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const h=y.useMemo(()=>e?.data()??{},[e]),f=y.useMemo(()=>h,[]),p=Wg({initial:f}),m=p.replaceData,g=y.useMemo(()=>Kg(i),[i]),b=Hn(),[w,x]=y.useState(()=>new Set),[v,_]=y.useState(null),S=y.useRef(e),k=y.useRef(new Set),R=y.useRef(!1),[O,P]=y.useState(null),A=y.useMemo(()=>eU(h,zi),[h]),E=vl({scope:t.path,entries:A,equals:Si,ready:v===null});y.useEffect(()=>{R.current&&(R.current=!1,P(null),n(p.toData()).catch(U=>{P(U instanceof Error?U:new Error(String(U)))}))},[p.tree]),y.useEffect(()=>{!e||e===S.current||v!==null||(S.current=e,k.current.clear(),m(e.data()??{}))},[v,m,e]);const j=y.useCallback(U=>{x(V=>{const B=new Set(V);return B.has(U)?B.delete(U):B.add(U),B})},[]),[$,C]=y.useState(null),N=y.useCallback((U,V)=>{if(V==="map"?p.addMapEntry(U,"","string"):p.addArrayEntry(U,"string"),U!==p.tree.rootId){const B=ab(p.tree,U);x(_e=>new Set(_e).add(B))}C(U)},[p]);y.useEffect(()=>{if(!$)return;const U=p.tree.childIds[$]??[],V=U[U.length-1];V&&!v&&(k.current.add(V),_(V),C(null))},[p.tree,$]);const I=y.useCallback(U=>{p.remove(U),k.current.delete(U),R.current=!0,v===U&&_(null)},[p,v]),M=y.useCallback(async(U,V,B)=>{if(oU(B)){I(U.id);return}await b({title:`Delete field "${V}"?`,destructive:!0,confirmLabel:"Delete"})&&I(U.id)},[b,I]),T=t.id,F=p.tree.childIds[p.tree.rootId]??[];return c.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[c.jsxs("div",{className:"fs-doctree__head",children:[c.jsx("span",{className:"fs-doctree__docid",children:T}),c.jsx(ib,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await b({title:"Delete all fields?",body:"The document itself is kept, empty.",destructive:!0,confirmLabel:"Delete fields"})&&s())()},destructive:!0},{label:"Delete document",onSelect:r,destructive:!0}]})]}),O?c.jsx("p",{className:"fs-doctree__err",children:O.message}):null,c.jsxs("ul",{className:"fs-doctree__rows",children:[a?c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:a,children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>N(p.tree.rootId,"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),F.map(U=>c.jsx(lb,{nodeId:U,depth:0,editor:p,registry:g,expanded:w,onToggle:j,editingId:v,setEditingId:_,newIdsRef:k,onAdd:N,onDelete:M,onCommitNeeded:()=>{R.current=!0},onReferenceClick:o,updates:E},U))]}),l&&u?c.jsx(ub,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function lb({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p}){const{tree:m}=n,g=m.nodes[e];if(!g)return null;const{label:b,isArrayChild:w}=nU(m,e),x=g.type==="map"||g.type==="array",v=tU(m,e),_=ab(m,e),S=p.get(_),k=s.has(_),R=o===e,O=l.current.has(e);return R?c.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:c.jsx(lU,{node:g,isNew:O,isArrayChild:w,tree:m,editor:n,registry:r,path:v,onCommitNeeded:h,onDone:()=>{l.current.delete(e),a(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),a(null)}})}):c.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":x?"":void 0,style:{"--fs-depth":t},children:[c.jsxs("div",{className:"fs-doctree__line","data-pyric-update":S?.kind,"data-pyric-update-cycle":S?.cycle,children:[x?c.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":k,onClick:()=>i(_),children:c.jsx("span",{"aria-hidden":"true",children:k?"▼":"▶"})}):c.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),w?c.jsx("span",{className:"fs-doctree__chip",children:b}):c.jsx("span",{className:"fs-doctree__key",children:b}),x?k?null:c.jsx("span",{className:"fs-doctree__preview",children:sU(m,e,{asVectorView:pn,vectorPreview:Mg})}):c.jsx("span",{className:"fs-doctree__value",children:c.jsx(rc,{value:g.value,path:v,fieldEditors:r})}),c.jsxs("span",{className:"fs-doctree__hover",children:[c.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),x?c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${b||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${b}`,onClick:()=>a(e),children:"✎"}),c.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${b||"field"} (shift-click to skip confirmation)`,onClick:P=>void d(g,b,{shiftKey:P.shiftKey}),children:"🗑"})]})]}),x&&k?c.jsxs("ul",{className:"fs-doctree__children",children:[(m.childIds[e]??[]).map(P=>c.jsx(lb,{nodeId:P,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p},P)),c.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function lU({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:o,onCommitNeeded:a,onDone:l,onCancelNew:u}){const[d,h]=y.useState(e.key??""),[f,p]=y.useState(e.type),[m,g]=y.useState(e.value),[b,w]=y.useState(!1),x=n?void 0:d===""?"Field name is required":iU(r,e,d)?"Field name must be unique":void 0,v=f==="map"||f==="array"?void 0:Fg(f,m),_=!x&&!v,S=()=>{if(!_){w(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,m),a(),l()},k=()=>{t?u():l()},O=i[f]?.Edit,P=f!=="map"&&f!=="array"&&O?c.jsx(O,{value:m,path:o,error:b?v:void 0,onChange:j=>g(j)}):f==="map"||f==="array"?c.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,A=c.jsxs("span",{className:"fs-doctree__editactions",children:[c.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:S,"aria-label":"Save field",children:"✓"}),c.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:k,"aria-label":"Cancel edit",children:"✕"})]}),E=c.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:j=>{const $=j.target.value;p($),$!=="map"&&$!=="array"&&$!==f&&g(uU($))},"aria-label":"Field type",children:(t?aU:cb).map(j=>c.jsx("option",{value:j,children:j},j))});return c.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:j=>{j.key==="Enter"&&!j.target.matches("textarea")?(j.preventDefault(),S()):j.key==="Escape"&&(j.preventDefault(),k())},children:[n?null:c.jsxs("div",{className:"fs-doctree__editline",children:[c.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:j=>h(j.target.value),onBlur:()=>w(!0),"aria-label":"Field name","aria-invalid":b&&x?"true":void 0}),E]}),c.jsxs("div",{className:"fs-doctree__editline",children:[n?E:null,P,A]}),b&&x?c.jsx("span",{className:"fs-doctree__editerr",children:x}):null]})}function uU(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function ub({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=uM({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:c.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[c.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),c.jsx("ul",{className:"fs-doctree__sublist",children:s.map(o=>c.jsx("li",{children:r?c.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(o),"aria-label":`Open subcollection ${o.id}`,children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),c.jsx("span",{"aria-hidden":"true",children:"›"})]}):c.jsxs("div",{className:"fs-doctree__subrow",children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},o.path))})]})}function dU(e){return e.split("/").filter(Boolean).length%2===0}function db(e,t){async function*n(s,i,o=!1){const a=await t.listSubcollections(s.path);for(const l of a)yield*r(e.collection(s,l),i);o||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const o=await t.listDocuments(s.path);for(const a of o){const l=a.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,a.phantom===!0))}}return{async*start(s){const i={n:0};dU(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function fb(e,t){for await(const n of e.start(t))if(n.done)return}async function hb({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:c.jsxs("label",{className:"fs-delete-recursive",children:[c.jsx("input",{type:"checkbox",onChange:o=>{s=o.currentTarget.checked}}),c.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await fb(r,t):await n.deleteDoc(t),!0):!1}function fU(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function hU(e,t,n,r){const s=e.doc(t,n),i=await e.getDoc(s);if(typeof i.exists=="function"?i.exists():!!i.exists)throw new Error(`Document "${n}" already exists here — choose a different ID.`);await e.setDoc(s,r)}function pU(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function zf(e){return e.__pyricPhantom===!0}function mU(e,t,n){const r=n.split("/");if(r.length===1)return e.collection(t,n);const s=r[r.length-1],i=r.slice(0,-1).join("/");return e.collection(e.doc(t,i),s)}function yU({handles:e}){const{target:t,navigate:n}=Gi(),r=e.adminFirestore,s=pl(),i=y.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),o=y.useCallback(_=>{const S=typeof _=="function"?_(i):_;n({view:"firestore",path:S})},[n,i]),a=(_,S)=>o(k=>[...k.slice(0,_+1),S]),[l,u]=y.useState(null),d=y.useCallback(async({collectionId:_,docId:S,data:k})=>{if(!l||!_)return;const R=l.parentDocPath,O=R?s.collection(s.doc(r,R),_):s.collection(r,_);await hU(s,O,S,k);const P=R?`${R}/${_}`:_;n({view:"firestore",path:Gr(`${P}/${S}`)})},[s,r,l,n]),h=[c.jsx(wU,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:_=>o([{kind:"collection",id:_,path:_}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((_,S)=>_.kind==="collection"?c.jsx(vU,{api:s,firestore:r,handles:e,collectionPath:_.path,selectedId:i[S+1]?.id??null,onSelect:k=>a(S,{kind:"document",id:k.id,path:k.path}),onCollectionDeleted:()=>o(k=>k.slice(0,S))},_.path):c.jsx(xU,{api:s,firestore:r,handles:e,docPath:_.path,onOpenSubcollection:k=>a(S,{kind:"collection",id:k.id,path:k.path}),onReferenceClick:k=>n({view:"firestore",path:Gr(k.path)}),onStartCollection:()=>u({parentDocPath:_.path}),onDeleted:()=>o(k=>k.slice(0,S))},_.path))],{ref:f,size:p}=Hi(QL),{startIndex:m,visibleCount:g,emptySlots:b}=ZL(h.length,p),w=h.slice(m,m+g),x=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,v=[...w,...Array.from({length:b},(_,S)=>c.jsx(bU,{hint:S===0?x:null},`__empty_${S}__`))];return y.useEffect(()=>{if(p==="wide")return;const _=f.current;if(!_)return;const S=document.activeElement;if(S&&S!==document.body&&_.contains(S))return;const k=_.querySelector(".fs-columns > .fs-col:last-child");k&&(k.tabIndex=-1,k.focus({preventScroll:!0}))},[i.length,p]),c.jsx(fl,{children:c.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[c.jsx(gU,{path:i,onHome:()=>o([]),onJump:_=>o(S=>S.slice(0,_+1))}),c.jsx("div",{className:"fs-columns",children:v}),l?c.jsx(sb,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function gU({path:e,onHome:t,onJump:n}){return c.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[c.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>c.jsxs(y.Fragment,{children:[c.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?c.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):c.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function bU({hint:e}){return c.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?c.jsx("p",{className:"fs-empty",children:e}):null})}function wU({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=y.useMemo(()=>n.map(o=>e.collection(t,o)),[e,t,n]);return c.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:"Collections"}),c.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),c.jsx(tL,{collections:i,onSelect:o=>r(o.id),emptyState:c.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function vU({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:o}){const a=y.useMemo(()=>mU(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:h,hasMore:f,loadMore:p,createDocument:m}=lM({collection:a,mode:"live"}),[g,b]=y.useState([]);y.useEffect(()=>{let E=!1;return Promise.resolve(n.listDocuments(r)).then(j=>{E||b(j.filter($=>$.phantom).map($=>$.path.split("/").pop()??""))}).catch(()=>{E||b([])}),()=>{E=!0}},[n,r,l]);const w=y.useMemo(()=>{const E=new Set(l.map(j=>j.id));return[...l,...g.filter(j=>j.length>0&&!E.has(j)).map(j=>pU(e.doc(t,`${r}/${j}`)))]},[l,g,e,t,r]),x=r.split("/").pop()??r,[v,_]=y.useState(null),[S,k]=y.useState(!1),R=Hn(),O=y.useMemo(()=>db(e,n),[e,n]),P=y.useCallback(async E=>{_(null);try{await hb({confirm:R,ref:E,api:e,recursiveImpl:O})}catch(j){_(j instanceof Error?j:new Error(String(j)))}},[e,R,O]),A=y.useCallback(async()=>{if(await R({title:`Delete collection "${x}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){_(null);try{await fb(O,a),o()}catch(j){_(j instanceof Error?j:new Error(String(j)))}}},[R,O,a,x,o]);return c.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:x}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:()=>k(!0),children:"+ New"})}),c.jsx(ib,{items:[{label:"Delete collection",onSelect:()=>void A(),destructive:!0}]})]}),S?c.jsx(sb,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:E,data:j})=>{const $=await m(E,j,{onExisting:"fail"});i($)},onClose:()=>k(!1)}):null,c.jsx(nL,{documents:w,isLoading:u,error:d,updateScope:`${r}:${h}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:E=>{const j=E.ref;return c.jsx("span",{"data-pyric-selected":s===j.id?"":void 0,style:{display:"contents"},children:zf(E)?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"fs-doc-phantom",children:E.id}),c.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):E.id})},renderRowAction:E=>{if(zf(E))return null;const j=E.ref;return c.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${j.id}`,onClick:$=>{$.stopPropagation(),P(j)},children:"×"})},emptyState:c.jsx("p",{className:"fs-empty",children:"No documents."})}),v?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:v.message}):null]})}function xU({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:o,onDeleted:a}){const l=y.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:h}=QT(l),f=y.useCallback(async(_,S)=>(await n.listSubcollections(S.path)).map(R=>e.collection(S,R)),[n,e]),p=Hn(),m=y.useMemo(()=>db(e,n),[e,n]),[g,b]=y.useState(null),w=y.useCallback(async()=>{b(null);try{await hb({confirm:p,ref:l,api:e,recursiveImpl:m})&&a()}catch(_){b(_ instanceof Error?_:new Error(String(_)))}},[e,p,m,l,a]),x=y.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),v=u!=null&&fU(u);return c.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[v?null:c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:l.id}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:o,children:"+ Collection"})})]}),u&&v?c.jsx(cU,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:o,onDeleteDocument:()=>void w(),onDeleteDocumentFields:x,onCommit:async _=>{await e.setDoc(l,_)}},r):d?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):h?c.jsx("p",{className:"fs-empty",children:"Loading document…"}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"fs-empty",children:"This document does not exist."}),c.jsx(ub,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const _U="block w-full text-sm text-soft-white";function SU({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:o,setFilter:a,updateUser:l}=Vi(e),[u,d]=y.useState(null);y.useEffect(()=>{t&&(d(t),a(t))},[t,a]);const h=n.find(f=>f.uid===u)??null;return c.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[c.jsxs("section",{className:"min-w-0",children:[c.jsx("input",{value:o,onChange:f=>a(f.target.value),placeholder:"Filter users…",className:"mb-3 w-full rounded border border-border bg-content-bg px-3 py-1.5 text-sm text-soft-white placeholder:text-slate-gray"}),c.jsx(kg,{users:n,isLoading:s,error:i,filter:o,onSelect:f=>d(f.uid),className:_U,emptyState:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users yet. Sign in from the app, or the agent seeds them, and they appear here."}),noResultsState:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),c.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),c.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:h?c.jsx(kU,{user:h,onSave:f=>l(h.uid,f)},h.uid):c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function kU({user:e,onSave:t}){const n=_g({initial:e}),[r,s]=y.useState(null),[i,o]=y.useState(!1),a=()=>{s(null),o(!1);try{t(n.toUpdateRequest()),o(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return c.jsxs("div",{"data-pyric-ui":"auth-editor",children:[c.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",c.jsx("input",{value:n.fields.displayName,onChange:l=>n.setField("displayName",l.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",c.jsx("textarea",{value:n.fields.claimsText,onChange:l=>n.setField("claimsText",l.target.value),rows:6,spellCheck:!1,className:"mt-1 w-full rounded border border-border bg-content-bg p-2 font-mono text-xs text-soft-white"}),n.errors.claims?c.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),c.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[c.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?c.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?c.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:a,disabled:!n.isValid||!n.isDirty,className:"rounded bg-primary/15 px-3 py-1 text-xs font-medium text-primary hover:bg-primary/25 disabled:opacity-40",children:"Save"}),c.jsx("button",{type:"button",onClick:n.reset,disabled:!n.isDirty,className:"rounded border border-border px-3 py-1 text-xs text-slate-gray hover:text-soft-white disabled:opacity-40",children:"Reset"})]})]})}function Hf(e){const t=de(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Kf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Gf(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const EU=[{key:"size",label:"size",value:e=>`${e.size} bytes`},{key:"contentType",label:"content type",value:e=>e.contentType},{key:"timeCreated",label:"created",value:e=>e.timeCreated},{key:"updated",label:"updated",value:e=>e.updated},{key:"md5Hash",label:"md5",value:e=>e.md5Hash},{key:"cacheControl",label:"cache control",value:e=>e.cacheControl},{key:"fullPath",label:"path",value:e=>`gs://${e.bucket}/${e.fullPath}`}];function jU(e){const t=Object.entries(e.customMetadata??{});return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[c.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),EU.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":n,children:[c.jsx("dt",{children:r}),c.jsx("dd",{children:i})]},n)}),t.length>0?c.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:r})]},`custom:${n}`))]})}function CU(){return c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:c.jsx("path",{d:"M1.75 4.25c0-.55.45-1 1-1h3.4l1.5 1.7h5.6c.55 0 1 .45 1 1v6.05c0 .55-.45 1-1 1H2.75c-.55 0-1-.45-1-1z"})})}function RU(){return c.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),c.jsx("path",{d:"M9.25 1.75v3h3"})]})}function NU(e){const t=e.kind==="folder";return c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"storage__cell-name",children:[c.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?c.jsx(CU,{}):c.jsx(RU,{})}),c.jsx("span",{className:"storage__nm",children:e.name}),t?c.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),c.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),c.jsx("span",{className:"storage__cell-size"}),c.jsx("span",{className:"storage__cell-updated"})]})}function IU({storage:e,focusTarget:t}){const n=Gi(),r=t.kind==="object"?de(t.path):null,s=t.kind==="prefix"?de(t.path):r?Hf(r):"",i=y.useCallback(E=>{const j=de(E);n.navigate(j?{view:"storage",kind:"prefix",path:j}:{view:"storage",kind:"root"})},[n.navigate]),o=dL({path:s,onPathChange:i}),a=E=>{n.navigate({view:"storage",kind:"object",path:de(E)})},l=uL(e,o.path),u=hL(),d=vL(e),[h,f]=y.useReducer(AL,Zg),p=SL(e,{path:o.path,list:l,onComplete:E=>f({type:"materialize",path:Hf(E.fullPath)})});y.useEffect(()=>{if(l.status==="success")for(const E of l.entries)E.kind==="folder"&&qf(h,E.fullPath)&&f({type:"materialize",path:E.fullPath})},[l.status,l.entries,h]);const[m,g]=y.useState(!1),[b,w]=y.useState(""),[x,v]=y.useState(null),_=y.useRef(null),S=y.useMemo(()=>{const E=OL(h,o.path).filter(C=>!l.entries.some(N=>N.kind==="folder"&&N.name===C));if(E.length===0)return l.entries;const j=E.map(C=>{const N=Kf(o.path,C);return{kind:"folder",name:C,fullPath:N,ref:{fullPath:N,name:C}}});return[...[...l.entries.filter(C=>C.kind==="folder"),...j].sort((C,N)=>C.name<N.name?-1:C.name>N.name?1:0),...l.entries.filter(C=>C.kind==="object")]},[l.entries,h,o.path]),k=S.length>0&&S.every(E=>u.isSelected(E.fullPath)),R=E=>{const j=new Set(S.map(C=>C.name)),$=IL(E.map(C=>C.relativePath),j);p.upload(E.map((C,N)=>({path:$[N],data:C.file})))},O=E=>{E.preventDefault();const j=$L(b);if(j){v(j);return}const $=Kf(o.path,de(b));f({type:"create",path:$}),o.setPath($),w(""),v(null),g(!1)};y.useEffect(()=>u.clear(),[o.path,u.clear]);const P=p.tasks.filter(E=>E.status==="error"),A=d.verdictFor(o.path);return c.jsx(WL,{children:c.jsx(fl,{children:c.jsxs("div",{className:"storage",children:[c.jsxs("div",{className:"storage__sub",children:[c.jsx(kL,{path:o.path,rootLabel:"files",onNavigate:o.setPath}),c.jsx("div",{className:"storage__actions",children:u.size>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),c.jsx(HL,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:E=>{for(const j of u.selected)j.kind==="folder"&&E.deleted.includes(j.fullPath)&&f({type:"discard",path:j.fullPath});r&&u.selected.some(j=>j.kind==="object"?j.fullPath===r:r.startsWith(`${j.fullPath}/`))&&o.setPath(o.path),u.clear(),l.refresh()},onFailed:E=>{const j=new Set(E.failed.map($=>$.fullPath));u.selectAll(u.selected.filter($=>j.has($.fullPath))),l.refresh()}}),c.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__action","aria-expanded":m,onClick:()=>{g(E=>!E),v(null)},children:"New folder"}),c.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>_.current?.click(),children:"Upload files"}),c.jsx("input",{ref:_,type:"file",multiple:!0,hidden:!0,onChange:E=>{const j=Array.from(E.currentTarget.files??[]);j.length>0&&R(j.map($=>({file:$,relativePath:$.name}))),E.currentTarget.value=""}})]})})]}),m?c.jsxs("form",{className:"storage__newfolder",onSubmit:O,children:[c.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:b,onChange:E=>{w(E.currentTarget.value),v(null)},onKeyDown:E=>{E.key==="Escape"&&g(!1)}}),c.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),x?c.jsx("span",{className:"storage__newfolder-err",role:"alert",children:x}):c.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,P.length>0?c.jsxs("p",{className:"storage__upload-err",role:"alert",children:[P.length===1?`Upload failed: ${Gf(P[0].fullPath)} — ${P[0].error?.message??"error"}`:`${P.length} uploads failed: ${P.map(E=>Gf(E.fullPath)).join(", ")}`,c.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,c.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[c.jsxs(CL,{className:"storage__browser",onFiles:R,disabled:!A.upload,disabledReason:A.reasons.write.join("; "),children:[c.jsxs("div",{className:"storage__lhead",children:[c.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:c.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:k,onChange:E=>E.currentTarget.checked?u.selectAll(S):u.clear()})}),c.jsx("span",{children:"name"}),c.jsx("span",{children:"type"}),c.jsx("span",{children:"size"}),c.jsx("span",{children:"updated"})]}),c.jsx(EL,{entries:S,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:NU,renderRowAction:E=>c.jsx("label",{className:"storage__select-row",title:`Select ${E.name}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${E.name}`,checked:u.isSelected(E.fullPath),onChange:()=>u.toggle(E)})}),onNavigate:o.enter,onSelect:E=>a(E.fullPath),emptyState:c.jsx("p",{className:"storage__empty",children:qf(h,o.path)?"Empty folder — session-only until a file is uploaded here. Drop files anywhere in this pane, or use Upload files.":"No files yet. Drop files here or use Upload files; files your app uploads to Storage also appear here."})}),c.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",o.path||""]})]}),c.jsx("div",{className:"storage__inspector",children:r?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__back",onClick:()=>o.setPath(o.path),"aria-label":"Back to files",children:"‹ Files"}),c.jsx(qL,{storage:e,path:r,renderMetadata:jU})]}):c.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function AU({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return c.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[c.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),c.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",t," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function pb({view:e}){const{target:t}=Gi(),n=Ct(),r=n.status==="ready"?n.handles.auth:null;return c.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?c.jsx(AU,{view:e}):n.authApi?c.jsx(bg,{value:n.authApi,children:c.jsx(Jf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):c.jsx(Jf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function Jf({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:o}=Vi(n),a=y.useMemo(()=>new Set(o.map(l=>l.uid)),[o]);switch(e){case"firestore":{const l=c.jsx(yU,{handles:t,knownUids:a});return s?c.jsx(YT,{value:s,children:l}):l}case"auth":return c.jsx(SU,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=c.jsx(IU,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?c.jsx(lL,{value:i,children:l}):l}}}function OU(){return c.jsx(pb,{view:"firestore"})}function $U(){return c.jsx(pb,{view:"storage"})}function PU(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function DU(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function TU(e){const[t,n]=y.useState(()=>new Set);y.useEffect(()=>{n(s=>{const i=PU(s,e);return i.size===s.size&&[...i].every(o=>s.has(o))?s:i})},[e]);const r=y.useMemo(()=>e.filter(s=>t.has(s.uid)),[t,e]);return{selectedUsers:r,allVisibleSelected:e.length>0&&r.length===e.length,isSelected:s=>t.has(s),toggle(s){n(i=>{const o=new Set(i);return o.has(s)?o.delete(s):o.add(s),o})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function MU({users:e,filter:t,onDelete:n,onComplete:r}){const s=Hn(),[i,o]=y.useState(!1),[a,l]=y.useState(null),u=async()=>{const d=t.trim().length>0;if(!await s({title:`Delete ${e.length} ${e.length===1?"user":"users"}?`,body:d?`Only the ${e.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${e.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;o(!0),l(null);const f=await DU(e,n);o(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),a?c.jsx("span",{className:"auth-sub__error",children:a}):null]})}function mb(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"never";const n=Math.max(0,Math.round((Date.now()-t)/1e3));if(n<45)return"just now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function yb(e){if(!e)return"unknown";const t=new Date(e);return Number.isNaN(t.getTime())?"unknown":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function LU(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return c.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[c.jsx("span",{className:"auth-ident__primary",title:n,children:n}),c.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function UU({auth:e}={}){const t=Ht(),n=Ct(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return c.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:c.jsx(WU,{status:t.status})});const i=c.jsx(fl,{children:c.jsx(BU,{auth:r})});return s?c.jsx(bg,{value:s,children:i}):i}function BU({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:o,createUser:a,updateUser:l,deleteUser:u}=Vi(e),d=Gi(),h=d.target?.view==="auth"?d.target.uid:null,f=w=>d.navigate({view:"auth",uid:w}),p=y.useMemo(()=>t.find(w=>w.uid===h)??null,[t,h]),[m,g]=y.useState(!1),b=TU(t);return c.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[c.jsxs("div",{className:"auth-sub",children:[c.jsxs("span",{className:"auth-sub__h",children:["users ",c.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),c.jsx("input",{className:"auth-sub__filter",value:i,onChange:w=>o(w.target.value),placeholder:"filter users…","aria-label":"Filter users"}),c.jsx("div",{className:"auth-sub__right",children:b.selectedUsers.length>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[b.selectedUsers.length," selected"]}),c.jsx(MU,{users:b.selectedUsers,filter:i,onDelete:w=>Promise.resolve(u(w)),onComplete:w=>{b.replace(w),h&&!w.includes(h)&&f(null)}}),c.jsx("button",{type:"button",className:"auth-sub__clear",onClick:b.clear,children:"Clear selection"})]}):c.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),c.jsxs("div",{className:"auth-body","data-auth-level":p||m?"detail":"list",children:[c.jsx("div",{className:"auth-list",children:c.jsx(kg,{users:t,isLoading:r,error:s,filter:i,onSelect:w=>{g(!1),f(w.uid)},renderIdentifier:LU,formatCreatedAt:yb,formatLastLoginAt:mb,renderSelectionHeader:c.jsx("label",{className:"auth-select",title:"Select all shown users",children:c.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:b.allVisibleSelected,onChange:w=>b.selectAll(w.currentTarget.checked)})}),renderSelection:w=>c.jsx("label",{className:"auth-select",title:`Select ${w.uid}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${w.uid}`,checked:b.isSelected(w.uid),onChange:()=>b.toggle(w.uid)})}),emptyState:c.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:c.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),c.jsx("div",{className:"auth-detail",children:m?c.jsx(FU,{onCancel:()=>g(!1),onCreate:async w=>{const x=await Promise.resolve(a(w));g(!1),f(x.uid)}}):p?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),c.jsx(VU,{user:p,onSave:w=>{w.mode==="edit"&&l(w.uid,w.request)},onProvidersChange:async w=>{await Promise.resolve(l(p.uid,{providerUserInfo:w}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):c.jsx("div",{className:"auth-detail__empty",children:c.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function FU({onCreate:e,onCancel:t}){const[n,r]=y.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(o=>{r(o instanceof Error?o:new Error(String(o)))}))};return c.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsx("div",{className:"auth-editor__who",children:"New user"}),c.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),c.jsx(Eg,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const Yf=[...Cc];function qU({user:e,onChange:t}){const[n,r]=y.useState(null),[s,i]=y.useState(""),o=e.providerUserInfo.map(p=>p.providerId),a=o.includes("password"),l=o.filter(p=>p!=="password"),u=l.filter(p=>!Yf.includes(p)),d=p=>{r(null),t(p.map(m=>({providerId:m}))).catch(m=>{r(m instanceof Error?m:new Error(String(m)))})},h=(p,m)=>{d(m?[...l,p]:l.filter(g=>g!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return c.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[c.jsx("div",{className:"auth-group",children:"Sign-in providers"}),c.jsx("div",{className:"auth-providers-editor__list",children:[...Yf,...u].map(p=>c.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[c.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:m=>h(p,m.target.checked)}),c.jsx("span",{className:"auth-provider-row__label",children:xi(p)}),c.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),a||e.isAnonymous?c.jsx("p",{className:"auth-providers-editor__derived",children:a?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,c.jsx("div",{className:"auth-provider-custom",children:c.jsxs("label",{className:"auth-provider-custom__field",children:[c.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),c.jsxs("span",{className:"auth-provider-custom__row",children:[c.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),c.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function VU({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=y.useState(null),[o,a]=y.useState(!1),l=h=>{i(null),a(!1);try{t(h),a(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=yb(e.createdAt),d=mb(e.lastLoginAt);return c.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?c.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),c.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),c.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),c.jsx(qU,{user:e,onChange:n}),c.jsxs(Eg,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,o?c.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),c.jsx("div",{className:"auth-editor__foot",children:c.jsx(mT,{user:e,onDelete:r,className:"auth-del"})})]})}function WU({status:e}){const t=e==="pending"?"Seeding the sandbox…":e==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return c.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:c.jsx("p",{className:"auth-zero",children:t})})}function zU(e){return e.operationContext.source.kind==="studio"}function HU(e,t){return t?e.filter(n=>!zU(n)):[...e]}const KU=["all","allow","deny","proof-unsupported","bypassed"];function Kn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":cl(e)?"proof-unsupported":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function GU(e,t){return t==="all"?[...e]:e.filter(n=>Kn(n)===t)}function Wo(e){return e.rulesDisposition.kind==="evaluated"}function Qf(e){const t=e.path;if(e.service==="storage"&&e.method==="list"&&(t===""||t==="/"))return{tab:"storage"};if(!t||t==="(service)")return null;const n=t.split("/").filter(Boolean);switch(e.service??"firestore"){case"firestore":return n.length?{tab:"firestore",rest:n}:null;case"rtdb":return{tab:"rtdb"};case"storage":return n.length?{tab:"storage",rest:n,...e.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return t!=="*"?{tab:"auth",rest:[t]}:null;default:return null}}function JU(e){return e.filter(t=>{const n=Kn(t);return n==="allow"||n==="deny"})}function YU(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end&&Kn(n)==="proof-unsupported").length}function gb(e){return e==="proof-unsupported"?"Query proof unsupported":e}const ac="inspect";function bb(e){const t=e[ac];return t||null}function wb(e,t){const{[ac]:n,...r}=e;return t?{...r,[ac]:t}:r}function QU(e,t){return wb(e,bb(e)===t?null:t)}const XU=y.lazy(()=>Am(()=>import("./RulesCodeEditor.D-eQLCvu.js"),__vite__mapDeps([0,1,2])));function vb(e){return c.jsx(y.Suspense,{fallback:c.jsx(ZU,{value:e.value,minHeightRem:e.minHeightRem}),children:c.jsx(XU,{...e})})}function ZU({value:e,minHeightRem:t=14}){return c.jsx("pre",{"data-pyric-ui":"rules-code-editor-loading",className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",style:{minHeight:`${t}rem`},children:e||"Loading editor…"})}function xb({denial:e,rulesSource:t}){const n=iD(e);let r="denied",s="deny";return cl(e)?(r="Query proof unsupported",s="proof-unsupported"):e.unsupported&&(r="unsupported",s="unsupported"),c.jsxs("div",{"data-pyric-ui":"denial-detail",className:"flex min-h-0 flex-col gap-4 overflow-auto rounded-lg border border-border bg-sidebar-bg p-5",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?c.jsx(Xa,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):c.jsx(Xa,{kind:s,className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:r}),c.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),c.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?c.jsx("p",{"data-pyric-ui":"rules-debug-no-evaluation",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"No matched rule, evaluation trace, or re-run is shown because this event carries no rules verdict to ground them in."}):c.jsxs(c.Fragment,{children:[c.jsx(eB,{denial:e,exp:n,rulesSource:t}),c.jsx(iB,{denial:e})]}),c.jsx(aB,{denial:e})]})}function eB({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?c.jsx(lB,{denial:e,exp:t,rulesSource:n},e.id):s?c.jsx(fB,{exp:t}):c.jsx(sB,{denial:e,exp:t,rulesSource:n})}function tB(e){const t="// @pyric-source-map:",n=e.indexOf(t);if(!(n!==-1))return null;const s=n+t.length,i=e.slice(s).trim();try{const o=JSON.parse(i);return Array.isArray(o)?o:null}catch{return null}}function nB(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function rB(e,t){if(e===void 0||t===void 0)return t;const s=tB(e);if(s!==null){const o=s.find(l=>l.authoredLine===t);if(o!==void 0)return o.generatedLine}return t}function sB({denial:e,exp:t,rulesSource:n}){const r=ll(e),s=r?.rule?.line??e.evaluatedRule?.line,i=rB(n,s),o=n!==void 0?nB(n):void 0,a=e.result==="allow",l=!!(o&&o.trim().length>0);return c.jsxs(xt,{label:r?`query proof — ${t.ruleNode}`:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${s?` · line ${s}`:""}`,children:[r?.predicate?c.jsxs("div",{className:"mb-3 text-sm text-slate-gray",children:[c.jsxs("p",{children:["Unsupported predicate",r.predicate.citation?` · ${r.predicate.citation}`:""]}),c.jsx("pre",{className:"overflow-auto font-mono text-xs",children:r.predicate.expression})]}):null,l?c.jsx(vb,{value:o,readOnly:!0,markLine:i,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:r?"Deployed firestore.rules — the rule Pyric could not prove is marked":`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...r?.rule?.expression?[r.rule.expression]:[],...t.ruleLines,...t.otherLines].join(`
146
+ `)||"(no trace)"})]})}function iB({denial:e}){const t=uD(e);return t.length===0?null:c.jsx(xt,{label:ll(e)?"residual evaluation — separate from the static proof":"show the work — how the condition evaluated",children:c.jsx("div",{"data-pyric-ui":"rules-debug-trace",className:"flex flex-col gap-0.5 overflow-auto rounded-md border border-border bg-content-bg p-3",children:t.map((n,r)=>c.jsx(xl,{step:n},r))})})}const oB={true:"✓",false:"✗",skipped:"⊘",error:"!",unsupported:"?",value:"·"};function xl({step:e}){const t=e.outcome==="true"?"text-diff-add":e.outcome==="false"||e.outcome==="error"?"text-danger":"text-slate-gray",n=e.outcome==="skipped"?"not evaluated (short-circuit)":e.outcome==="error"?e.error:e.outcome==="unsupported"?`unsupported${e.error?`: ${e.error}`:""}`:`→ ${_b(e.value)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[c.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:oB[e.outcome]}),c.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),c.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?c.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>c.jsx(xl,{step:r},s))]})}function _b(e){if(e===void 0)return"undefined";try{return JSON.stringify(_i(e))}catch{return String(e)}}function aB({denial:e}){const t=hD(e);return c.jsx(xt,{label:"what the rule saw (request / resource)",children:c.jsx("div",{"data-pyric-ui":"rules-debug-variables",className:"flex flex-col gap-2 rounded-md border border-border bg-content-bg p-3",children:t.map(n=>c.jsx(cB,{variable:n},n.name))})})}function cB({variable:e}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?c.jsx(Sb,{value:e.value}):c.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Sb({value:e,depth:t=0}){const[n,r]=y.useState(t<2),s=_i(e);if(s===null||typeof s!="object")return c.jsx("span",{className:"font-mono text-xs text-soft-white",children:_b(s)});const i=Array.isArray(s)?s.map((o,a)=>[String(a),o]):Object.entries(s);return i.length===0?c.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):c.jsxs("div",{className:"flex flex-col",children:[c.jsxs("button",{type:"button",onClick:()=>r(o=>!o),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[c.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),c.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?c.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([o,a])=>c.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[c.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[o,":"]}),c.jsx(Sb,{value:a,depth:t+1})]},o))}):null]})}function lB({denial:e,exp:t,rulesSource:n}){const r=sD(e,n),s=fD(e,n),[i,o]=y.useState(null),[a,l]=y.useState(!1),u=a?s:s.slice(0,uB),d=i===null?void 0:s[i];let h=r;d&&(h=d.verdict==="UNSUPPORTED"?void 0:d.line);const f=d?d.verdict==="ALLOW":e.result==="allow",p=n!==void 0&&n.trim().length>0;let m;t.implicitDeny||!t.ruleNode?m="rule node":r!==void 0?m=`rule node: ${t.ruleNode} · line ${r}`:m=`rule node: ${t.ruleNode}`;let g;return f?g="Deployed database.rules.json, the allowing rule is marked":g="Deployed database.rules.json, the denying rule is marked",c.jsxs(c.Fragment,{children:[c.jsx(xt,{label:m,children:p?c.jsx("div",{"data-pyric-ui":"rtdb-rule-source","data-marked-line":h,children:c.jsx(vb,{value:n,readOnly:!0,markLine:h,markKind:f?"allow":"deny",minHeightRem:12,ariaLabel:g})}):c.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[t.phase?`.${t.phase}`:"(no matching rule)",e.rules?.matchedPath?` at ${e.rules.matchedPath}`:""]})}),s.length>0?c.jsxs(xt,{label:"evaluated rules, root first",children:[c.jsx("ul",{"data-pyric-ui":"rtdb-trace",className:"flex flex-col gap-1",children:u.map((b,w)=>c.jsx(dB,{row:b,current:w===i,onSelect:()=>o(w)},w))}),s.length>u.length?c.jsxs("button",{type:"button","data-pyric-ui":"rtdb-trace-show-all",onClick:()=>l(!0),className:"w-fit font-mono text-xs text-slate-gray hover:text-soft-white",children:["show all ",s.length," rules"]}):null]}):null,!p&&t.ruleExpression?c.jsx(xt,{label:"rule expression",children:c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:t.ruleExpression})}):null,t.bindings?c.jsx(xt,{label:"$variable bindings",children:c.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([b,w])=>`${b.startsWith("$")?b:`$${b}`} → ${w}`).join(", ")})}):null,e.rules?.reason?c.jsx(xt,{label:"simulator reason",children:c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}const uB=20;function dB({row:e,current:t,onSelect:n}){const r=Object.entries(e.bindings);return c.jsxs("li",{"data-pyric-ui":"rtdb-trace-row","data-line":e.line,"aria-current":t?"true":void 0,onClick:n,className:`flex cursor-pointer flex-col gap-1 rounded-md border px-3 py-2 ${t?"border-primary bg-primary/10":"border-border bg-content-bg hover:bg-sidebar-bg"}`,children:[c.jsxs("button",{type:"button",onClick:s=>{s.stopPropagation(),n()},className:"flex w-fit items-baseline gap-2 font-mono text-xs text-slate-gray",children:[c.jsx("span",{className:"text-soft-white",children:e.path}),c.jsxs("span",{children:[".",e.kind]}),e.line!==void 0?c.jsxs("span",{children:["line ",e.line]}):null]}),c.jsx(xl,{step:e.step}),r.length>0?c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:r.map(([s,i])=>`${s} → ${i}`).join(", ")}):null]})}function fB({exp:e}){return c.jsxs(xt,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?c.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...e.ruleLines,...e.otherLines].join(`
147
+ `)||"(no trace)"})]})}function xt({label:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function hB(e="firestore"){const t=Ht(),n=t.status==="ready",[r,s]=y.useState({});return y.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{if(!i||!o||typeof o!="object")return;const l={};typeof o.rules=="string"&&(l.firestore=o.rules),o.databaseRules!==void 0&&o.databaseRules!==null&&(typeof o.databaseRules=="string"?l.rtdb=o.databaseRules:l.rtdb=JSON.stringify(o.databaseRules,null,2)),typeof o.storageRules=="string"&&(l.storage=o.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),y.useMemo(()=>{const i=t.status==="ready",o=e==="database"?"rtdb":e;if(!i){const a=r[o];return a!==void 0?a:""}try{if(o==="rtdb"){const u=rg(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return Xr(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function Xf({eventId:e,onClose:t}){const r=bD().find(o=>o.id===e),s=r?.service??"firestore",i=hB(s);return r?c.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),c.jsx(xb,{denial:r,rulesSource:i})]}):c.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[c.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const pB=new Intl.NumberFormat,mB={reads:"read operations",writes:"writes",deletes:"deletes"},yB={allows:"allowed requests",denies:"denied requests"};function Zf(e){return e.length<=1?e[0]??"":e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e.at(-1)}`}function eh(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function kb(e,t){const n=e.reduce((u,d)=>u+d.total,0);if(n===0)return{total:n,headline:t.emptyHeadline,finding:t.emptyFinding};const r=Math.max(...e.map(u=>u.total)),s=e.filter(u=>u.total===r),i=`${pB.format(n)} observed ${n===1?t.singular:t.plural}`,o=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(o);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${Zf(u)}.`:`${eh(Zf(u))} tied for the largest share of ${t.subject} in this window.`}}const a=s[0],l=Math.round(a.total/n*100);return{total:n,headline:i,finding:`${eh(o(a))} accounted for ${l}% of ${t.subject} in this window.`}}function gB(e){return kb(e,{labels:mB,singular:"billable operation",plural:"billable operations",subject:"activity",evenSplitPrefix:"Activity was split evenly across",emptyHeadline:"No billable activity observed",emptyFinding:"Successful reads, writes, and deletes will appear here as they happen."})}function bB(e){return kb(e,{labels:yB,singular:"Rules evaluation",plural:"Rules evaluations",subject:"evaluations",evenSplitPrefix:"Evaluations were split evenly between",emptyHeadline:"No Rules evaluations observed",emptyFinding:"Allow and deny decisions will appear here as Rules evaluate requests."})}const wB=new Intl.NumberFormat,vB=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function th(e){return wB.format(e)}function lr(e){return vB.format(e)}function xB(e){return Kn(e)==="bypassed"}function _B(e){return e.every(t=>t.total===0)}function Eb({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:o,source:a,methodology:l}){const[u,d]=y.useState(()=>new Set(n.map(f=>f.key))),h=y.useCallback(f=>{d(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:e}),c.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),c.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),c.jsx(hl,{series:n,visible:u,onToggle:h,formatValue:th,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),_B(n)?c.jsx("p",{className:"traffic__empty",children:i}):c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:o}),c.jsxs("span",{children:[lr(s.start),"–",lr(s.end)]})]}),c.jsx(Ag,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:th,formatTime:lr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:lr(s.start)}),c.jsx("span",{children:lr(s.end)})]})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:a}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsx("div",{children:l})]})]})]})}function SB({events:e,window:t}){const n=y.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=UT({events:n,window:t,isAdmin:xB}),s=y.useMemo(()=>gB(r.series),[r.series]);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:c.jsx(Eb,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:t,emptyLabel:"No reads, writes, or deletes in this session yet.",evidenceTitle:"When the activity happened",source:"Source: Pyric Firestore sandbox events · Operation counts, not a Firebase invoice",methodology:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts successful Firestore sandbox ",c.jsx("code",{children:"get"}),"/",c.jsx("code",{children:"list"}),","," ",c.jsx("code",{children:"create"}),"/",c.jsx("code",{children:"update"}),"/",c.jsx("code",{children:"set"}),", and"," ",c.jsx("code",{children:"delete"}),"/",c.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",c.jsx("code",{children:"list"})," is counted once because the event does not report how many documents the query returned. This is observed sandbox activity, not a Firebase invoice."]})]})})})}function kB({events:e,window:t}){const n=y.useMemo(()=>JU(e),[e]),r=BT({events:n,window:t}),s=y.useMemo(()=>r.series.filter(o=>o.key==="allows"||o.key==="denies"),[r.series]),i=y.useMemo(()=>bB(s),[s]);return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:[c.jsxs("p",{children:["Query proof unsupported: ",YU(e,t)]}),c.jsx(Eb,{eyebrow:"Rules decisions",story:i,series:s,points:r.points,window:t,emptyLabel:"No allow or deny decisions in this session yet.",evidenceTitle:"When Rules evaluated requests",source:"Source: Pyric sandbox events · Evaluated Rules dispositions only",methodology:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",c.jsx("code",{children:"evaluated"}),", grouped by its ",c.jsx("code",{children:"allow"})," or ",c.jsx("code",{children:"deny"})," ","verdict. Query-proof limitations are counted separately, not as ordinary denials."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Bypasses and runtime failures are not Rules decisions."})," Admin bypasses, services without Rules, unsupported operations, and runtime errors are excluded because Rules did not produce a verdict."]})]})})]})}function _l(e){for(const t of e??[])if(t.kind==="component")return t;return null}function Ji(e){for(const t of e??[])if(t.kind==="tag")return t;return null}function EB(e){for(const t of e??[])if(t.kind==="frame")return t;return null}function jB(e){const t=_l(e);if(t?.element!==void 0)return t.element;const n=Ji(e);if(n?.element!==void 0)return n.element}function Tn(e){return typeof e=="string"?e:e.query!==void 0?`${e.collection} (query)`:e.collection}function CB(e,t){const n=_l(e);if(n)return n.name;const r=Ji(e);return r?r.name:Tn(t)}function Yi(e){const t=_l(e.owners);if(t)return{key:`component:${t.name}`,label:t.name};const n=Ji(e.owners);if(n)return{key:`tag:${n.name}`,label:n.name};const r=Tn(e.target);return{key:`target:${r}`,label:r}}function RB(e,t){return!(t.service!==void 0&&e.service!==t.service||t.targetPrefix!==void 0&&t.targetPrefix!==""&&!D_(e.target,t.targetPrefix))}function NB(e,t={}){const n=new Map;for(const r of e){if(!RB(r,t))continue;const s=Yi(r),i=n.get(s.key);i?i.listeners.push(r):n.set(s.key,{identity:s,listeners:[r]})}return[...n.values()].map(r=>Object.freeze({identity:r.identity,listeners:Object.freeze(r.listeners)})).sort((r,s)=>r.listeners[0].attachedAt-s.listeners[0].attachedAt)}function IB(e){return{history:()=>e,subscribe:()=>()=>{}}}function jb(e){const t=aR(IB(e),()=>{});try{return t.report().incidents}finally{t.dispose()}}function AB(e){try{const t=JSON.parse(e.targetFingerprint);if(t.kind==="doc"&&typeof t.path=="string")return t.path;if(t.kind==="query"&&typeof t.collection=="string")return{collection:t.collection,query:!0}}catch{}return null}function OB(e,t){return typeof e=="string"||typeof t=="string"?e===t:e.collection===t.collection}function Cb(e,t){return e.filter(n=>{if(n.pattern!=="duplicate-listener"&&n.pattern!=="listener-churn")return!1;const r=AB(n);return r!==null&&OB(r,t)})}function $B(e,t){return e?.column===t&&e.direction==="asc"?{column:t,direction:"desc"}:{column:t,direction:"asc"}}const PB=e=>e.deliveryCount;function DB(e,t,n){const r=new Map;for(const s of e.listeners){const i=Tn(s.target),o=r.get(i);o?o.push(s):r.set(i,[s])}return[...r.entries()].map(([s,i])=>{const o=[...i].sort((l,u)=>l.attachedAt-u.attachedAt),a=o[0];return Object.freeze({key:`${e.identity.key}|${s}`,listeners:Object.freeze(o),listener:a,ownerLabel:e.identity.label,target:s,count:o.length,deliveryCount:o.reduce((l,u)=>l+n(u),0),incidents:Cb(t,a.target)})})}function nh(e,t){return e<t?-1:e>t?1:0}function ki(e){return e.incidents.length>0?1:0}function TB(e,t,n){return n==="target"?nh(e.target,t.target):n==="service"?nh(e.listener.service,t.listener.service):n==="attached"?e.listener.attachedAt-t.listener.attachedAt:n==="deliveries"?e.deliveryCount-t.deliveryCount:ki(e)-ki(t)}function MB(e,t){const n=ki(t)-ki(e);if(n!==0)return n;const r=t.deliveryCount-e.deliveryCount;return r!==0?r:e.listener.attachedAt-t.listener.attachedAt}function LB(e){if(e===void 0)return MB;const t=e.direction==="asc"?1:-1;return(n,r)=>{const s=TB(n,r,e.column)*t;return s!==0?s:n.listener.attachedAt-r.listener.attachedAt}}function UB(e,t,n,r=PB){const s=LB(n);return e.map(i=>{const o=[...DB(i,t,r)].sort(s);return Object.freeze({identity:i.identity,rows:Object.freeze(o),listenerCount:i.listeners.length})}).sort((i,o)=>s(i.rows[0],o.rows[0]))}function BB(e,t){let n=0;const r=[];let s;for(const a of e){n+=a.listenerCount,(s===void 0||a.listenerCount>s.count)&&(s={label:a.identity.label,count:a.listenerCount});for(const l of a.rows)l.count>1&&r.push(l.count)}const i=t.filter(a=>a.pattern==="listener-churn").length,o={listeners:n,duplicates:r,churn:i};return s!==void 0&&(o.busiest=s),o}function FB(e){let t=0,n=0,r=0;for(const s of e)for(const i of s.rows)i.deliveryCount>0?t+=i.count:n+=i.count,i.incidents.length>0&&(r+=i.count);return{delivering:t,idle:n,incidents:r}}function qB(e){const t=[e.deliveryCount>0?"delivering":"idle"];return e.incidents.length>0&&t.push("incidents"),t}function Sl(e){return e.kind==="snapshot_delivery"?!0:e.kind==="listener"&&e.phase==="delivery"}const Rb=[{key:"delivering",label:"Delivering"},{key:"idle",label:"Idle"},{key:"incidents",label:"Incidents"}];function VB(e){return Rb.map(t=>({key:t.key,label:t.label,values:[],total:e[t.key]}))}const zo=[{key:"firestore",label:"Firestore"},{key:"database",label:"Database"}];function WB(e,t){const n=new Map;for(const r of e){if(!Sl(r)||r.at<t.start||r.at>=t.end)continue;const s=r.listenerId;s!==void 0&&n.set(s,(n.get(s)??0)+1)}return n}function zB(e,t,n,r=24){const s=n.end-n.start,i=zo.map(f=>({key:f.key,label:f.label,values:[],total:0}));if(r<=0||s<=0)return{points:[],series:i,total:0};const o=s/r,a=new Map;for(const f of t)a.set(f.id,f.service);const l=new Map(zo.map(f=>[f.key,new Array(r).fill(0)]));let u=0;for(const f of e){if(!Sl(f)||f.at<n.start||f.at>=n.end)continue;const p=f.listenerId;if(p===void 0)continue;const m=a.get(p);if(m===void 0)continue;const g=l.get(m);if(g===void 0)continue;let b=Math.floor((f.at-n.start)/o);b>=r&&(b=r-1),g[b]=(g[b]??0)+1,u+=1}const d=[];for(let f=0;f<r;f+=1)d.push({index:f,start:n.start+f*o,end:n.start+(f+1)*o});const h=zo.map(f=>{const p=l.get(f.key);return{key:f.key,label:f.label,values:p,total:p.reduce((m,g)=>m+g,0)}});return{points:d,series:h,total:u}}function cc(e,t){if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>cc(i,t[o]));if(typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n);return s.length!==Object.keys(r).length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&cc(n[i],r[i]))}function HB(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function KB(e){if(e.kind==="snapshot_delivery"){const r=e.sample?.docs;return r===void 0?[]:r.map(s=>[s.path,s.data])}const t=e.target?.path;if(t===void 0||t==="")return[];const n=e.sample;return n==null?[]:HB(n)?Object.keys(n).map(r=>[`${t}/${r}`,n[r]]):[[t,n]]}function GB(e){if(e.kind!=="snapshot_delivery")return;const t=e;if(!(t.addedCount===void 0||t.modifiedCount===void 0||t.removedCount===void 0))return{added:t.addedCount,modified:t.modifiedCount,removed:t.removedCount}}function Nb(e,t){const n=[];let r=new Map;for(const s of e){if(!Sl(s)||s.listenerId!==t)continue;const i=KB(s),o=new Map(i.map(([f,p])=>[f,p])),a=[];let l=0,u=0;for(const[f,p]of i)r.has(f)?cc(r.get(f),p)?a.push({path:f,change:"unchanged"}):(a.push({path:f,change:"modified"}),u+=1):(a.push({path:f,change:"added"}),l+=1);let d=0;for(const f of r.keys())o.has(f)||(a.push({path:f,change:"removed"}),d+=1);const h=GB(s);n.push({at:s.at,initial:n.length===0,addedCount:h?.added??l,modifiedCount:h?.modified??u,removedCount:h?.removed??d,size:i.length,docs:a}),r=o}return n}function Ib(e){const t=e[0];if(t===void 0)return 0;let n=Math.max(t.size,1);for(const r of e.slice(1))n+=r.addedCount+r.modifiedCount;return n}function Ab(e){const t=[{key:"deliveries",label:"Deliveries",total:e.deliveries},{key:"snapshot",label:"Snapshot",total:e.snapshot,unit:e.single||e.snapshot===1?"document":"documents"}];return e.service==="firestore"&&t.push({key:"reads",label:"Estimated reads",total:e.reads}),t}function JB(e){return e.map(t=>({key:t.key,label:t.label,values:[],total:t.total}))}function YB(e,t){let n=0;return r=>{const s=e[n];return n+=1,s?.unit===void 0?t(r):`${t(r)} ${s.unit}`}}function QB(e){if(e==="firestore")return"Estimated reads: initial snapshot + documents added or modified since · reconnects and duplicate listeners not counted"}function XB(e,t){return e.map((n,r)=>({id:`delivery-${r}`,at:n.at,method:"listen",path:t,auth:null,result:"allow",reasons:[],origin:"listener"}))}function rh(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end)}function sh(e){let t=0,n=0,r=0;for(const o of e)t+=o.initial?o.size:o.addedCount,n+=o.initial?0:o.modifiedCount,r+=o.initial?0:o.removedCount;const s=e.length,i=[`${s} ${s===1?"delivery":"deliveries"}`];return t>0&&i.push(`${t} added`),n>0&&i.push(`${n} modified`),r>0&&i.push(`${r} removed`),i}function ZB(e){if(e.initial)return"initial";const t=[];return e.addedCount>0&&t.push(`+${e.addedCount}`),e.modifiedCount>0&&t.push(`~${e.modifiedCount}`),e.removedCount>0&&t.push(`−${e.removedCount}`),t.join(" ")}const Ob="listeners";function $b(e,t){return e==="firestore"?nb({view:"firestore",path:Gr(t)}):{tab:"rtdb",rest:t.split("/").filter(Boolean)}}function e1(e,t){return kt($b(e,t))}function Pb(e){return{tab:"traffic",rest:[Ob,e]}}function t1(e){return kt(Pb(e))}function Db(){return{tab:"traffic",query:{view:"listeners"}}}function n1(){return kt(Db())}function Tb(e){if(e.tab!=="traffic"||e.rest[0]!==Ob)return;const t=e.rest[1];return t===void 0||t===""?void 0:t}const Mb=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});function ih(e){return Mb.formatToParts(e).filter(t=>t.type!=="dayPeriod").map(t=>t.value).join("").trim()}function r1(e){const t=e.lastIndexOf("/");return t===-1?{prefix:"",id:e}:{prefix:e.slice(0,t+1),id:e.slice(t+1)}}function s1({path:e,service:t}){const{prefix:n,id:r}=r1(e);return c.jsx("a",{className:"traffic__listener-path-link",href:e1(t,e),title:e,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.button!==0||(s.preventDefault(),Ie($b(t,e)))},children:c.jsxs("span",{"data-pyric-path":e,children:[c.jsx("span",{"data-pyric-path-prefix":"",children:n}),c.jsx("span",{"data-pyric-path-id":"",children:r})]})})}function i1(e){return e.initial?[]:e.docs.filter(t=>t.change!=="unchanged")}function Lb({delivery:e,service:t,expanded:n=!1,onToggle:r}){const s=i1(e),i=n&&s.length>0;return c.jsxs("div",{className:"traffic__delivery-entry","data-pyric-delivery-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__delivery-row","data-pyric-delivery-row":"","data-pyric-delivery-at":e.at,"data-pyric-selected":i?"":void 0,disabled:s.length===0||r===void 0,onClick:r,children:[c.jsx("span",{"data-pyric-delivery-time":"",children:Mb.format(e.at)}),c.jsx("span",{"data-pyric-delivery-figures":"",children:ZB(e)}),c.jsxs("span",{"data-pyric-delivery-snapshot":"",children:[e.size," in snapshot"]})]}),i?c.jsx("div",{className:"traffic__delivery-changes","data-pyric-delivery-changes":"",children:s.map(o=>c.jsxs("div",{className:"traffic__delivery-path","data-pyric-delivery-path":o.path,children:[c.jsx(s1,{path:o.path,service:t}),c.jsx("span",{className:"traffic__delivery-change","data-pyric-change":o.change,children:o.change})]},o.path))}):null]})}const o1=/^\[[a-zA-Z][\w-]*(?:=["']?([^"'\]]+)["']?)?\]$/,a1=/^([a-z][a-z0-9-]*?)-[0-9a-z]+$/,c1=/^[a-z][a-z0-9-]*$/;function l1(e){const n=e?.find(r=>r.kind==="component"&&typeof r.tag=="string")?.tag??Ji(e)?.name;if(!(n===void 0||!c1.test(n)))return n}function u1(e){const t=e.split(">");return t[t.length-1].trim()}function d1(e){const t=o1.exec(e);if(t!==null){const a=a1.exec(t[1]??"");return a===null?{}:{tag:a[1]}}const n=e.replace(/:[a-z-]+(\([^)]*\))?/g,""),r={},s=/^[a-zA-Z][\w-]*/.exec(n)?.[0];s!==void 0&&(r.tag=s.toLowerCase());const i=/#([\w-]+)/.exec(n)?.[1];i!==void 0&&(r.id=i);const o=/\.([\w-]+)/.exec(n)?.[1];return o!==void 0&&(r.className=o),r}function Qi(e){const t=jB(e);if(t===void 0||t==="")return;const n=d1(u1(t)),r=n.tag??l1(e)??"";return n.id!==void 0?`${r}#${n.id}`:n.className!==void 0?`${r}.${n.className}`:r===""?void 0:r}function f1(e){const t="owners"in e&&Array.isArray(e.owners)?e.owners:void 0;if(e.kind==="listener_attach"){const n=e.target;if(n.kind==="doc"&&n.path!==void 0)return t===void 0?{target:n.path}:{target:n.path,owners:t};const r={collection:n.collection??"",query:n.query};return t===void 0?{target:r}:{target:r,owners:t}}if(e.kind==="listener"&&e.phase==="attach"){const n=e.target?.path??"";return t===void 0?{target:n}:{target:n,owners:t}}return null}function h1(e,t,n){const r=Tn(t),s=[];for(const i of e){const o=f1(i);if(o===null||Tn(o.target)!==r||CB(o.owners,o.target)!==n)continue;const a=EB(o.owners),l=Qi(o.owners),u={at:i.at};a!==null&&(u.frame=`${a.file}:${a.line}`),l!==void 0&&(u.element=l),s.push(Object.freeze(u))}return Object.freeze(s)}function Ub(e){const t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function kl(e,t){return`${Ub(t-e)} ago`}function lc(e,t){return`${e} ${t}${e===1?"":"s"}`}function Bb(e){return e===2?"twice":`${e} times`}function Fb(e){return e==="firestore"?"Firestore":"Database"}function p1(e){if(e.listeners===0)return"No listeners attached";const t=lc(e.listeners,"listener");if(e.duplicates.length>0){const n=Math.max(...e.duplicates);return`${t}, ${e.duplicates.length} attached ${Bb(n)}`}return e.churn>0?`${t}, ${lc(e.churn,"listener")} reattaching`:t}function m1(e){const t=e.busiest;if(!(t===void 0||t.count<2))return`${t.label} · ${lc(t.count,"listener")}`}function qb(e,t){const n=[];return e.owner!==void 0&&n.push(e.owner),e.element!==void 0&&n.push(e.element),n.push(Fb(e.service)),n.push(`attached ${kl(e.attachedAt,t)}`),n.join(" · ")}function y1(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function g1(e,t,n){const r=t===void 0?"":` by ${t}`;if(e.pattern==="listener-churn")return`Reattached ${e.count} times in ${Ub(e.windowMs)}${r}`;const s=y1(n),i=`Attached ${Bb(e.count)}${r}`;return s===""?i:`${i} · ${s}`}function Vb({incident:e,listener:t,events:n,now:r}){const s=Yi(t).label,i=h1(n,t.target,s),o=e.pattern==="listener-churn"?i.slice(-1):i,a=e.pattern==="listener-churn"?[]:i.map(d=>kl(d.at,r)),l=Qi(t.owners),u=o.filter(d=>d.frame!==void 0||(d.element??l)!==void 0);return c.jsxs("div",{className:"traffic__listener-incident","data-pyric-incident-block":"",children:[c.jsxs("p",{className:"traffic__listener-incident-line",children:[c.jsx("span",{"aria-hidden":"true",children:"⚠"})," ",g1(e,s,a)]}),u.map((d,h)=>{const f=d.element??l;return c.jsxs("p",{className:"traffic__listener-incident-attach","data-pyric-incident-attach":"",children:[d.frame===void 0?null:c.jsx("span",{children:d.frame}),d.frame!==void 0&&f!==void 0?c.jsx("span",{children:" · "}):null,f===void 0?null:c.jsx("span",{"data-pyric-element":"",children:f})]},`${d.at}|${h}`)})]})}const Ho=40,jn=" ";function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function b1(e){return e.length<=Ho?e:e.startsWith("'")&&e.endsWith("'")?`${e.slice(0,Ho-2)}…'`:`${e.slice(0,Ho-1)}…`}function Jr(e,t){const n=w1(e,t);return t?n:b1(n)}function w1(e,t){if(typeof e=="string")return qe(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return"null";if(!st(e))return"…";switch(e.type){case"string":return typeof e.value=="string"?qe(e.value):"…";case"number":case"boolean":return String(e.value);case"null":return"null";case"reference":return typeof e.path=="string"?`doc(db, ${qe(e.path)})`:"…";case"timestamp":return typeof e.iso=="string"?qe(e.iso):"…";case"geoPoint":return`GeoPoint(${String(e.latitude)}, ${String(e.longitude)})`;case"bytes":return`Bytes(${String(e.length)})`;case"vector":return`Vector(${String(e.length)})`;case"array":{const r=(Array.isArray(e.values)?e.values:[]).map(s=>Jr(s,t));return e.truncated===!0&&r.push("…"),`[${r.join(", ")}]`}case"map":{const r=(Array.isArray(e.entries)?e.entries:[]).filter(s=>Array.isArray(s)&&typeof s[0]=="string").map(([s,i])=>`${s}: ${Jr(i,t)}`);return e.truncated===!0&&r.push("…"),r.length===0?"{}":`{ ${r.join(", ")} }`}default:return"…"}}function Wb(e,t,n){if(!st(e))return;const r=jn.repeat(t);if(e.kind==="where"){const o=typeof e.field=="string"?e.field:"",a=typeof e.op=="string"?e.op:"",l="display"in e?e.display:e.value;return`${r}where(${qe(o)}, ${qe(a)}, ${Jr(l,n)})`}if(e.kind!=="or"&&e.kind!=="and")return;const i=(Array.isArray(e.filters)?e.filters:[]).map(o=>Wb(o,t+1,n)).filter(o=>o!==void 0);if(i.length!==0)return`${r}${e.kind}(
148
+ ${i.join(`,
149
+ `)})`}function oh(e,t,n){if(!st(e))return;const r=Array.isArray(e.display)?e.display:Array.isArray(e.values)?e.values:[];if(r.length===0)return;const s=e.inclusive!==!1;return`${jn}${t==="start"?s?"startAt":"startAfter":s?"endAt":"endBefore"}(${r.map(o=>Jr(o,n)).join(", ")})`}function v1(e,t){return(st(t?.scope)?t.scope:void 0)?.kind==="collection-group"?`collectionGroup(db, ${qe(e)})`:`collection(db, ${qe(e)})`}function x1(e,t){const n=[],r=Array.isArray(e.filters)?e.filters:[];for(const a of r){const l=Wb(a,1,t);l!==void 0&&n.push(l)}const s=Array.isArray(e.orderBy)?e.orderBy:[];for(const a of s)!st(a)||typeof a.field!="string"||n.push(a.direction==="desc"?`${jn}orderBy(${qe(a.field)}, 'desc')`:`${jn}orderBy(${qe(a.field)})`);typeof e.limit=="number"&&n.push(e.limitFromEnd===!0?`${jn}limitToLast(${String(e.limit)})`:`${jn}limit(${String(e.limit)})`);const i=oh(e.start,"start",t);i!==void 0&&n.push(i);const o=oh(e.end,"end",t);return o!==void 0&&n.push(o),n}function ah(e,t,n){const r=v1(e,t),s=t===void 0?[]:x1(t,n);return s.length===0?r:`query(${r},
150
+ ${s.join(`,
151
+ `)})`}function _1(e){return st(e)?e.kind==="child"?typeof e.path=="string"?`.orderByChild(${qe(e.path)})`:"":e.kind==="key"?".orderByKey()":e.kind==="value"?".orderByValue()":e.kind==="priority"?".orderByPriority()":"":""}const S1=new Set(["startAt","startAfter","endAt","endBefore","equalTo"]);function ch(e,t,n){const r=[];if(st(t)){r.push(_1(t.orderBy));const s=Array.isArray(t.bounds)?t.bounds:[];for(const o of s){if(!st(o)||typeof o.kind!="string"||!S1.has(o.kind))continue;const a=[Jr(o.value,n)];typeof o.key=="string"&&a.push(qe(o.key)),r.push(`.${o.kind}(${a.join(", ")})`)}const i=t.limit;st(i)&&typeof i.n=="number"&&(i.kind==="limitToFirst"||i.kind==="limitToLast")&&r.push(`.${i.kind}(${String(i.n)})`)}return`ref(db, ${qe(e)})${r.join("")}`}function k1(e){if(e.service==="database"){const r=typeof e.target=="string"?e.target:"";return r===""?void 0:{text:ch(r,e.query,!1),full:ch(r,e.query,!0)}}if(typeof e.target=="string")return;const t=e.target.collection;if(t==="")return;const n=st(e.query)?e.query:st(e.target.query)?e.target.query:void 0;return{text:ah(t,n,!1),full:ah(t,n,!0)}}function E1({value:e,clipboard:t}){const[n,r]=y.useState(!1),s=t??globalThis.navigator?.clipboard;return c.jsx("button",{type:"button",className:"traffic__listener-query-copy","data-pyric-query-copy":"","data-pyric-copy-value":e,"data-pyric-copy-failed":n?"":void 0,"aria-label":n?"Copy failed":"Copy the query",title:n?"Copy failed":"Copy the query",disabled:s===void 0,onClick:()=>{s!==void 0&&Promise.resolve(s.writeText(e)).then(()=>r(!1),()=>r(!0))},children:c.jsxs("svg",{className:"traffic__listener-query-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[c.jsx("rect",{x:"8",y:"8",width:"11",height:"11",rx:"1"}),c.jsx("path",{d:"M16 8V5H5v11h3"})]})})}function zb({listener:e,clipboard:t}){const n=y.useMemo(()=>k1({service:e.service,target:e.target,query:e.query}),[e.service,e.target,e.query]);return n===void 0?null:c.jsxs("div",{className:"traffic__listener-query","data-pyric-query-block":"",children:[c.jsx("pre",{className:"traffic__listener-query-text","data-pyric-query-text":"",title:n.full===n.text?void 0:n.full,children:n.text}),c.jsx(E1,{value:n.full,clipboard:t})]})}const j1=new Intl.NumberFormat,C1=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Cn(e){return j1.format(e)}function ur(e){return C1.format(e)}const R1=[{id:"incident",label:"",name:"Incidents"},{id:"target",label:"Target",name:"Target"},{id:"deliveries",label:"Deliveries",name:"Deliveries"},{id:"attached",label:"Attached",name:"Attached"},{id:"service",label:"Service",name:"Service"}];function N1(e,t){const n={};return e!==""&&(n.service=e),t!==""&&(n.targetPrefix=t),n}function I1(e,t){return e?.column!==t?"none":e.direction==="asc"?"ascending":"descending"}function A1({metric:e,label:t,value:n,unit:r}){return c.jsxs("span",{className:"traffic__listener-figure","data-pyric-inspector-figure":e,children:[c.jsx("span",{className:"traffic__listener-figure-label",children:t}),c.jsx("span",{className:"traffic__listener-figure-value",children:r===void 0?Cn(n):`${Cn(n)} ${r}`})]})}function O1({listener:e,row:t,events:n,now:r,onClose:s}){const[i,o]=y.useState(!1),a=y.useMemo(()=>Nb(n,e.id),[n,e.id]),l=a[a.length-1],u=Qi(e.owners),d={service:e.service,attachedAt:e.attachedAt};d.owner=Yi(e).label,u!==void 0&&(d.element=u);const h=t.incidents[0],f=Ab({deliveries:a.length,snapshot:l===void 0?0:l.size,reads:Ib(a),service:e.service,single:typeof e.target=="string"&&e.service==="firestore"});return c.jsxs("div",{className:"traffic__inspector","data-pyric-listener-inspector":"",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("a",{className:"traffic__listener-inspector-target","data-pyric-inspector-title":"",href:t1(e.id),onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button!==0||(p.preventDefault(),Ie(Pb(e.id)))},children:t.target}),c.jsx("button",{type:"button",className:"traffic__inspector-close","data-pyric-inspector-close":"",onClick:s,"aria-label":"Close the listener inspector",children:"✕"})]}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-inspector-facts":"",children:qb(d,r)}),c.jsx(zb,{listener:e}),h===void 0?null:c.jsx(Vb,{incident:h,listener:e,events:n,now:r}),c.jsx("div",{className:"traffic__listener-figures",children:f.map(p=>c.jsx(A1,{metric:p.key,label:p.label,value:p.total,unit:p.unit},p.key))}),l===void 0?null:c.jsx(Lb,{delivery:l,service:e.service,expanded:i,onToggle:()=>o(p=>!p)})]})}function $1({events:e,window:t,selectedListenerId:n,initialTargetPrefix:r,hideStudio:s=!1,now:i}){const[o,a]=y.useState(""),[l,u]=y.useState(r??""),[d,h]=y.useState(void 0),[f,p]=y.useState(n),[m,g]=y.useState([]),b=y.useRef(null),w=y.useMemo(()=>{const N=kc(e);return s?N.filter(I=>I.actor.kind!=="studio"):N},[e,s]),x=y.useMemo(()=>jb(e),[e]),v=y.useMemo(()=>WB(e,t),[e,t]),_=y.useMemo(()=>UB(NB(w,N1(o,l)),x,d,N=>v.get(N.id)??0),[w,o,l,x,d,v]),S=y.useMemo(()=>BB(_,x),[_,x]),k=y.useMemo(()=>VB(FB(_)),[_]),R=y.useMemo(()=>zB(e,w,t),[e,w,t]),O=y.useMemo(()=>new Set(Rb.map(N=>N.key).filter(N=>!m.includes(N))),[m]),P=N=>g(I=>I.includes(N)?I.filter(M=>M!==N):[...I,N]),A=i??Date.now(),E=y.useMemo(()=>{if(n!==void 0){for(const N of _)for(const I of N.rows)if(I.listeners.some(M=>M.id===n))return I.listener.id;return n}},[n,_]);y.useEffect(()=>{E!==void 0&&(p(E),b.current?.scrollIntoView({block:"center"}))},[E]);const j=y.useMemo(()=>_.map(N=>({...N,rows:N.rows.filter(I=>qB(I).some(M=>O.has(M)))})).filter(N=>N.rows.length>0),[_,O]);function $(N){const I=N.listener,M=I.id===f;return c.jsxs("div",{className:"traffic__listener-entry","data-pyric-listener-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__listener-row",ref:M?b:void 0,"data-pyric-listener-row":"","data-pyric-listener-id":I.id,"data-pyric-selected":M?"":void 0,"data-pyric-incident":N.incidents.length>0?"":void 0,onClick:()=>p(M?void 0:I.id),children:[c.jsx("span",{"data-col":"incident","aria-hidden":"true",children:N.incidents.length>0?"⚠":""}),c.jsxs("span",{"data-col":"target",title:N.target,children:[c.jsx("span",{className:"traffic__listener-target-text",children:N.target}),N.count>1?c.jsxs("span",{className:"traffic__listener-duplicate","data-pyric-listener-duplicate":"",children:["×",N.count]}):null]}),c.jsx("span",{"data-col":"deliveries",children:Cn(N.deliveryCount)}),c.jsx("span",{"data-col":"attached",children:kl(I.attachedAt,A)}),c.jsx("span",{"data-col":"service",children:Fb(I.service)})]}),M?c.jsx(O1,{listener:I,row:N,events:e,now:A,onClose:()=>p(void 0)}):null]},N.key)}const C=m1(S);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listeners-view",children:c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:"Listener activity"}),c.jsx("h3",{className:"traffic__metric-headline",children:p1(S)}),C===void 0?null:c.jsx("p",{className:"traffic__metric-finding","data-pyric-listener-owner-fact":"",children:C})]}),c.jsx(hl,{series:k,visible:O,onToggle:P,formatValue:Cn,className:"traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--3"}),c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:"When deliveries happened"}),c.jsxs("span",{children:[ur(t.start),"–",ur(t.end)]})]}),R.total===0?c.jsx("p",{className:"traffic__empty",children:"No deliveries in this window."}):c.jsxs(c.Fragment,{children:[c.jsx(Ag,{points:R.points,series:R.series,omitZeroSeries:!0,formatValue:Cn,formatTime:ur,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:ur(t.start)}),c.jsx("span",{children:ur(t.end)})]})]})]}),c.jsxs("div",{className:"traffic__filters traffic__filters--listeners",role:"group","aria-label":"Listener filters",children:[c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Service"}),c.jsxs("select",{className:"traffic__filter-select",value:o,onChange:N=>a(N.target.value),children:[c.jsx("option",{value:"",children:"All"}),c.jsx("option",{value:"firestore",children:"Firestore"}),c.jsx("option",{value:"database",children:"Database"})]})]}),c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Target"}),c.jsx("input",{className:"traffic__filter-input",type:"text",value:l,onChange:N=>u(N.target.value)})]})]}),w.length===0?null:j.length===0?c.jsx("p",{className:"traffic__empty","data-pyric-listener-empty":"",children:"No listeners match these filters"}):c.jsxs("div",{className:"traffic__log traffic__listener-grid","data-pyric-listener-grid":"","data-pyric-ui":"traffic-listeners-log",children:[c.jsx("div",{className:"traffic__listener-header","data-pyric-listener-header":"",role:"row",children:R1.map(N=>c.jsxs("button",{type:"button",role:"columnheader",className:"traffic__listener-column","data-col":N.id,"aria-label":N.label===""?N.name:void 0,"aria-sort":I1(d,N.id),onClick:()=>h(I=>$B(I,N.id)),children:[N.label,d?.column===N.id?c.jsx("span",{"aria-hidden":"true",children:d.direction==="asc"?"↑":"↓"}):null]},N.id))}),j.map(N=>c.jsxs("div",{className:"traffic__listener-run",children:[c.jsxs("div",{className:"traffic__listener-group","data-pyric-listener-group":N.identity.key,children:[c.jsx("span",{"data-col":"owner",children:N.identity.label}),c.jsx("span",{"data-col":"count",children:Cn(N.listenerCount)})]}),N.rows.map(I=>$(I))]},N.identity.key))]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox listener events · listeners attached now, deliveries in this window"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsxs("p",{children:["A listener is attached when the sandbox recorded its ",c.jsx("code",{children:"attach"})," and has not recorded a ",c.jsx("code",{children:"detach"})," or an error for it since. The count is that fold, not the number of attach events."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Owners come from the attach, deliveries from the window."})," The owner is the React component the listener was opened in, else the tag the app gave it, else the target itself. Two listeners on the same target under the same owner are one thing attached twice, so they collapse into one row carrying"," ",c.jsx("code",{children:"×N"}),". Delivery counts cover the displayed window only; a listener with none is idle, not gone."]})]})]})]})]})})}const Hb={open:!1};function Kb(e){const t=new URLSearchParams(e);if(t.get("view")!=="listeners")return Hb;const n={open:!0},r=t.get("listener");r!==null&&r!==""&&(n.listenerId=r);const s=t.get("target");return s!==null&&s!==""&&(n.targetPrefix=s),n}function P1(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))r!==void 0&&t.set(n,r);return Kb(t.toString())}function D1(){return typeof window>"u"?Hb:Kb(window.location.search)}const T1={open:!1};function M1(){return P1(He().query)}function L1({window:e,hideStudio:t,deepLink:n}){const r=Gt("active-listeners"),s=y.useSyncExternalStore(Kt,al,()=>""),i=y.useMemo(()=>s===""?T1:M1(),[s]),o=n??i,a={events:r,window:e};return t!==void 0&&(a.hideStudio=t),o.listenerId!==void 0&&(a.selectedListenerId=o.listenerId),o.targetPrefix!==void 0&&(a.initialTargetPrefix=o.targetPrefix),c.jsx($1,{...a})}function U1(e,t){return e===0?"No requests occurred in this interval.":e===1?t===1?"The request in this interval was denied.":"One request occurred in this interval; it was not denied.":t===0?`${e} requests occurred in this interval; none were denied.`:t===e?`All ${e} requests in this interval were denied.`:`${e} requests occurred in this interval; ${t} ${t===1?"was":"were"} denied.`}function B1(e,t){const n=e.filter(s=>s.at>=t.start&&s.at<t.end),r=n.reduce((s,i)=>s+(i.result==="deny"?1:0),0);return{window:t,events:n,total:n.length,denies:r,finding:U1(n.length,r)}}function Gb(e,t){return e?.start===t.start&&e.end===t.end?null:t}const F1=new Intl.NumberFormat;function q1(e){return F1.format(e)}function lh(e){return`${ih(e.start)}–${ih(e.end)}`}function V1(e,t){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);return r<60?`${r}m ago`:`${Math.round(r/60)}h ago`}function uh(){return c.jsx("a",{className:"traffic__listener-back",href:n1(),"data-pyric-page-back":"",onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),Ie(Db()))},children:"← Listeners"})}function W1({events:e,listenerId:t,window:n,now:r}){const[s,i]=y.useState(null),[o,a]=y.useState(null),l=y.useMemo(()=>kc(e).find(_=>_.id===t),[e,t]),u=y.useMemo(()=>Nb(e,t),[e,t]),d=y.useMemo(()=>{if(l!==void 0)return Cb(jb(e),l.target)[0]},[e,l]);if(l===void 0)return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(uh,{}),c.jsx("p",{className:"traffic__empty","data-pyric-listener-missing":"",children:"This listener is not attached in this session."})]});const h=r??Date.now(),f=Qi(l.owners),p={service:l.service,attachedAt:l.attachedAt};p.owner=Yi(l).label,f!==void 0&&(p.element=f);const m=Tn(l.target),g=Ab({deliveries:u.length,snapshot:u.length===0?0:u[u.length-1].size,reads:Ib(u),service:l.service,single:typeof l.target=="string"&&l.service==="firestore"}),b=QB(l.service),w=XB(u,m),x=s===null?u:rh(u,s),v=u.map((_,S)=>({delivery:_,index:S})).filter(({delivery:_})=>s===null||_.at>=s.start&&_.at<s.end).reverse();return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(uh,{}),c.jsxs("div",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("section",{className:"traffic__metric-story","data-pyric-section":"header",children:[c.jsx("h3",{className:"traffic__metric-headline","data-pyric-page-title":"",children:m}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-page-facts":"",children:qb(p,h)})]}),c.jsx(zb,{listener:l}),d===void 0?null:c.jsx(Vb,{incident:d,listener:l,events:e,now:h}),c.jsxs("section",{"data-pyric-section":"cards",children:[c.jsx(hl,{series:JB(g),formatValue:YB(g,q1),className:`traffic__metric-cards traffic__metric-cards--journal${g.length===2?" traffic__metric-cards--2":""}`}),b===void 0?null:c.jsx("p",{className:"traffic__metric-source","data-pyric-metric-footnote":"",children:b})]}),u.length===0?null:c.jsxs("section",{className:"traffic__listener-section","data-pyric-section":"deliveries",children:[c.jsx(Ig,{events:w,window:n,brush:s??void 0,onBrush:_=>{i(S=>Gb(S,_)),a(null)},liveAt:n.end,bucketCount:36,className:"traffic__timeline",axis:_=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:V1(_.start,h)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:_=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:lh(_)}),c.jsx("strong",{children:sh(rh(u,_))[0]})]})}),s===null?null:c.jsxs("p",{className:"traffic__listener-interval","data-pyric-interval":"",children:[c.jsx("span",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("span",{"data-pyric-interval-facts":"",children:[lh(s),...sh(x)].join(" · ")})]}),v.length===0?null:c.jsx("div",{className:"traffic__log","data-pyric-delivery-log":"",children:v.map(_=>c.jsx(Lb,{delivery:_.delivery,service:l.service,expanded:o===_.index,onToggle:()=>a(o===_.index?null:_.index)},_.index))})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox delivery events · every delivery this session recorded for this listener"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsx("p",{children:"Every delivery event carries the result set the callback received: a Firestore delivery carries the documents in callback order, and a database delivery carries the value at the target path, whose keys are child paths when that value is an object. The paths under a delivery are that result set, not a re-read of the store."}),c.jsxs("p",{children:[c.jsx("strong",{children:"The labels come from the previous delivery."})," A path is"," ",c.jsx("code",{children:"added"})," when the previous delivery did not carry it,"," ",c.jsx("code",{children:"modified"})," when it did and the data differs, and ",c.jsx("code",{children:"removed"})," ","when the previous delivery carried it and this one does not. A path whose data is identical is not listed. The first delivery is ",c.jsx("code",{children:"initial"}),": every path in it arrived, so it lists none."]}),c.jsx("p",{children:"Firestore charges a listener for the documents in its first snapshot, then for each document a later delivery adds or changes; a delivery that only drops documents costs nothing, and an empty first snapshot still costs one read. The estimate covers this session's deliveries, so a reconnect that re-read the result set and a second listener on the same query are not in it."})]})]})]})]})]})}function z1({listenerId:e,window:t}){const n=Gt();return c.jsx(W1,{events:n,listenerId:e,window:t})}const H1=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"},{id:"listeners",label:"Listeners"}];function K1(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":e==="listeners"?"listeners":"timeline"}function G1(e){return e.tab!=="traffic"?"timeline":Tb(e)!==void 0?"listeners":K1(e.query.view)}function J1(){return G1(He())}function Y1(){const{tab:e,rest:t}=He();return Tb({tab:e,rest:t})}function Q1(){return y.useSyncExternalStore(Kt,Y1,()=>{})}function X1(){const e=y.useSyncExternalStore(Kt,J1,()=>"timeline"),t=y.useCallback(n=>{const r={...He().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Ie({tab:"traffic",query:r})},[]);return[e,t]}function Z1(){const e=y.useSyncExternalStore(Kt,()=>He().query.hide==="studio",()=>!1),t=y.useCallback(()=>{const n={...He().query};n.hide==="studio"?delete n.hide:n.hide="studio",Ie({tab:"traffic",query:n})},[]);return[e,t]}function eF(e,t){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);return r<60?`${r}m ago`:`${Math.round(r/60)}h ago`}function dh(e){return`${Kr(e.start)}–${Kr(e.end)}`}function tF({event:e}){const t=Kn(e);return t?c.jsx("span",{className:"traffic__verdict","data-verdict":t,children:gb(t)}):null}function nF(){return y.useSyncExternalStore(Kt,()=>bb(He().query),()=>null)}const Ko=100;function rF(){const e=gD(),[t,n]=X1(),r=Q1(),[s,i]=Z1(),o=y.useMemo(()=>HU(e,s),[e,s]),a=e.length-o.length,[l,u]=y.useState("all"),[d,h]=y.useState(null),f=nF(),[p,m]=y.useState(Ko),g=C=>{Ie({tab:"traffic",query:QU(He().query,C)})},b=()=>{Ie({tab:"traffic",query:wb(He().query,null)})};y.useEffect(()=>{if(!f)return;const C=N=>{N.key==="Escape"&&b()};return globalThis.addEventListener("keydown",C),()=>globalThis.removeEventListener("keydown",C)},[f]);const w=y.useMemo(()=>{const C=Date.now();if(o.length===0)return{start:C-15*6e4,end:C};let N=1/0;for(const I of o)I.at<N&&(N=I.at);return{start:Math.min(N,C-6e4),end:C+1e3}},[o]),x=w.end,v=y.useMemo(()=>d?B1(o,d):null,[o,d]),_=v?.events??o,S=y.useMemo(()=>GU(_,l).sort((C,N)=>N.at-C.at),[_,l]),{items:k}=ET({events:S}),R=k.slice(0,p),O=k.length-R.length,P=o.length>=kr,A=o.filter(C=>C.result==="deny").length,E=C=>c.jsx(tF,{event:C}),j=C=>{if(Wo(C)){g(C.id);return}const N=Qf(C);N&&Ie(N)},$=f!=null&&R.some(C=>C.type!=="group"&&C.event.id===f);return c.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[c.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[H1.map(C=>c.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===C.id,onClick:()=>n(C.id),children:C.label},C.id)),c.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":s,onClick:i,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",s&&a>0?` (${a} hidden)`:""]})]}),r!==void 0?c.jsx(z1,{listenerId:r,window:w}):t==="billable"?c.jsx(SB,{events:o,window:w}):t==="rules"?c.jsx(kB,{events:o,window:w}):t==="listeners"?c.jsx(L1,{window:w,hideStudio:s}):c.jsxs(c.Fragment,{children:[c.jsx(Ig,{events:o,window:w,brush:d??void 0,onBrush:C=>{h(N=>Gb(N,C)),f&&b()},liveAt:w.end,bucketCount:36,className:"traffic__timeline",header:c.jsxs("div",{className:"traffic__tl-header",children:[c.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",P?` (showing latest ${kr})`:""]}),A>0?c.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>u(C=>C==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[A," denied"]}):null,c.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:C=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:eF(C.start,x)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:C=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:dh(C)}),c.jsxs("strong",{children:[C.count," ",C.count===1?"request":"requests"]}),c.jsxs("span",{children:[C.denies," denied"]})]}),emptyState:c.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),v?c.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[c.jsxs("div",{className:"traffic__time-focus-story",children:[c.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("h3",{children:dh(v.window)}),c.jsx("p",{children:v.finding})]}),c.jsx("button",{type:"button",onClick:()=>h(null),children:"Show all traffic"})]}):null,c.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[c.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),KU.map(C=>c.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===C,onClick:()=>u(C),children:gb(C)},C))]}),f&&!$?c.jsx(Xf,{eventId:f,onClose:b},f):null,k.length===0?c.jsx("p",{className:"traffic__empty",children:v?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):c.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":v?"":void 0,children:[c.jsx("ul",{"data-pyric-traffic-log-items":"",children:R.map(C=>C.type==="group"?c.jsx("li",{"data-pyric-traffic-group-entry":"",children:c.jsx(qT,{group:C,onSelect:N=>{const I=N;if(Wo(I)){g(I.id);return}const M=Qf(I);M&&Ie(M)},renderClassification:N=>E(N),formatTime:Kr})},C.key):c.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":C.event.id,"data-verdict":Kn(C.event)??void 0,children:[c.jsx(Ng,{event:C.event,selected:C.event.id===f,onSelect:N=>j(N),renderClassification:N=>E(N),formatTime:Kr}),C.event.id===f&&Wo(C.event)?c.jsx(Xf,{eventId:f,onClose:b},f):null]},C.event.id))}),O>0?c.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(C=>C+Ko),children:["Show ",Math.min(O,Ko)," more (",O," hidden)"]}):null]})]})]})}const fh=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],hh=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function El(e){if(!e)return"";let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)>>>0;return`${fh[t%fh.length]}-${hh[(t>>>4)%hh.length]}`}function jl(){const e=ot(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState("");return y.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function sF(){const e=ot(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async()=>t?t.exportState():null,[t])}function iF(){const e=ot(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function oF(){const e=ot(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState([]),s=y.useCallback(async()=>{if(!t){r([]);return}const l=await t.listStates();r(l.map(u=>u.name))},[t]);y.useEffect(()=>{s()},[s]);const i=y.useCallback(async l=>{t&&(await t.saveState(l),await s())},[t,s]),o=y.useCallback(async l=>{t&&await t.restoreState(l)},[t]),a=y.useCallback(async l=>{t&&(await t.deleteState(l),await s())},[t,s]);return{names:n,save:i,restore:o,remove:a}}function aF(e){const t=e.operationContext?.source??e.actor;if(t?.kind==="agent")return{provenance:"agent",identity:`agent:${t.name}`};if(t?.kind==="studio")return{provenance:"studio",identity:"studio"};if(t?.kind==="app-builder")return{provenance:"app-builder",identity:"builder"};const n="auth"in e&&e.auth&&typeof e.auth=="object"?e.auth.uid:void 0;return!t||t.kind==="unattributed"?{provenance:"unattributed",identity:n??"unattributed"}:{provenance:"app",identity:n??"app"}}function cF(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function lF(e){const{provenance:t,identity:n}=aF(e),r={id:e.id,at:e.at,provenance:t,identity:n};switch(e.kind){case"write":return{...r,denied:!1,summary:`${e.method} /${e.path}`,target:cF(e.path)};case"request":return e.result!=="deny"?null:{...r,denied:!0,summary:`denied ${e.method} /${e.path}`,target:{tab:"traffic",query:{inspect:e.id}}};case"operation":return e.result==="deny"?{...r,denied:!0,summary:`denied ${e.service} ${e.method}${e.path?` ${e.path}`:""}`,target:{tab:"traffic",query:{inspect:e.id}}}:null;case"service_mutation":{const s=e.path?` ${e.path}`:"",i=e.service==="auth"&&e.path&&e.path!=="*"?{tab:"auth",rest:[e.path]}:e.service==="storage"&&e.path?{tab:"storage",rest:e.path.split("/").filter(Boolean)}:e.service==="rtdb"?{tab:"rtdb"}:null;return{...r,denied:!1,summary:`${e.service} ${e.op}${s}`,target:i}}case"commit":return e.service!=="rtdb"||e.detail?.admin!==!0?null:{...r,denied:!1,summary:`rtdb ${e.method}${e.path?` ${e.path}`:""}`,target:{tab:"rtdb"}};case"session_boundary":return{...r,provenance:"system",identity:"sandbox",denied:!1,summary:`session ${e.phase}`,target:null};default:return null}}function uF(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=lF(e[r]);s&&n.push(s)}return n}const dF=20;function fF(e){Ie(e)}function Mn({target:e,className:t,children:n,title:r}){return c.jsx("a",{className:t,href:kt(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),fF(e))},children:n})}function hF(){const e=Ht(),t=fs(),n=jl();if(t.status==="loading"||e.status==="pending")return c.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(c.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(c.jsxs(Mn,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(c.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(c.jsxs(Mn,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),El(n)]},"instance")),c.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function pF(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function mF(){const e=Gt(),t=y.useMemo(()=>uF(e,dF),[e]);return c.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[c.jsxs("header",{className:"studio-home__feed-head",children:[c.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),c.jsx(Mn,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?c.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):c.jsx("div",{className:"studio-home__feed-scroll",children:c.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[c.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),c.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),c.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:pF(n.at)})]});return c.jsx("li",{children:n.target?c.jsx(Mn,{className:"studio-home__feed-row",target:n.target,children:r}):c.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const yF=["firestore","auth","rtdb","storage","traffic"];function gF(){const e=Ct(),t=Gt(),n=y.useMemo(()=>{const r={};if(e.status==="ready"){const s=e.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return t.length&&(r.traffic=`${t.length} events`),r},[e,t]);return c.jsx("div",{className:"studio-home__tiles",children:yF.map(r=>{const s=un.find(i=>i.id===r);return s?c.jsxs(Mn,{className:"studio-card studio-home__tile",target:{tab:r},children:[c.jsxs("span",{className:"studio-home__tile-top",children:[c.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?c.jsx("span",{className:"studio-badge",children:n[r]}):null]}),c.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function bF(){const e=fs(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return c.jsxs(c.Fragment,{children:[c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Point Claude Code, Cursor, or any MCP client at this sandbox and its writes show up in the feed, attributed."}),c.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),c.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),c.jsx(Mn,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?c.jsxs("span",{className:"studio-home__tile-desc",children:["Your repo rules are deployed to this sandbox (",s.slice(0,8),"). Denials will appear in the feed and in Traffic."]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),c.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function wF(){const e=Ct(),t=Gt(),n=Ht(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return c.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[c.jsxs("div",{className:"studio-home__hero",children:[c.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),c.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),c.jsx(mg,{exposeFocus:hP}),c.jsx(hF,{}),c.jsx("div",{className:"studio-home__body",children:r?c.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"})]}):s?c.jsx(bF,{}):c.jsxs(c.Fragment,{children:[c.jsx(mF,{}),c.jsx(gF,{})]})})]})}function xe(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function mt(e){return xe(e).split("/").filter(Boolean)}function uc(e,t){return xe([...mt(e),...t.split("/").filter(Boolean)].join("/"))}function vF(e){const t=mt(e);return t.length<=1?"/":`/${t.slice(0,-1).join("/")}`}function Cl(e,t){const n=mt(e),r=mt(t);if(r.length<n.length)return null;for(let i=0;i<n.length;i++)if(r[i]!==n[i])return null;const s=r.slice(n.length);return s.length===0?"/":`/${s.join("/")}`}function Jb(e){if(e==null)return null;if(typeof e!="object")return e;const t=e;let n=!1;const r={};for(const[s,i]of Object.entries(t)){const o=Jb(i);if(o===null){n=!0;continue}o!==i&&(n=!0),r[s]=o}return Object.keys(r).length===0?null:n?r:e}function xF(e){if(typeof e=="string")return JSON.stringify(e);if(e==null)return"null";if(typeof e=="object")try{return JSON.stringify(e)??"null"}catch{return"null"}return String(e)}function Rl(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Yb(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Qb(e,t){let n=e??null;for(const r of mt(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function _F(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function dc(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((o,a)=>dc(o,t[a]));if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n),i=Object.keys(r);return s.length!==i.length?!1:s.every(o=>o in r&&dc(n[o],r[o]))}function SF(e,t){const n=new Map,r=(s,i)=>{if(!Rl(s)){n.set(i,["leaf",s??null]);return}const o=Yb(s);n.set(i,["parent",o.map(([a])=>a)]);for(const[a,l]of o)r(l,uc(i,a))};return r(e,xe(t)),n}function kF(e){let t=e.trim();if(t.length===0)return"/";const n=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(t);return n&&(t=t.slice(n[0].length)),t=t.replace(/[?#].*$/,""),xe(t)}function EF(e){const t=mt(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const jF=["string","number","boolean","json"];function ph(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function CF(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function RF(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function NF(e,t){switch(e){case"string":return{ok:!0,value:t};case"number":{const n=t.trim();if(n.length===0)return{ok:!1,error:"Enter a number."};const r=Number(n);return Number.isNaN(r)?{ok:!1,error:`"${t}" is not a number.`}:{ok:!0,value:r}}case"boolean":{const n=t.trim().toLowerCase();return n==="true"?{ok:!0,value:!0}:n==="false"?{ok:!0,value:!1}:{ok:!1,error:"Enter true or false."}}case"json":{const n=t.trim();if(n.length===0)return{ok:!0,value:null};try{return{ok:!0,value:JSON.parse(n)}}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Invalid JSON."}}}}}function Xb(e){return{path:xe(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Zb(e,t){const n=Cl(e.path,t);return n===null?null:Qb(e.value,n)}function IF(e,t){const n=xe(t);return n===e.path||e.expanded[n]===!0}function AF(e,t,n){const r=Yb(Zb(e,t)),s=Math.min(r.length,e.pages[xe(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function mh(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const o=Cl(t.path,s);o!==null&&Rl(Qb(t.value,o))?n[s]=i:r=!0}return r?n:e}function ew(e,t){switch(t.type){case"navigate":{const n=xe(t.path);return n===e.path?e:Xb(n)}case"value":{if(xe(t.path)!==e.path)return e;const n={...e,status:"live",value:Jb(t.value),error:null};return n.expanded=mh(e.expanded,n),n.pages=mh(e.pages,n),n}case"error":return xe(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=xe(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=xe(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=xe(t.path);return ew(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=xe(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const OF=50;function $F(e,t,n={}){const r=n.pageSize??OF,s=xe(t),[i,o]=y.useReducer(ew,s,Xb),a=y.useMemo(()=>SF(i.value,i.path),[i.path,i.value]),l=vl({scope:i.path,entries:a,equals:dc,ready:i.status==="live"});i.path!==s&&o({type:"navigate",path:s}),y.useEffect(()=>{let g=!1;const b=e.subscribeValue(s,w=>{g||o({type:"value",path:s,value:w})},w=>{g||o({type:"error",path:s,message:w instanceof Error?w.message:String(w)})});return()=>{g=!0,b()}},[e,s]);const u=y.useCallback(g=>Zb(i,g),[i]),d=y.useCallback(g=>IF(i,g),[i]),h=y.useCallback(g=>AF(i,g,r),[i,r]),f=y.useCallback(g=>o({type:"toggle",path:g}),[]),p=y.useCallback(g=>o({type:"show-more",path:g,pageSize:r}),[r]),m=y.useCallback(g=>l.get(xe(g)),[l]);return y.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:h,toggle:f,showMore:p,updateAt:m}),[i,r,u,d,h,f,p,m])}function PF({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=xe(e),[o,a]=y.useState(!1),l=y.useRef(null);y.useEffect(()=>{o&&l.current?.select()},[o]);const u=f=>{f.preventDefault(),t(kF(l.current?.value??"")),a(!1)},d=()=>a(!1),h=EF(i);return c.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":o?"":void 0,"aria-label":"Database path",children:o?c.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?c.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,c.jsx("input",{ref:l,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:i,onBlur:d,onKeyDown:f=>{f.key==="Escape"&&d()},spellCheck:!1})]}):c.jsxs(c.Fragment,{children:[c.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[c.jsx("li",{"data-rtdb-crumb-item":!0,children:c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":h.length===0?"":void 0,"aria-current":h.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),h.map((f,p)=>{const m=p===h.length-1;return c.jsxs("li",{"data-rtdb-crumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":m?"":void 0,"aria-current":m?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),c.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>a(!0),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:c.jsx("path",{d:"M11.7 1.3a1 1 0 0 1 1.4 0l1.6 1.6a1 1 0 0 1 0 1.4l-8.5 8.5-3.4 1.1a.5.5 0 0 1-.63-.63l1.1-3.4 8.43-8.57ZM10.9 3.5l1.6 1.6 1.2-1.2-1.6-1.6-1.2 1.2Z"})})})]})})}function DF({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,o=mt(i.path),a=o.length===0?r:o[o.length-1];return c.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?c.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):c.jsx(tw,{tree:e,api:t,onNavigate:n,path:i.path,label:a,isViewRoot:!0})})}function tw({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const o=e.valueAt(r),a=Rl(o),l=e.isExpanded(r),u=e.updateAt(r),[d,h]=y.useState(!1),[f,p]=y.useState(!1),[m,g]=y.useState(!1),[b,w]=y.useState(null),x=async(S,k)=>{try{await S(),w(null),k()}catch(R){w(R instanceof Error?R.message:String(R))}},v=()=>{h(!0),g(!1),a&&!l&&e.toggle(r)},_=a&&l?e.childrenAt(r):null;return c.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":a?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":a&&l?"":void 0,children:[c.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[a&&!i?c.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:c.jsx("path",{d:"M1 0l6 4-6 4z"})})}):c.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),c.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),c.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":_F(o),title:"Edit value",onClick:()=>{p(!0),g(!1)},children:xF(o)})]}),c.jsx("span",{"data-rtdb-actions":!0,children:m?c.jsxs("span",{"data-rtdb-confirm":!0,children:[c.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",a?" subtree":"","?"]}),c.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void x(()=>t.remove(r),()=>g(!1)),children:"Delete"}),c.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${yh(r)}`,title:"Add child",onClick:v,children:"+"}),c.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${yh(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),b?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:b}):null,f?c.jsx(gh,{initialType:ph(o),initialText:CF(o,ph(o)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:S=>x(()=>t.set(r,S),()=>p(!1))}):null,d?c.jsx(gh,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>h(!1),onSubmit:(S,k)=>x(()=>t.set(uc(r,k),S),()=>h(!1))}):null,_?c.jsxs("ul",{"data-rtdb-children":!0,children:[_.entries.map(([S])=>c.jsx("li",{children:c.jsx(tw,{tree:e,api:t,onNavigate:n,path:uc(r,S),label:S})},S)),_.hiddenCount>0?c.jsx("li",{"data-rtdb-show-more-item":!0,children:c.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",_.hiddenCount," hidden)"]})}):null]}):null]})}function yh(e){const t=mt(e);return t.length===0?"root":t[t.length-1]}function gh({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const o=y.useRef(null),a=y.useRef(null),[l,u]=y.useState(t),[d,h]=y.useState(null),f=m=>{m.preventDefault();const g=o.current?.value??"";if(e){const w=RF(g);if(w){h(w);return}}const b=NF(l,a.current?.value??"");if(!b.ok){h(b.error);return}h(null),s(b.value,e?g.trim():void 0)},p=m=>{m.key==="Escape"&&i()};return c.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?c.jsx("input",{ref:o,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,c.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:m=>u(m.currentTarget.value),onKeyDown:p,children:jF.map(m=>c.jsx("option",{value:m,children:m},m))}),l==="boolean"?c.jsxs("select",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]}):c.jsx("input",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),c.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),c.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?c.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}const nw="rtdb";function TF(e){return e.tab!==nw?"/":xe(e.rest.join("/"))}function MF(e){return{tab:nw,rest:mt(e)}}function LF(){const e=y.useSyncExternalStore(Kt,()=>TF(He()),()=>"/"),t=y.useCallback(n=>{Ie(MF(n))},[]);return[e,t]}function UF(){const e=ot(),t=e.status==="ready"?e.env.live:void 0;return c.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),c.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),c.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?c.jsx(FF,{live:t}):c.jsx(BF,{})]})}function BF(){return c.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[c.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),c.jsx("p",{className:"mx-auto mt-3 max-w-md text-sm leading-relaxed text-muted",children:"The RTDB viewer goes live once Studio connects to the shared sandbox worker."})]})}function FF({live:e}){const t=El(jl()),n=y.useMemo(()=>({set:(r,s)=>e.setRtdbValue(r,s),remove:r=>e.deleteRtdbValue(r),subscribeValue:(r,s,i)=>e.subscribeRtdbValue(r,s,i)}),[e]);return c.jsx(qF,{api:n,instanceLabel:t?`${t}-sandbox`:"sandbox"})}function qF({api:e,instanceLabel:t}){const[n,r]=LF(),{viewRoot:s,missingTail:i,tree:o}=VF(e,n),a=y.useRef(null);return y.useEffect(()=>{if(s==="/")return;const l=a.current;l&&typeof l.scrollIntoView=="function"&&l.scrollIntoView({block:"nearest"})},[s]),c.jsxs("div",{className:"rtdb",ref:a,children:[c.jsx(PF,{className:"rtdb__pathbar",path:n,onNavigate:r,rootLabel:t,inputPrefix:t}),i?c.jsxs("p",{className:"rtdb__missing","data-rtdb-missing":"",children:["This path does not exist. Showing ",c.jsx("code",{children:s}),", the nearest path that does; ",c.jsx("code",{children:i})," is not in the database."]}):null,c.jsx(DF,{className:"rtdb__tree",tree:o,api:e,onNavigate:r,rootLabel:t})]})}function VF(e,t){const[n,r]=y.useState({requested:t,root:t}),s=n.requested===t?n:{requested:t,root:t};s!==n&&r(s);const i=s.root,o=$F(e,i),{path:a,status:l,value:u}=o.state;y.useEffect(()=>{a===i&&l==="live"&&u==null&&i!=="/"&&r({requested:t,root:vF(i)})},[a,l,u,i,t]);const d=i===t?null:Cl(i,t);return{viewRoot:i,missingTail:d&&mt(d).length>0?d:null,tree:o}}function WF(){const e=Ct();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??tt,s=e.firestoreApi?.setDoc??Gs;let i=0;const o=[];for(const a of t)try{await s(r(n,a.path),a.data),i++}catch(l){o.push(`${a.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:o}},[e])}function zF(){const e=Ct();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=e.handles.auth,r=e.authApi?.createUser??ve.createUser;let s=0;const i=[];for(const o of t)try{await r(n,o.request),s++}catch(a){const l=o.request.uid??o.request.email??"<auto>";i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}return{created:s,errors:i}},[e])}function HF(){const e=Ct(),t=ot(),n=t.status==="ready"?t.env.live:void 0;return y.useCallback(async()=>{if(e.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await e.handles.sandbox.resetAll();r.push(...s?.errors??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[e,n])}function KF(){const e=HF(),t=WF(),n=zF(),r=Ht();return y.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:o}=await Am(async()=>{const{applySeed:a,deploySeedRules:l}=await import("./seed.BvtbLu-q.js");return{applySeed:a,deploySeedRules:l}},__vite__mapDeps([3,1,4,2,5]));o(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),o=i?.seed;o&&await t(Object.entries(o).map(([l,u])=>({path:l,data:u})));const a=i?.authUsers;Array.isArray(a)&&await n(a.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function GF(e){if(e===null)return null;const t={collections:0,users:0,objects:0,rtdbKeys:0};for(const n of e)n.kind==="collection"?t.collections++:n.kind==="user"?t.users++:n.kind==="object"?t.objects++:n.kind==="rtdb-key"&&t.rtdbKeys++;return t}function Ps(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function JF(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Ps(e.collections,"collection")),e.users&&t.push(Ps(e.users,"user")),e.objects&&t.push(Ps(e.objects,"file")),e.rtdbKeys&&t.push(Ps(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Xi(){return{width:15,height:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0}}function YF(){return c.jsxs("svg",{...Xi(),children:[c.jsx("path",{d:"M12 4v10"}),c.jsx("path",{d:"M8 10l4 4 4-4"}),c.jsx("path",{d:"M4 19h16"})]})}function QF(){return c.jsxs("svg",{...Xi(),children:[c.jsx("path",{d:"M12 14V4"}),c.jsx("path",{d:"M8 8l4-4 4 4"}),c.jsx("path",{d:"M4 19h16"})]})}function XF(){return c.jsxs("svg",{...Xi(),children:[c.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),c.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),c.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),c.jsx("path",{d:"M7 8.4v7.2"}),c.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function ZF(){return c.jsxs("svg",{...Xi(),children:[c.jsx("path",{d:"M4 5v5h5"}),c.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Ds({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return c.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[c.jsxs("span",{className:"studio-sandbox__action-top",children:[e,c.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),c.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function eq(){const e=KF(),t=sF(),n=iF(),r=oF(),s=fs(),i=y.useRef(null),o=El(jl()),[a,l]=y.useState(!1),[u,d]=y.useState(!1),[h,f]=y.useState(!1),[p,m]=y.useState(!1),[g,b]=y.useState(""),w=pg(),{ensure:x}=w;y.useEffect(()=>x(),[x]);const v=GF(w.entries),_=JF(v),S=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",k=async()=>{const j=await t();if(!j||typeof document>"u")return;const $=URL.createObjectURL(new Blob([j],{type:"application/json"})),C=document.createElement("a");C.href=$,C.download=`pyric-sandbox-${o||"export"}.json`,C.click(),URL.revokeObjectURL($)},R=async j=>{const $=j.target.files?.[0];if(j.target.value="",!!$&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await $.text())}finally{d(!1)}}},O=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},P=async()=>{const j=g.trim();j&&(await r.save(j),b(""),m(!1))},A=async j=>{typeof window<"u"&&!window.confirm(`Restore saved state "${j}"? This replaces the current sandbox state.`)||await r.restore(j)},E=async j=>{typeof window<"u"&&!window.confirm(`Delete saved state "${j}"?`)||await r.remove(j)};return c.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),c.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),c.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),c.jsx("div",{className:"studio-settings__grid",children:c.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[c.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),c.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[c.jsx("span",{className:"studio-sandbox__instance mono",children:o||"local"}),c.jsx("span",{className:"studio-sandbox__inventory",children:_}),c.jsx("span",{className:"studio-sandbox__persist",children:S})]}),c.jsxs("div",{className:"studio-sandbox__actions",children:[c.jsx(Ds,{glyph:c.jsx(YF,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void k()}),c.jsx(Ds,{glyph:c.jsx(QF,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),c.jsx(Ds,{glyph:c.jsx(XF,{}),name:"Save state",caption:"Keeps a copy you can return to.",onClick:()=>m(j=>!j)}),c.jsx(Ds,{glyph:c.jsx(ZF,{}),name:a?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:a,danger:!0,onClick:()=>f(!0)})]}),c.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:R}),p?c.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:j=>{j.preventDefault(),P()},children:[c.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"saved state name","aria-label":"Saved state name",autoFocus:!0,onChange:j=>b(j.target.value),onKeyDown:j=>{j.key==="Escape"&&(m(!1),b(""))}}),c.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>{m(!1),b("")},children:"Cancel"})]}):null,h?c.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[c.jsx("span",{className:"studio-sandbox__confirm-copy",children:v&&_!=="empty — no data yet"?`This erases ${_}.`:"This erases everything in this sandbox."}),c.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[c.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void O(),children:"Erase and reseed"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.names.length>0?c.jsx("div",{className:"studio-settings__saved-states",children:r.names.map(j=>c.jsxs("div",{className:"studio-settings__saved-state",children:[c.jsx("span",{className:"mono",children:j}),c.jsxs("span",{className:"studio-settings__saved-state-actions",children:[c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void A(j),children:"Restore"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void E(j),children:"Delete"})]})]},j))}):c.jsx("p",{className:"studio-sandbox__saved-states-empty",children:"No saved states yet. Save state keeps this exact sandbox to come back to."})]})})]})}function Ts(e){return e===null?"absent":e===void 0?"unknown":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):JSON.stringify(e)}function tq(e){const t=e.stateDiff;if(!t)return"No state evidence";if(!t.changed)return e.mutation.output!==void 0?"Read result captured":"No state change";if(t.before&&t.after&&typeof t.before=="object"&&typeof t.after=="object"&&!Array.isArray(t.before)&&!Array.isArray(t.after)){const n=t.before,r=t.after,i=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(o=>JSON.stringify(n[o])!==JSON.stringify(r[o]));if(i.length>0&&i.length<=3)return i.map(o=>`${o}: ${Ts(n[o])} -> ${Ts(r[o])}`).join(", ")}return`${Ts(t.before)} -> ${Ts(t.after)}`}function nq(e){return e.results.map(t=>({id:t.probeId,service:t.control.operation.service,operation:`${t.mutation.operation.method} ${t.mutation.operation.path}`,actor:t.actorEvidence.uid??(t.actorEvidence.acquisition==="anonymous-request"?"anonymous":t.actorEvidence.actorId),expected:t.invariant.expected,observed:t.mutation.decision,classification:t.classification,impact:tq(t),supported:t.qualification.supported}))}function rq(e){const t=e.mutation.events.find(o=>o.result==="allow"||o.result==="deny"||o.result==="unsupported");if(!t)return null;const n=t.result,r={id:t.id??`${e.probeId}-decision`,at:t.at??0,result:n,method:t.method??t.op??e.mutation.operation.method,service:t.service??e.mutation.operation.service,path:t.path??e.mutation.operation.path,auth:t.auth??null,reasons:t.reasons??[],origin:t.origin??"user",unsupported:n==="unsupported"};t.queryProof&&(r.queryProof=t.queryProof),t.matchedRule&&(r.matchedRule=t.matchedRule),t.evaluatedRule&&(r.evaluatedRule=t.evaluatedRule),t.rules&&(r.rules=t.rules),t.resourceBefore&&(r.resourceBefore=t.resourceBefore);const s=t.request,i=s?.resourceData??s?.data;return i!==void 0&&(r.resourceData=i),r}const sq="pyric:assurance-campaign",iq="pyric-assurance-v1",fc=new Set;let bh=!1,wh;function vh(e){for(const t of fc)t(e)}function xh(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function oq(){if(!(bh||typeof document>"u")){bh=!0,globalThis.addEventListener(sq,e=>{const t=e.detail;xh(t)&&vh(t)});try{wh=new BroadcastChannel(iq),wh.onmessage=e=>{xh(e.data)&&vh(e.data)}}catch{}}}function aq(e){return oq(),fc.add(e),()=>fc.delete(e)}function Go(e){return{campaignId:"collaboration-local-v1",probeId:e.id,targetHash:"fnv1a32-7f4c911a",actorEvidence:{actorId:"member-b",acquisition:"password",reachability:"reachable",uid:"mallory"},invariant:{id:`${e.id}-invariant`,service:e.service,statement:e.statement,expected:"DENY",source:"declared",confidence:"authoritative"},mutationSpec:{dimension:e.service==="firestore"?"payload":"path",description:e.description,operation:e.mutation},control:{operation:e.control,decision:"ALLOW",events:[]},mutation:{operation:e.mutation,decision:"ALLOW",events:e.service==="firestore"?[{id:"req-firestore-owner-transfer",at:100,kind:"request",service:"firestore",method:"update",path:"rooms/r1",result:"allow",auth:{uid:"mallory",token:{}},reasons:["Rule #1 (update) -> ALLOW"],origin:"user",request:{resourceData:{ownerId:"mallory"}},resourceBefore:{exists:!0,data:e.before},matchedRule:{ruleIndex:0,operations:["update"]}}]:[]},stateDiff:{changed:!0,before:e.before,after:e.after},qualification:{engine:"pyric-local-sandboxes",supported:!0,requirements:[{id:`${e.service}.local-supported-subset`,supported:!0,reason:"This probe stays within the supported local evaluator subset."}]},classification:"local-counterexample"}}const cq=[Go({id:"firestore-owner-transfer",service:"firestore",control:{service:"firestore",method:"update",path:"rooms/r1",data:{title:"Edited"}},mutation:{service:"firestore",method:"update",path:"rooms/r1",data:{ownerId:"mallory"}},statement:"A non-owner room member must not change ownerId.",description:"Changed only the updated field from title to ownerId.",before:{ownerId:"alice",title:"Original title"},after:{ownerId:"mallory",title:"Original title"}}),Go({id:"rtdb-other-role",service:"rtdb",control:{service:"rtdb",method:"set",path:"/rooms/r1/members/mallory/status",data:"online"},mutation:{service:"rtdb",method:"set",path:"/rooms/r1/members/alice/role",data:"online"},statement:"A member must not change another member's role.",description:"Changed only the target path from own status to another member role.",before:"owner",after:"online"}),Go({id:"storage-overwrite-owner",service:"storage",control:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/mallory/note.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},mutation:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/alice/private.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},statement:"A member must not overwrite an object owned by another actor.",description:"Changed only the target from a new own object to an existing other-owned object.",before:{text:"alice-secret",customMetadata:{owner:"alice"}},after:{text:"mallory",customMetadata:{owner:"mallory"}}})],Tq=cq.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const hc="pyric:assurance:campaigns",rw="pyric:assurance:campaign:";function lq(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function uq(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(hc)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${rw}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(lq);return t.length,t}catch{return[]}}function dq(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(hc)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(hc,JSON.stringify(n)),sessionStorage.setItem(`${rw}${e.campaignId}`,JSON.stringify(e))}catch{}}function fq(e,t){const n=e.findIndex(s=>s.campaignId===t.campaignId);if(n===-1)return[...e,t];const r=[...e];return r[n]=t,r}function hq(){const[e,t]=y.useState(uq);return y.useEffect(()=>{const r=aq(s=>{dq(s),t(i=>fq(i,s))});return()=>{r()}},[]),e}function pq(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function mq(e){return e.replaceAll("-"," ")}function _h({value:e}){return c.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function yq(){return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),c.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function Sh({attachment:e}){return e?c.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[c.jsxs("span",{children:[c.jsx("strong",{children:e.source.origin}),"read-only clone"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function gq({campaigns:e}){const t=hq(),n=e??t,r=He().query,[s,i]=y.useState(r.campaign??n.find(v=>v.report)?.campaignId??n[0]?.campaignId??""),o=n.find(v=>v.campaignId===s)??n[0],a=y.useMemo(()=>o?.report?nq(o.report):[],[o]),[l,u]=y.useState(r.probe??a[0]?.id??"");if(y.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),y.useEffect(()=>{a.some(v=>v.id===l)||u(a[0]?.id??"")},[a,l]),!o)return c.jsx(yq,{});const d=o.context?.attachment,h=o.report;if(!h)return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:o.campaignId}),c.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),c.jsxs("p",{children:[o.observations.length," known-good operation(s) and"," ",o.probes.length," probe(s) are available."]}),c.jsx(Sh,{attachment:d}),d?.coverageGaps.length?c.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.service}),v.reason]},v.code))}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=a.find(v=>v.id===l)??a[0],p=h.results.find(v=>v.probeId===f?.id),m=p?rq(p):null,g=o.verifications?.at(-1),b=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function w(v){i(v);const S=n.find(k=>k.campaignId===v)?.report?.results[0]?.probeId??"";u(S),Hr({tab:"assurance",query:{campaign:v,probe:S||void 0}})}function x(v){u(v.id),Hr({tab:"assurance",query:{campaign:o.campaignId,probe:v.id}})}return c.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[c.jsxs("header",{className:"assurance-surface__header",children:[c.jsxs("div",{children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-title",children:o.campaignId})]}),c.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?c.jsxs("label",{children:[c.jsx("span",{children:"Campaign"}),c.jsx("select",{value:o.campaignId,onChange:v=>w(v.target.value),children:n.map(v=>c.jsx("option",{value:v.campaignId,children:v.campaignId},v.campaignId))})]}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),c.jsx(Sh,{attachment:d}),c.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Controls"}),c.jsxs("strong",{children:[h.summary.controlsPassed,"/",h.summary.probes]})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Counterexamples"}),c.jsx("strong",{children:h.summary.localCounterexamples})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Candidate signals"}),c.jsx("strong",{children:h.summary.candidateSignals})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Engine gaps"}),c.jsx("strong",{children:h.summary.engineGaps})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Coverage gaps"}),c.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?c.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${b?"passed":"failed"}`,role:"status",children:[c.jsx("strong",{children:b?"Candidate rules verified":"Candidate rules need review"}),c.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),c.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?c.jsxs("div",{className:"assurance-coverage-band",children:[c.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),c.jsx("span",{children:d.coverageGaps.map(v=>`${v.service}: ${v.reason}`).join(" ")})]}):null,c.jsxs("div",{className:"assurance-workspace",children:[c.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),c.jsx("span",{children:h.targetHash})]}),c.jsxs("div",{className:"assurance-table",role:"table",children:[c.jsxs("div",{className:"assurance-table__header",role:"row",children:[c.jsx("span",{role:"columnheader",children:"Operation"}),c.jsx("span",{role:"columnheader",children:"Actor"}),c.jsx("span",{role:"columnheader",children:"Expected"}),c.jsx("span",{role:"columnheader",children:"Observed"}),c.jsx("span",{role:"columnheader",children:"Impact"})]}),a.map(v=>c.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":v.id===f?.id,onClick:()=>x(v),role:"row",children:[c.jsxs("span",{role:"cell",children:[c.jsx("small",{children:v.service}),v.operation]}),c.jsx("span",{role:"cell",children:v.actor}),c.jsx("span",{role:"cell",className:`assurance-verdict ${v.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:v.expected}),c.jsx("span",{role:"cell",className:`assurance-verdict ${pq(v.expected,v.observed)}`,children:v.observed}),c.jsx("span",{role:"cell",children:v.impact})]},v.id))]})]}),p?c.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsxs("div",{children:[c.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:mq(p.classification)}),c.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),c.jsx("span",{children:p.actorEvidence.reachability})]}),c.jsxs("dl",{className:"assurance-facts",children:[c.jsxs("div",{children:[c.jsx("dt",{children:"Invariant"}),c.jsx("dd",{children:p.invariant.statement})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Mutation"}),c.jsx("dd",{children:p.mutationSpec.description})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Actor"}),c.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Fidelity"}),c.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(v=>!v.supported)?c.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(v=>!v.supported).map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.id}),v.reason]},v.id))}):null,p.stateDiff?c.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[c.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),c.jsxs("div",{className:"assurance-evidence__diff",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Before"}),c.jsx(_h,{value:p.stateDiff.before})]}),c.jsxs("div",{children:[c.jsx("span",{children:"After"}),c.jsx(_h,{value:p.stateDiff.after})]})]})]}):null,m?c.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[c.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),c.jsx(xb,{denial:m})]}):c.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function kh(){return qi()}function sw(){return`${qi()}docs`}function Eh(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function bq(){const[e,t]=y.useState(!1);return y.useEffect(()=>{let n=!0;return fetch(`${sw()}/index.json`,{method:"HEAD"}).then(r=>{const s=r.headers.get("content-type")??"";n&&r.ok&&s.includes("json")&&t(!0)}).catch(()=>{}),()=>{n=!1}},[]),e}function wq({id:e}){const t=cP(e),n=Ht(),r=[`route #${t.id}`];return n.status==="ready"?(r.push(`events: ${n.events.length}`),r.push("dev-seed: ready")):n.status==="pending"?r.push("dev-seed: seeding…"):n.status==="error"?r.push("dev-seed: error"):r.push("dev-seed: off"),c.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[c.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),c.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),c.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),c.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>c.jsx("span",{children:s},s))})]})}function vq({id:e}){switch(e){case"home":return c.jsx(wF,{});case"firestore":return c.jsx(OU,{});case"auth":return c.jsx(UU,{});case"storage":return c.jsx($U,{});case"rtdb":return c.jsx(UF,{});case"traffic":return c.jsx(rF,{});case"assurance":return c.jsx(gq,{});case"settings":return c.jsx(eq,{});default:return c.jsx(wq,{id:e})}}function xq(){const[e,t]=fP(aP,"home"),n=u=>t(u),[r,s]=y.useState(!1),i=bq(),[o]=y.useState(()=>D1());y.useEffect(()=>{if(!o.open)return;const u={view:"listeners"};o.listenerId!==void 0&&(u.listener=o.listenerId),o.targetPrefix!==void 0&&(u.target=o.targetPrefix),Hr({tab:"traffic",query:u})},[]);const a=e==="home";y.useEffect(()=>{const u=d=>{if(mP(d)){if(r){d.preventDefault(),s(!1);return}if(a){pP()&&d.preventDefault();return}d.preventDefault(),s(!0)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a,r]),y.useEffect(()=>{a&&s(!1)},[a]),y.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const l=un.filter(u=>u.id!=="home");return c.jsxs("div",{className:"studio","data-surface":e,children:[c.jsxs("header",{className:"studio__chrome",children:[c.jsx("div",{className:"studio__bar",children:c.jsxs("div",{className:"studio__chrome-inner",children:[c.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[c.jsx("a",{className:"studio__brand",href:kh(),"aria-label":"Pyric",children:"pyric"}),c.jsx("a",{className:"studio__nav-tab",href:kh(),children:"Home"}),i?c.jsx("a",{className:"studio__nav-tab",href:sw(),children:"Docs"}):null,c.jsx("a",{className:"studio__nav-tab",href:kt({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:Eh(()=>n("home")),children:"Studio"})]}),c.jsx(ST,{})]})}),c.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:c.jsx("div",{className:"studio__chrome-inner",children:c.jsx("div",{className:"studio__nav",children:l.map(u=>c.jsx("a",{className:"studio__nav-tab",href:kt({tab:u.id}),"aria-current":u.id===e?"page":void 0,onClick:Eh(()=>n(u.id)),children:u.label},u.id))})})})]}),c.jsx("main",{className:"studio__content","data-surface":e,children:c.jsx("div",{className:"studio__surface-slot","data-active":"true",children:c.jsx(vq,{id:e})})}),r?c.jsx(GP,{onClose:()=>s(!1)}):null]})}function _q(){return c.jsx(nP,{children:c.jsx(LR,{children:c.jsx(Q$,{mode:"local",children:c.jsx(xq,{})})})})}function Mq(){return c.jsx(y.StrictMode,{children:c.jsx(_q,{})})}export{Mq as S,Dq as a,kE as b,Pr as r,ve as s,WC as u};