@pyric/cli 0.1.0-alpha.21 → 0.1.0-alpha.22

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 (154) hide show
  1. package/dist/assurance/.generated/conformance-verdicts.d.ts +170 -0
  2. package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
  3. package/dist/assurance/.generated/conformance-verdicts.js +170 -0
  4. package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
  5. package/dist/conformance/.generated/can-i-use-browser.d.ts +1 -1
  6. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  7. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  8. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  9. package/dist/conformance/.generated/can-i-use.d.ts +1 -1
  10. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  11. package/dist/conformance/.generated/can-i-use.js +1 -1
  12. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  13. package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
  14. package/dist/conformance/.generated/conformance-docs.js +1 -1
  15. package/dist/conformance/.generated/conformance-docs.js.map +1 -1
  16. package/dist/serve/site-ui/_astro/{app.DhAcImFD.js → app.CMmTxyhL.js} +1 -1
  17. package/dist/serve/site-ui/_astro/{app.BOr2kwae.js → app.DhALsVii.js} +12 -12
  18. package/dist/serve/site-ui/_astro/{seed.03a08f9t.js → seed.lywYbXZ0.js} +1 -1
  19. package/dist/serve/site-ui/auth/index.html +1 -1
  20. package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
  21. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +1 -1
  22. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
  23. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
  24. package/dist/serve/site-ui/docs/ai-compat/index.html +1 -1
  25. package/dist/serve/site-ui/docs/api-reference/index.html +1 -1
  26. package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
  27. package/dist/serve/site-ui/docs/auth-compat/index.html +1 -1
  28. package/dist/serve/site-ui/docs/build/ai-logic/index.html +1 -1
  29. package/dist/serve/site-ui/docs/build/authentication/index.html +2 -2
  30. package/dist/serve/site-ui/docs/build/authentication.md +1 -1
  31. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +4 -2
  32. package/dist/serve/site-ui/docs/build/cloud-firestore.md +4 -0
  33. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
  34. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +1 -1
  35. package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
  36. package/dist/serve/site-ui/docs/conformance-scores/index.html +9 -1
  37. package/dist/serve/site-ui/docs/conformance-scores.md +8 -0
  38. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +1 -1
  39. package/dist/serve/site-ui/docs/database-compat/index.html +1 -1
  40. package/dist/serve/site-ui/docs/examples/chess/index.html +1 -1
  41. package/dist/serve/site-ui/docs/examples/index.html +1 -1
  42. package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
  43. package/dist/serve/site-ui/docs/firestore-flutter-compat/index.html +1 -1
  44. package/dist/serve/site-ui/docs/firestore-kotlin-compat/index.html +319 -0
  45. package/dist/serve/site-ui/docs/firestore-kotlin-compat.md +344 -0
  46. package/dist/serve/site-ui/docs/firestore-swift-compat/index.html +490 -0
  47. package/dist/serve/site-ui/docs/firestore-swift-compat.md +517 -0
  48. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +1 -1
  49. package/dist/serve/site-ui/docs/get-started/backend-bundlers/index.html +1 -1
  50. package/dist/serve/site-ui/docs/get-started/flutter/index.html +98 -0
  51. package/dist/serve/site-ui/docs/get-started/flutter.md +105 -0
  52. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
  53. package/dist/serve/site-ui/docs/get-started/nextjs/index.html +1 -1
  54. package/dist/serve/site-ui/docs/get-started/start-building/index.html +1 -1
  55. package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
  56. package/dist/serve/site-ui/docs/index.json +255 -0
  57. package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
  58. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +4 -3
  59. package/dist/serve/site-ui/docs/observe/resolve-runtime-status.md +3 -1
  60. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
  61. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
  62. package/dist/serve/site-ui/docs/observe/switch-and-impersonate-identities/index.html +110 -0
  63. package/dist/serve/site-ui/docs/observe/switch-and-impersonate-identities.md +134 -0
  64. package/dist/serve/site-ui/docs/overview/index.html +1 -1
  65. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  66. package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  67. package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  68. package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  69. package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
  70. package/dist/serve/site-ui/docs/pyric-admin-reference-api/index.html +1 -1
  71. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  72. package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
  73. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  74. package/dist/serve/site-ui/docs/pyric-analytics-reference-api/index.html +1 -1
  75. package/dist/serve/site-ui/docs/pyric-app-check-reference-api/index.html +1 -1
  76. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
  77. package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +1 -1
  78. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  79. package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  80. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  81. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  82. package/dist/serve/site-ui/docs/pyric-cli-bundler-reference-api/index.html +1 -1
  83. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +3 -1
  84. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api.md +2 -0
  85. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  86. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +3 -1
  87. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api.md +2 -0
  88. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  89. package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  90. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -1
  91. package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +1 -1
  92. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  93. package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  94. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +1 -1
  95. package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  96. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +1 -1
  97. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
  98. package/dist/serve/site-ui/docs/pyric-firestore-lite-reference-api/index.html +1 -1
  99. package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  100. package/dist/serve/site-ui/docs/pyric-functions-reference-api/index.html +1 -1
  101. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  102. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  103. package/dist/serve/site-ui/docs/pyric-performance-reference-api/index.html +1 -1
  104. package/dist/serve/site-ui/docs/pyric-remote-config-reference-api/index.html +1 -1
  105. package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +1 -1
  106. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  107. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  108. package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +1 -1
  109. package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +2 -2
  110. package/dist/serve/site-ui/docs/pyric-storage-reference-api.md +1 -1
  111. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  112. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  113. package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  114. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  115. package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  116. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  117. package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  118. package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  119. package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  120. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  121. package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
  122. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  123. package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  124. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  125. package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  126. package/dist/serve/site-ui/docs/reference/cli/index.html +1 -1
  127. package/dist/serve/site-ui/docs/rules-compat/index.html +1 -1
  128. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
  129. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  130. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
  131. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  132. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
  133. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  134. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +1 -1
  135. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  136. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
  137. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
  138. package/dist/serve/site-ui/docs/storage-compat/index.html +1 -1
  139. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  140. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
  141. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  142. package/dist/serve/site-ui/docs/tutorial/index.html +1 -1
  143. package/dist/serve/site-ui/firestore/index.html +1 -1
  144. package/dist/serve/site-ui/llms.txt +4 -0
  145. package/dist/serve/site-ui/rtdb/index.html +1 -1
  146. package/dist/serve/site-ui/settings/index.html +1 -1
  147. package/dist/serve/site-ui/storage/index.html +1 -1
  148. package/dist/serve/site-ui/studio/index.html +1 -1
  149. package/dist/serve/site-ui/traffic/index.html +1 -1
  150. package/package.json +4 -4
  151. package/src/assurance/.generated/conformance-verdicts.ts +170 -0
  152. package/src/conformance/.generated/can-i-use-browser.ts +2 -2
  153. package/src/conformance/.generated/can-i-use.ts +2 -2
  154. package/src/conformance/.generated/conformance-docs.ts +1 -1
@@ -1,8 +1,8 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.03a08f9t.js","_astro/sandbox-controls.rOuZTOUG.js","_astro/writes.BsPBG3dp.js","_astro/index.DBy5LfQW.js","_astro/index.DNyk7q8W.js","_astro/RulesCodeEditor.DsTAsKIa.js"])))=>i.map(i=>d[i]);
2
- import{g as Ll,e as Ie,m as Cn,d as Ja,f as Fl,h as Vl,o as sn,k as ql,u as zt,l as ze,r as wr,n as Wl,p as zl,q as Ya,t as Ls,v as Kl,i as Hl,j as o,w as Gl,x as Jl,y as Yl,z as Ql,R as Se,A as Xl,B as Fs,C as Qa,S as Zl,Z as Xa,D as eu,E as tu,F as nu,G as ru,H as su,I as iu,J as au,K as Nn,L as ou,M as cu,N as Za,O as lu,T as pt}from"./sandbox-controls.rOuZTOUG.js";import{r as h}from"./index.DBy5LfQW.js";import{r as eo,c as Pe,t as Ke,a as Rn,f as to,b as Vs,e as us,h as no,j as ds,u as xr,k as uu,l as An,m as du,n as fu,p as hu,o as qs,q as pu,v as mu,F as mt,d as We,w as Nt,s as ln,x as ro,y as Ws,z as jr,A as yu,g as so,B as io,C as bu,D as gu,i as vu,G as lt,E as In}from"./writes.BsPBG3dp.js";import{r as wu}from"./index.DNyk7q8W.js";const Ge={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},xu=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],ju={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 _u(e){return xu.includes(e)}class ee extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ye extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const ku={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},Su={true:"true",false:"false",null:"null"};function Eu(e){if(e.length>Ge.maxExpressionLength)throw new ee(`expression exceeds ${Ge.maxExpressionLength}-character cap (got ${e.length})`,F(Ge.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:a,next:c}=Ru(e,n,s);if(t.push(a),n=c,n<=r)throw new ee("lexer stalled on string",F(r));continue}if(s>="0"&&s<="9"){const{token:a,next:c}=Nu(e,n);if(t.push(a),n=c,n<=r)throw new ee("lexer stalled on number",F(r));continue}if(Dn(s)){const{token:a,next:c}=Cu(e,n);t.push(a),n=c;continue}if(s==="$"){const{token:a,next:c}=zs(e,n,"$","reference");t.push(a),n=c;continue}if(s==="@"){const{token:a,next:c}=zs(e,n,"@","sentinel");t.push(a),n=c;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:F(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:F(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:F(n)}),n+=2):(t.push({kind:"lt",pos:F(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:F(n)}),n+=2):(t.push({kind:"gt",pos:F(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new ee("unexpected '&' (did you mean '&&'?)",F(n));t.push({kind:"and",pos:F(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new ee("unexpected '|' (did you mean '||'?)",F(n));t.push({kind:"or",pos:F(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:F(n)}),n+=1;continue}if(s==="=")throw new ee("unexpected '=' (did you mean '=='?)",F(n));const i=ku[s];if(i){t.push({kind:i,pos:F(n)}),n+=1;continue}throw new ee(`unexpected character ${JSON.stringify(s)}`,F(n))}return t.push({kind:"eof",pos:F(e.length)}),t}function F(e){return{offset:e,column:e+1}}function Dn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function ao(e){return Dn(e)||e>="0"&&e<="9"}function Cu(e,t){let n=t+1;for(;n<e.length&&ao(e[n]);)n+=1;const r=e.slice(t,n),s=Su[r];return s?{token:{kind:s,pos:F(t)},next:n}:{token:{kind:"identifier",pos:F(t),value:r},next:n}}function zs(e,t,n,r){const s=t+1;if(s>=e.length||!Dn(e[s]))throw new ee(`expected identifier after '${n}'`,F(t));let i=s+1;for(;i<e.length&&ao(e[i]);)i+=1;const a=e.slice(s,i);return{token:{kind:r,pos:F(t),value:a},next:i}}function Nu(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 ee("leading zeros are not allowed in number literals",F(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const c=e[n+1];if(c!==void 0&&c>="0"&&c<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(c!==void 0&&Dn(c)))throw new ee("expected digit after '.' in number literal",F(n))}const i=e.slice(t,n),a=Number.parseFloat(i);if(!Number.isFinite(a))throw new ee(`numeric literal '${i}' is not finite`,F(t));if(!s&&!Number.isSafeInteger(a))throw new ee(`integer literal '${i}' exceeds safe integer range`,F(t));return{token:{kind:"number",pos:F(t),value:a},next:n}}function Ru(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:F(t),value:s},next:r+1};if(i==="\\"){const a=e[r+1];if(a===void 0)throw new ee("unterminated escape sequence in string literal",F(r));switch(a){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
4
- `;break;case"t":s+=" ";break;default:throw new ee(`invalid escape sequence '\\${a}' (only \\", \\', \\\\, \\n, \\t are allowed)`,F(r))}r+=2}else{if(i===`
5
- `||i==="\r")throw new ee("unterminated string literal (newline before closing quote)",F(t));s+=i,r+=1}if(s.length>Ge.maxStringLiteralLength)throw new ee(`string literal exceeds ${Ge.maxStringLiteralLength}-character cap`,F(t))}throw new ee("unterminated string literal",F(t))}function Au(e){const t=new Iu(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),$u(n),n}class Iu{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=Du(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 ye(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ye("unexpected end of expression",t.pos);default:throw new ye("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!_u(n))throw new ye(`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=ju[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 ye(`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 ye(`${n} (got ${Pu(r)})`,r.pos);return this.consume()}}function Du(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 Pu(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function $u(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>Ge.maxAstDepth)throw new ye(`expression AST exceeds depth cap of ${Ge.maxAstDepth}`,n.pos);return s}}class oe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function Ut(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 ue(e,t){return new oe("type-mismatch",t,e.pos)}function ce(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Ou(e,t);case"sentinel":return Tu(e,t);case"unary":return Mu(e,t);case"binary":return Uu(e,t);case"logical":return Lu(e,t);case"ternary":return Fu(e,t);case"fieldAccess":return Vu(e,t);case"indexAccess":return qu(e,t)}}function Ou(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new oe("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 Tu(e,t){const n=e.args.map(r=>{const s=ce(r,t);if(Ut(s))throw new oe("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 ue(e,`'@increment' expects a numeric argument, got ${re(r)}`);return un(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function Mu(e,t){const n=ce(e.operand,t);if(_r(n,e),e.op==="-"){if(typeof n!="number")throw ue(e,`unary '-' expects a number, got ${re(n)}`);const r=-n;return un(r,e),r}if(typeof n!="boolean")throw ue(e,`unary '!' expects a boolean, got ${re(n)}`);return!n}function Uu(e,t){const n=ce(e.left,t),r=ce(e.right,t);switch(_r(n,e),_r(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return un(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw ue(e,`'+' expects (number, number) or (string, string); got (${re(n)}, ${re(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw ue(e,`'${e.op}' expects (number, number); got (${re(n)}, ${re(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 un(s,e),s}case"==":return Ks(e,n,r);case"!=":return!Ks(e,n,r);case"<":case"<=":case">":case">=":return Bu(e,n,r)}}function Ks(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 ue(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function Bu(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw ue(e,`'${e.op}' expects matching number/number or string/string operands; got (${re(t)}, ${re(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 Lu(e,t){const n=ce(e.left,t);if(typeof n!="boolean")throw ue(e,`'${e.op}' expects boolean operands; left is ${re(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=ce(e.right,t);if(typeof r!="boolean")throw ue(e,`'${e.op}' expects boolean operands; right is ${re(r)}`);return r}function Fu(e,t){const n=ce(e.cond,t);if(typeof n!="boolean")throw ue(e,`ternary condition must be boolean, got ${re(n)}`);return ce(n?e.whenTrue:e.whenFalse,t)}function Vu(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||Ut(n))throw ue(e,`cannot access field '${e.field}' on ${re(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function qu(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access","cannot index null target",e.pos);const r=ce(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new oe("invalid-index",`array index must be a non-negative integer, got ${re(r)}`,e.pos);if(r<0)throw new oe("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"&&!Ut(n)){if(typeof r!="string")throw new oe("invalid-index",`object key must be a string, got ${re(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw ue(e,`cannot index into ${re(n)}`)}function _r(e,t){if(Ut(e))throw new oe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function un(e,t){if(!Number.isFinite(e))throw new oe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function re(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(Ut(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 oo="$expr";class dn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function Wu(e,t){return kr(e,t,"")}function kr(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 a=0;a<e.length;a+=1)i[a]=kr(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,oo))return zu(r,t,n);const s={};for(const i of Object.keys(r))s[i]=kr(r[i],t,n===""?i:`${n}.${i}`);return s}function zu(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new dn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(c=>JSON.stringify(c)).join(", ")}]`,n);const s=e[oo];if(typeof s!="string")throw new dn(`'$expr' value at '${n||"<root>"}' must be a string, got ${Gu(s)}`,n);const i=Hu(s,n);return Ku(i,t,n)}function Ku(e,t,n){try{return ce(e,t)}catch(r){if(r instanceof oe){const s=new oe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function Hu(e,t){try{return Au(Eu(e))}catch(n){throw n instanceof ee?Hs(n,ee,t):n instanceof ye?Hs(n,ye,t):n}}function Hs(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function Gu(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ju(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. 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 a=s;if(a.includes("'2+modules'")||a.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 u=n(a);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};a=u.data.resolved}const l=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:l,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:a,data:c}=r,u=(await t()).execute({method:s,path:i,auth:a,data:c});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:a,evaluateRules:c}=r,l=await t();if(c){const u=l.execute({method:i??"get",path:s,auth:a??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,c=(await t()).batch(s,i);return{ok:c.allowed,summary:c.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:c.allowed,results:c.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:a}=r,c=await t(),{path:l,result:u}=c.createWithAutoId(s,a,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 the log is empty.",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 every event the sandbox has seen — allowed and denied — with timestamps, auth, and debug messages. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){return{ok:!0,summary:"Event log",data:{events:(await t()).getEvents().map(s=>({id:s.id,method:s.method,path:s.path,allowed:s.allowed,auth:s.auth,debugMessages:s.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:a,reads:c,writes:l}=r;for(let m=0;m<l.length;m+=1){const f=l[m];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${m}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${m}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=a===!0;try{const m=u.transaction(p=>{const y={};for(const[b,v]of Object.entries(c)){const w=p.get(v).data();y[b]=w===void 0?null:w}for(let b=0;b<l.length;b+=1){const v=l[b];if(v.method==="delete"){p.delete(v.path);continue}const g=Wu(v.data,{reads:y});if(g===null||typeof g!="object"||Array.isArray(g))throw new dn(`writes[${b}].data resolved to a non-object`,`writes.${b}.data`);const w=g;switch(v.method){case"create":p.create(v.path,w);break;case"update":p.update(v.path,w);break;case"set":p.set(v.path,w);break}}},{auth:s,readOnly:i}),f={allowed:m.allowed,writes:m.writes.map(p=>{const y={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(y.error={code:p.error.code,message:p.error.message}),d&&(y.debugMessages=p.debugMessages),y})};return m.error&&(f.error={code:m.error.code,message:m.error.message}),m.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=m.reads.map(p=>({path:p.path,data:p.data}))),{ok:m.allowed,summary:m.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(m){if(m instanceof dn||m instanceof ee||m instanceof ye||m instanceof oe)return{ok:!1,summary:`Transaction failed: ${m.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:m.message}}};throw m}}}]}function Yu(e){return Ju({resolveSandbox:e.resolveSandbox,resolveModulesFn:eo})}const Qu=`RtdbExpr {
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.lywYbXZ0.js","_astro/sandbox-controls.rOuZTOUG.js","_astro/writes.BsPBG3dp.js","_astro/index.DBy5LfQW.js","_astro/index.DNyk7q8W.js","_astro/RulesCodeEditor.DsTAsKIa.js"])))=>i.map(i=>d[i]);
2
+ import{g as Hl,e as Pe,m as In,d as eo,f as Gl,h as Jl,o as cn,k as Yl,u as Gt,l as Ge,r as Er,n as Ql,p as Xl,q as to,t as Ks,v as Zl,i as eu,j as o,w as tu,x as nu,y as ru,z as su,R as Ce,A as iu,B as Hs,C as no,S as au,Z as ro,D as ou,E as cu,F as lu,G as uu,H as du,I as fu,J as hu,K as Dn,L as pu,M as mu,N as so,O as yu,T as bt}from"./sandbox-controls.rOuZTOUG.js";import{r as h}from"./index.DBy5LfQW.js";import{r as io,c as Oe,t as Je,a as Pn,f as ao,b as Gs,e as ys,h as oo,j as bs,u as Cr,k as bu,l as $n,m as gu,n as vu,p as wu,o as Js,q as xu,v as ju,F as gt,d as He,w as It,s as fn,x as co,y as Ys,z as Nr,A as ku,g as lo,B as uo,C as _u,D as Su,i as Eu,G as ft,E as On}from"./writes.BsPBG3dp.js";import{r as Cu}from"./index.DNyk7q8W.js";const Qe={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Nu=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],Ru={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 Au(e){return Nu.includes(e)}class te extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ge extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const Iu={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},Du={true:"true",false:"false",null:"null"};function Pu(e){if(e.length>Qe.maxExpressionLength)throw new te(`expression exceeds ${Qe.maxExpressionLength}-character cap (got ${e.length})`,F(Qe.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:a,next:c}=Tu(e,n,s);if(t.push(a),n=c,n<=r)throw new te("lexer stalled on string",F(r));continue}if(s>="0"&&s<="9"){const{token:a,next:c}=Ou(e,n);if(t.push(a),n=c,n<=r)throw new te("lexer stalled on number",F(r));continue}if(Tn(s)){const{token:a,next:c}=$u(e,n);t.push(a),n=c;continue}if(s==="$"){const{token:a,next:c}=Qs(e,n,"$","reference");t.push(a),n=c;continue}if(s==="@"){const{token:a,next:c}=Qs(e,n,"@","sentinel");t.push(a),n=c;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:F(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:F(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:F(n)}),n+=2):(t.push({kind:"lt",pos:F(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:F(n)}),n+=2):(t.push({kind:"gt",pos:F(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new te("unexpected '&' (did you mean '&&'?)",F(n));t.push({kind:"and",pos:F(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new te("unexpected '|' (did you mean '||'?)",F(n));t.push({kind:"or",pos:F(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:F(n)}),n+=1;continue}if(s==="=")throw new te("unexpected '=' (did you mean '=='?)",F(n));const i=Iu[s];if(i){t.push({kind:i,pos:F(n)}),n+=1;continue}throw new te(`unexpected character ${JSON.stringify(s)}`,F(n))}return t.push({kind:"eof",pos:F(e.length)}),t}function F(e){return{offset:e,column:e+1}}function Tn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function fo(e){return Tn(e)||e>="0"&&e<="9"}function $u(e,t){let n=t+1;for(;n<e.length&&fo(e[n]);)n+=1;const r=e.slice(t,n),s=Du[r];return s?{token:{kind:s,pos:F(t)},next:n}:{token:{kind:"identifier",pos:F(t),value:r},next:n}}function Qs(e,t,n,r){const s=t+1;if(s>=e.length||!Tn(e[s]))throw new te(`expected identifier after '${n}'`,F(t));let i=s+1;for(;i<e.length&&fo(e[i]);)i+=1;const a=e.slice(s,i);return{token:{kind:r,pos:F(t),value:a},next:i}}function Ou(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 te("leading zeros are not allowed in number literals",F(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const c=e[n+1];if(c!==void 0&&c>="0"&&c<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(c!==void 0&&Tn(c)))throw new te("expected digit after '.' in number literal",F(n))}const i=e.slice(t,n),a=Number.parseFloat(i);if(!Number.isFinite(a))throw new te(`numeric literal '${i}' is not finite`,F(t));if(!s&&!Number.isSafeInteger(a))throw new te(`integer literal '${i}' exceeds safe integer range`,F(t));return{token:{kind:"number",pos:F(t),value:a},next:n}}function Tu(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:F(t),value:s},next:r+1};if(i==="\\"){const a=e[r+1];if(a===void 0)throw new te("unterminated escape sequence in string literal",F(r));switch(a){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
4
+ `;break;case"t":s+=" ";break;default:throw new te(`invalid escape sequence '\\${a}' (only \\", \\', \\\\, \\n, \\t are allowed)`,F(r))}r+=2}else{if(i===`
5
+ `||i==="\r")throw new te("unterminated string literal (newline before closing quote)",F(t));s+=i,r+=1}if(s.length>Qe.maxStringLiteralLength)throw new te(`string literal exceeds ${Qe.maxStringLiteralLength}-character cap`,F(t))}throw new te("unterminated string literal",F(t))}function Mu(e){const t=new Uu(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),Fu(n),n}class Uu{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=Bu(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 ge(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ge("unexpected end of expression",t.pos);default:throw new ge("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!Au(n))throw new ge(`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=Ru[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 ge(`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 ge(`${n} (got ${Lu(r)})`,r.pos);return this.consume()}}function Bu(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 Lu(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function Fu(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>Qe.maxAstDepth)throw new ge(`expression AST exceeds depth cap of ${Qe.maxAstDepth}`,n.pos);return s}}class le extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function Ft(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 fe(e,t){return new le("type-mismatch",t,e.pos)}function ue(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Vu(e,t);case"sentinel":return qu(e,t);case"unary":return Wu(e,t);case"binary":return zu(e,t);case"logical":return Hu(e,t);case"ternary":return Gu(e,t);case"fieldAccess":return Ju(e,t);case"indexAccess":return Yu(e,t)}}function Vu(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new le("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 qu(e,t){const n=e.args.map(r=>{const s=ue(r,t);if(Ft(s))throw new le("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 fe(e,`'@increment' expects a numeric argument, got ${ie(r)}`);return hn(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function Wu(e,t){const n=ue(e.operand,t);if(Rr(n,e),e.op==="-"){if(typeof n!="number")throw fe(e,`unary '-' expects a number, got ${ie(n)}`);const r=-n;return hn(r,e),r}if(typeof n!="boolean")throw fe(e,`unary '!' expects a boolean, got ${ie(n)}`);return!n}function zu(e,t){const n=ue(e.left,t),r=ue(e.right,t);switch(Rr(n,e),Rr(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return hn(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw fe(e,`'+' expects (number, number) or (string, string); got (${ie(n)}, ${ie(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw fe(e,`'${e.op}' expects (number, number); got (${ie(n)}, ${ie(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 hn(s,e),s}case"==":return Xs(e,n,r);case"!=":return!Xs(e,n,r);case"<":case"<=":case">":case">=":return Ku(e,n,r)}}function Xs(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 fe(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function Ku(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw fe(e,`'${e.op}' expects matching number/number or string/string operands; got (${ie(t)}, ${ie(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 Hu(e,t){const n=ue(e.left,t);if(typeof n!="boolean")throw fe(e,`'${e.op}' expects boolean operands; left is ${ie(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=ue(e.right,t);if(typeof r!="boolean")throw fe(e,`'${e.op}' expects boolean operands; right is ${ie(r)}`);return r}function Gu(e,t){const n=ue(e.cond,t);if(typeof n!="boolean")throw fe(e,`ternary condition must be boolean, got ${ie(n)}`);return ue(n?e.whenTrue:e.whenFalse,t)}function Ju(e,t){const n=ue(e.target,t);if(n==null)throw new le("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||Ft(n))throw fe(e,`cannot access field '${e.field}' on ${ie(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function Yu(e,t){const n=ue(e.target,t);if(n==null)throw new le("null-access","cannot index null target",e.pos);const r=ue(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new le("invalid-index",`array index must be a non-negative integer, got ${ie(r)}`,e.pos);if(r<0)throw new le("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"&&!Ft(n)){if(typeof r!="string")throw new le("invalid-index",`object key must be a string, got ${ie(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw fe(e,`cannot index into ${ie(n)}`)}function Rr(e,t){if(Ft(e))throw new le("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function hn(e,t){if(!Number.isFinite(e))throw new le("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function ie(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(Ft(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 ho="$expr";class pn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function Qu(e,t){return Ar(e,t,"")}function Ar(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 a=0;a<e.length;a+=1)i[a]=Ar(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,ho))return Xu(r,t,n);const s={};for(const i of Object.keys(r))s[i]=Ar(r[i],t,n===""?i:`${n}.${i}`);return s}function Xu(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new pn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(c=>JSON.stringify(c)).join(", ")}]`,n);const s=e[ho];if(typeof s!="string")throw new pn(`'$expr' value at '${n||"<root>"}' must be a string, got ${td(s)}`,n);const i=ed(s,n);return Zu(i,t,n)}function Zu(e,t,n){try{return ue(e,t)}catch(r){if(r instanceof le){const s=new le(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function ed(e,t){try{return Mu(Pu(e))}catch(n){throw n instanceof te?Zs(n,te,t):n instanceof ge?Zs(n,ge,t):n}}function Zs(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function td(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function nd(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. 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 a=s;if(a.includes("'2+modules'")||a.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 u=n(a);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};a=u.data.resolved}const l=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:l,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:a,data:c}=r,u=(await t()).execute({method:s,path:i,auth:a,data:c});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:a,evaluateRules:c}=r,l=await t();if(c){const u=l.execute({method:i??"get",path:s,auth:a??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,c=(await t()).batch(s,i);return{ok:c.allowed,summary:c.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:c.allowed,results:c.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:a}=r,c=await t(),{path:l,result:u}=c.createWithAutoId(s,a,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 the log is empty.",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 every event the sandbox has seen — allowed and denied — with timestamps, auth, and debug messages. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){return{ok:!0,summary:"Event log",data:{events:(await t()).getEvents().map(s=>({id:s.id,method:s.method,path:s.path,allowed:s.allowed,auth:s.auth,debugMessages:s.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:a,reads:c,writes:l}=r;for(let m=0;m<l.length;m+=1){const f=l[m];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${m}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${m}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=a===!0;try{const m=u.transaction(p=>{const y={};for(const[b,v]of Object.entries(c)){const w=p.get(v).data();y[b]=w===void 0?null:w}for(let b=0;b<l.length;b+=1){const v=l[b];if(v.method==="delete"){p.delete(v.path);continue}const g=Qu(v.data,{reads:y});if(g===null||typeof g!="object"||Array.isArray(g))throw new pn(`writes[${b}].data resolved to a non-object`,`writes.${b}.data`);const w=g;switch(v.method){case"create":p.create(v.path,w);break;case"update":p.update(v.path,w);break;case"set":p.set(v.path,w);break}}},{auth:s,readOnly:i}),f={allowed:m.allowed,writes:m.writes.map(p=>{const y={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(y.error={code:p.error.code,message:p.error.message}),d&&(y.debugMessages=p.debugMessages),y})};return m.error&&(f.error={code:m.error.code,message:m.error.message}),m.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=m.reads.map(p=>({path:p.path,data:p.data}))),{ok:m.allowed,summary:m.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(m){if(m instanceof pn||m instanceof te||m instanceof ge||m instanceof le)return{ok:!1,summary:`Transaction failed: ${m.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:m.message}}};throw m}}}]}function rd(e){return nd({resolveSandbox:e.resolveSandbox,resolveModulesFn:io})}const sd=`RtdbExpr {
6
6
  Expr = Ternary
7
7
 
8
8
  Ternary
@@ -103,13 +103,13 @@ import{g as Ll,e as Ie,m as Cn,d as Ja,f as Fl,h as Vl,o as sn,k as ql,u as zt,l
103
103
 
104
104
  identChar = alnum | "_" | "$"
105
105
  }
106
- `;let Gs;function co(){return Gs??=Ll(Qu),Gs}function Pn(e){return co().match(e.trim())}function $n(){return co().createSemantics()}let Yn;function Xu(){if(Yn)return Yn;const e=$n();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,a){return[...t.identifiers(),...i.asIteration().children.flatMap(c=>c.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),Yn=e,e}function Zu(e){const t=Pn(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=Xu()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const ed=new Set(["__proto__","prototype","constructor"]);function L(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(ed.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 J(e){return e.length===0?"/":"/"+e.join("/")}function Ae(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Ae(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Ae(r);return t}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ut(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)=>ut(s,t[i]));if(!Js(e)||!Js(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&ut(e[s],t[s]))}class td{root={};snapshot(){return Ae(this.root)}restore(t){this.root=Ae(t)}read(t){const n=L(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 a=s;if(!Object.hasOwn(a,i))return null;s=a[i]}return Ae(s)}write(t,n){const r=L(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Ae(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let c=0;c<r.length-1;c++){const l=r[c],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 a=r[r.length-1];return n===null?(delete i[a],this.trim(r)):i[a]=Ae(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,a])=>({path:J(L(i)),value:a}));for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){const c=r[i].path,l=r[a].path;if(c===l)throw new Error(`multi-path update: duplicate path '${c}'.`);const u=c==="/"?"/":c+"/",d=l==="/"?"/":l+"/";if(c!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`);if(l!=="/"&&c.startsWith(d))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:a}of r){const c=this.write(i,a);s.push({path:i,prior:c})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const c=[...s,...L(i)],l=J(c),u=this.write(l,a);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 c=0;c<r.length-1;c++){const l=i[r[c]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const a=i[s];if(a!==void 0&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0){delete i[s];continue}return}}}function nd(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class rd{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=>J(L(n)))})}conflictsSince(t,n){const r=J(L(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>nd(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 he(e){return e==="unsupported"?"unsupported":"deny"}function je(e){return J(L(e))}class sd{sandbox;nextId=0;constructor(t){this.sandbox=t}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{Ie(this.sandbox,Cn({service:"rtdb",op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,a={}){if(this.sandbox)try{let c;i&&(c={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let l="user";a.origin&&(l=a.origin),Ie(this.sandbox,Ja({service:"rtdb",method:n,path:je(r),auth:t,result:s,origin:l,durationMs:a.durationMs,reasons:i?.reasons,rules:c,request:a.request,resourceBefore:a.resourceBefore,resourceAfter:a.resourceAfter,groupId:a.groupId,groupKind:a.groupKind,triggeredBy:a.triggeredBy,detail:a.detail,at:a.at}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{Ie(this.sandbox,Fl({service:"rtdb",method:n,path:je(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),Ie(this.sandbox,Vl({service:"rtdb",phase:t,listenerId:n.id,target:{kind:i,path:je(n.path)},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}),{service:"rtdb"})}catch{}}}class id{values=new Map;get(t){return this.values.get(J(L(t)))??null}forChild(t){const n=L(t);return r=>this.get(J([...n,r]))}clear(){this.values.clear()}clearAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n){this.clearAtOrBelow(t),n!==null&&this.values.set(J(L(t)),n)}set(t,n){const r=J(L(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t){for(const n of t){const r=this.get(n.path);this.clearAtOrBelow(n.path),n.value!==null&&r!==null&&this.values.set(J(L(n.path)),r)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(J(L(n)),r)}}function fn(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)")}let He=[],Sr=!1,Er=!1,Cr=!1,Qn;function ad(){if(Qn)return Qn;const e=$n();return e.addOperation("lint",{_nonterminal(...t){t.forEach(n=>n.lint())},_iter(...t){t.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.lint(),i.asIteration().children.forEach(c=>c.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(Cr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(Sr=!0),s==="newData"&&(Er=!0)},bool_true(t){He.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){He.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){He.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){He.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),Qn=e,e}function od(e,t="read"){const n=Pn(e);return n.failed()?[]:(He=[],Sr=!1,Er=!1,Cr=!1,ad()(n).lint(),t==="write"&&Sr&&!Er&&!Cr&&He.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...He])}const cd={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},ld=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),ud=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),dd=new Set([...ld,...ud]);let Rt=[],an="read",lo=new Set,Xn;function fd(){if(Xn)return Xn;const e=$n();return e.addOperation("validate",{_nonterminal(...t){t.forEach(n=>n.validate())},_iter(...t){t.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.validate();const c=r.sourceString;dd.has(c)||Rt.push({code:"UNKNOWN_METHOD",message:`Unknown method '${c}'`}),i.asIteration().children.forEach(l=>l.validate())},CallExpr_memberAccess(t,n,r){t.validate()},CallExpr_indexAccess(t,n,r,s){t.validate(),r.validate()},ident(t,n,r){const s=this.sourceString;if(t.sourceString==="$")return;const a=cd[an];a&&(!a.has(s)&&!lo.has(s)&&Rt.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${an}' context`}),s==="newData"&&an==="read"&&Rt.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),Xn=e,e}function hd(e,t,n=[]){const r=Pn(e);return r.failed()?[]:(Rt=[],an=t,lo=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),fd()(r).validate(),[...Rt])}const pd=new Set(["__proto__","prototype","constructor"]);function Ys(e,t){return pd.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 md(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="\\"||n===e.length-1){t+=r;continue}const s=e[++n];switch(s){case"\\":t+="\\";break;case"'":t+="'";break;case'"':t+='"';break;case"n":t+=`
107
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"b":t+="\b";break;case"f":t+="\f";break;case"/":t+="/";break;default:t+="\\"+s;break}}return t}class be{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(t){return this.child(t).exists()}hasChildren(t){return Array.isArray(t)?t.every(n=>this.hasChild(String(n))):typeof this._value=="object"&&this._value!==null&&Object.keys(this._value).length>0}isString(){return typeof this._value=="string"}isNumber(){return typeof this._value=="number"}isBoolean(){return typeof this._value=="boolean"}child(t){const n=t.split("/").filter(a=>a.length>0);if(n.length===0)return this;let r=this._value;for(const a of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,a)?r[a]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new be(r,i,this._root)}parent(){if(this._path==="/")return null;const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new be(this._root,"/"):new be(this._root,"/").child(t.join("/"))}getPriority(){return null}}class yd{value;constructor(t){this.value=t}matches(t){return(t instanceof RegExp?t:new RegExp(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){if(t instanceof RegExp){const r=t.flags.includes("g")?t.flags:`${t.flags}g`;return this.value.replace(new RegExp(t.source,r),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}}let Ne={auth:null,data:new be(null),newData:new be(null),root:new be(null),now:Date.now(),pathVariableBindings:{}},Zn;function bd(){if(Zn)return Zn;const e=$n();return e.addOperation("eval",{Expr(t){return t.eval()},Ternary_ternary(t,n,r,s,i){return t.eval()?r.eval():i.eval()},Ternary(t){return t.eval()},Logical_and(t,n,r){return t.eval()&&r.eval()},Logical_or(t,n,r){return t.eval()||r.eval()},Logical(t){return t.eval()},Comparison_strictEq(t,n,r){return t.eval()===r.eval()},Comparison_strictNeq(t,n,r){return t.eval()!==r.eval()},Comparison_gte(t,n,r){return t.eval()>=r.eval()},Comparison_lte(t,n,r){return t.eval()<=r.eval()},Comparison_gt(t,n,r){return t.eval()>r.eval()},Comparison_lt(t,n,r){return t.eval()<r.eval()},Comparison_looseEq(t,n,r){return t.eval()==r.eval()},Comparison_looseNeq(t,n,r){return t.eval()!=r.eval()},Comparison(t){return t.eval()},Additive_add(t,n,r){return t.eval()+r.eval()},Additive_sub(t,n,r){return t.eval()-r.eval()},Additive(t){return t.eval()},Multiplicative_mul(t,n,r){return t.eval()*r.eval()},Multiplicative_div(t,n,r){return t.eval()/r.eval()},Multiplicative_mod(t,n,r){return t.eval()%r.eval()},Multiplicative(t){return t.eval()},UnaryExpr_not(t,n){return!n.eval()},UnaryExpr_neg(t,n){return-n.eval()},UnaryExpr(t){return t.eval()},CallExpr_methodCall(t,n,r,s,i,a){const c=t.eval(),l=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(c instanceof be)switch(l){case"val":return c.val();case"exists":return c.exists();case"hasChild":return c.hasChild(String(u[0]));case"hasChildren":return c.hasChildren(u.length>0?u[0]:void 0);case"isString":return c.isString();case"isNumber":return c.isNumber();case"isBoolean":return c.isBoolean();case"child":return c.child(String(u[0]));case"parent":return c.parent();case"getPriority":return c.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof c=="string"){const d=new yd(c);switch(l){case"matches":return d.matches(u[0]);case"contains":return d.contains(String(u[0]));case"beginsWith":return d.beginsWith(String(u[0]));case"endsWith":return d.endsWith(String(u[0]));case"replace":return d.replace(u[0],String(u[1]));case"toLowerCase":return d.toLowerCase();case"toUpperCase":return d.toUpperCase();default:throw new Error(`Unknown string method: ${l}`)}}throw new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:Ys(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:Ys(i,String(a))},CallExpr(t){return t.eval()},Primary_paren(t,n,r){return n.eval()},Primary(t){return t.eval()},Array(t,n,r){return n.asIteration().children.map(s=>s.eval())},literal(t){return t.eval()},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()},string_double(t,n,r){return JSON.parse(this.sourceString)},string_single(t,n,r){return md(n.sourceString)},string(t){return t.eval()},regex(t,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval()},null(t){return null},ident(t,n,r){const s=this.sourceString;if(s in Ne.pathVariableBindings)return Ne.pathVariableBindings[s];switch(s){case"auth":return Ne.auth;case"data":return Ne.data;case"newData":return Ne.newData;case"root":return Ne.root;case"now":return Ne.now;default:return}}}),Zn=e,e}function uo(e,t){const n=Pn(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ne=t,bd()(n).eval()}const gd=sn({operation:Ya(["read","write","validate"]),path:ze().min(1).startsWith("/"),auth:Wl([sn({uid:ze(),token:wr(zt())}),zl()]),mockData:wr(zt()),newData:zt().optional(),updates:ql(sn({path:ze().min(1).startsWith("/"),value:zt()})).optional()});Ya(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);sn({allowed:Ls(),unsupported:Ls().optional(),matchedPath:ze(),matchedRule:ze(),reason:ze(),pathVariableBindings:wr(ze())});function er(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function Nr(e){return e.validate?!0:e.children.some(Nr)}function Qs(e,t,n){return e.length>0||t||n.some(r=>r.length===1)}function vd(e,t,n,r,s,i,a){let c=null;const l=new Set;if(a&&a.length>0)for(const f of a)l.add(f.path.split("/").filter(Boolean).join("/"));l.add(i.filter(Boolean).join("/"));const u=Array.from(l).map(f=>f.split("/").filter(Boolean));function d(f,p,y,b,v,g){if(y.exists()){const _=f.validate;if(_){if(!_.parsed.valid)c||(c={node:f,rule:_,bindings:b,unsupported:!0});else if(!uo(_.raw,s(p,y,b)))return{node:f,rule:_,bindings:b}}}const w=u.some(_=>_.length<=v.length&&_.every((j,k)=>j===v[k])),x=er(p).some(_=>!y.child(_).exists());for(const _ of f.children){const j=_.path.split("/").filter(Boolean);if(j.length===0)continue;const k=j[j.length-1],N=k.startsWith("$");if(w||g){if(N)for(const A of er(y)){const R=d(_,p.child(A),y.child(A),{...b,[k]:A},[...v,A],!0);if(R)return R}else if(y.child(k).exists()){const A=d(_,p.child(k),y.child(k),b,[...v,k],!0);if(A)return A}}else if(N){const A=new Set;for(const R of u)R.length>v.length&&v.every((I,C)=>I===R[C])&&A.add(R[v.length]);for(const R of A){const I=d(_,p.child(R),y.child(R),{...b,[k]:R},[...v,R],!1);if(I)return I}if(Nr(_)&&Qs(v,x,u))for(const R of er(y)){if(A.has(R))continue;const I=d(_,p.child(R),y.child(R),{...b,[k]:R},[...v,R],!0);if(I)return I}}else{const A=k;if(u.some(I=>I.length>v.length&&I[v.length]===A&&v.every((C,S)=>C===I[S]))){const I=d(_,p.child(A),y.child(A),b,[...v,A],!1);if(I)return I}else if(y.child(A).exists()&&Nr(_)&&Qs(v,x,u)){const I=d(_,p.child(A),y.child(A),b,[...v,A],!0);if(I)return I}}}return null}return d(e,t,n,r,[],!1)??c}function fo(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;for(const i of e.children){const a=i.path.split("/").filter(Boolean);if(a.length===0)continue;const c=a[a.length-1],l=c.startsWith("$");if(l||t[0]===c){const u=l?{...n,[c]:t[0]}:{...n},d=fo(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function Rr(e,t,n){if(t.length===0)return n??null;const[r,...s]=t,i=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},a=Object.hasOwn(i,r)?i[r]:null,c=Rr(a,s,n);return c==null?delete i[r]:i[r]=c,i}function wd(e,t,n,r){if(!r||r.length===0)return Rr(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=Rr(s,a,i.value??null)}return s}class xd{execute(t,n){const r=gd.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:i,auth:a,mockData:c,newData:l,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),m=t,f=fo(m,d,{}),p=new be(c,"/"),y=s==="read"?c:wd(c,d,l,u),b=new be(y,"/"),v=(_,j,k)=>{const N={};for(const[A,R]of Object.entries(k))N[A]=R,N[A.slice(1)]=R;return{auth:a?{uid:a.uid,token:a.token}:null,data:_,newData:j,root:p,now:Date.now(),pathVariableBindings:N}};let g;for(const _ of f){const j=_.node[s];if(!j)continue;if(!j.parsed.valid){g||(g=_);continue}const k=d.slice(0,_.depth).join("/"),N=p.child(k),A=b.child(k);if(uo(j.raw,v(N,A,_.pathVariableBindings))){if(s==="write"){const I=vd(m,p,b,{},v,d,u);if(I)return{success:!0,data:{allowed:!1,unsupported:I.unsupported===!0,matchedPath:I.node.path,matchedRule:I.rule.raw,reason:I.unsupported?`Validation rule at '${I.node.path}' contains an expression the simulator cannot evaluate: ${I.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:I.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:_.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:_.pathVariableBindings}}}}if(g){const _=g.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:g.node.path,matchedRule:_.raw,reason:`'${s}' rule at '${g.node.path}' contains an expression the simulator cannot evaluate: ${_.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:g.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const jd=new Set([".read",".write",".validate",".indexOn"]);function ho(e,t,n=[]){const r=Zu(e),s=r.valid?hd(e,t,n):r.errors,i=r.valid?od(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function po(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const c=e[i];c!==void 0&&(r[a]=ho(String(c),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(jd.has(i)||typeof a!="object"||a===null)continue;const c=t==="/"?`/${i}`:`${t}/${i}`,l=i.startsWith("$")?[...n,i]:[...n];r.children.push(po(a,c,l))}return r}function mo(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)throw new Error('Invalid rules JSON: "rules" must be an object');return po(t.rules,"/",[])}function tr(e){return e==="true"?!0:e==="false"?!1:e}function yo(e){const t={};e.read&&(t[".read"]=tr(e.read.raw)),e.write&&(t[".write"]=tr(e.write.raw)),e.validate&&(t[".validate"]=tr(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]]=yo(n)}return t}function _d(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:yo(e)}}function fs(e,t){return new xd().execute(e,t)}function we(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class kd{compiled=null;defaultPolicy="deny";setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=mo(t)}hasRules(){return this.compiled!==null}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."]};const i=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},a=fs(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates});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}:{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}:a.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class Sd{tree=new td;rules=new kd;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new id;mutations=new rd;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new sd(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function hs(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=Xs(e),r=Xs(t);return n!==r?n-r:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===t?0:e?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function Xs(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const Ed=/^-?(0*)\d{1,10}$/,Cd=-2147483648,Nd=2147483647;function Zs(e){if(Ed.test(e)){const t=Number(e);if(t>=Cd&&t<=Nd)return t}return null}function hn(e,t){if(e===t)return 0;const n=Zs(e),r=Zs(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function It(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 i=s.path.split("/").filter(c=>c.length>0);let a=n;for(const c of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[c]??null}return a}}}function Je(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,c])=>({key:a,value:c,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,c)=>{if(i)return hn(a.key,c.key);const l=It(t.orderBy,a.key,a.value,a.priority),u=It(t.orderBy,c.key,c.value,c.priority),d=hs(l,u);return d!==0?d:hn(a.key,c.key)});for(const a of t.bounds)s=s.filter(c=>Rd(a,c,t.orderBy));if(t.limit){const a=t.limit.n;t.limit.kind==="limitToFirst"?s=s.slice(0,a):s=a>=s.length?s:s.slice(s.length-a)}return s}function Rd(e,t,n){const s=n?.kind==="key"?hn(t.key,String(e.value)):hs(It(n,t.key,t.value,t.priority),e.value),i=a=>hn(t.key,a);switch(e.kind){case"startAt":return s>0?!0:s<0?!1:e.key===void 0||i(e.key)>=0;case"startAfter":return s>0?!0:s<0||e.key===void 0?!1:i(e.key)>0;case"endAt":return s<0?!0:s>0?!1:e.key===void 0||i(e.key)<=0;case"endBefore":return s<0?!0:s>0||e.key===void 0?!1:i(e.key)<0;case"equalTo":return s!==0?!1:e.key===void 0||i(e.key)===0}}function ei(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Ad(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&ut(n.value,s.value)})}function ps(e){const t=new Error(`permission_denied at ${J(L(e))}: Client doesn't have permission to access the desired data.`);return t.code="PERMISSION_DENIED",t}class Id{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const c=Date.now(),l=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(l.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,he(l.check),l,{at:c,durationMs:Date.now()-c,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:l.matchedPath,matchedRule:l.matchedRule,pathVariableBindings:l.pathVariableBindings,reason:l.reason,errorCode:l.errorCode};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:l.reasons},reasons:l.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(ps(n))}),()=>{};throw we()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:l,at:c},i,a)}adminOnValue(t,n,r){return this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attach(t,n,r,s,i,a,c){const l=this.state.events.nextListenerId();this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:Date.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const u={id:l,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:c};if(this.state.valueListeners.add(u),this.state.events.listener("attach",u,t,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const d=Je(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:ei(d),exists:d.length>0,key:this.key(n),rows:d},{initial:!0,query:!0})}else{const d=this.snapshot(n);u.lastValue=d.val,u.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(u,d,{initial:!0})}return()=>{this.state.valueListeners.delete(u),this.state.events.listener("detach",u,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>J(L(r)));for(const r of this.state.valueListeners){const s=J(L(r.path));if(!n.some(c=>Dd(s,c)))continue;if(r.query){const c=Je(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Ad(r.lastWindow??[],c)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=c,this.deliver(r,{val:ei(c),exists:c.length>0,key:this.key(r.path),rows:c},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(ut(r.lastValue??null,i.val)&&r.lastPriorityState===a){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=a,this.deliver(r,i,{})}}off(t,n){const r=J(L(t));for(const s of[...this.state.valueListeners])J(L(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=L(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r});try{t.cb(n)}catch(s){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){try{t.cb(n),this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r})}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function Dd(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function et(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function xt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function ti(e,t){if(t===void 0)return null;const n=L(e),r=L(t);return r.length!==n.length+1||!n.every((s,i)=>r[i]===s)?null:r[r.length-1]??null}class Pd{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,c){const l=Date.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.tree.snapshot()});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,he(d.check),d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const f={engine:"rtdb",matchedPath:d.matchedPath,matchedRule:d.matchedRule,pathVariableBindings:d.pathVariableBindings,reason:d.reason,errorCode:d.errorCode};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:f}),a)return queueMicrotask(()=>{c&&c(),a(ps(r))}),()=>{};throw we()}this.state.events.operation(t,"listen",r,"allow",d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const m={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:c};if(this.state.childListeners.add(m),this.state.events.listener("attach",m,t,{event:n,result:"allow",detail:i?{query:i}:void 0}),i){const f=Je(this.state.tree.read(r),i,this.state.priorities.forChild(r));if(m.lastWindow=f,n==="child_added")for(const{key:p,value:y}of f)this.deliver(m,{key:p,val:y,previousChildName:et(f,p)},{initial:!0,query:!0})}else if(n==="child_added")for(const{key:f,val:p}of this.directChildren(r)){const y=this.directChildren(r);this.deliver(m,{key:f,val:p,previousChildName:xt(y,f)},{initial:!0})}return()=>{this.state.childListeners.delete(m),this.state.events.listener("detach",m,t,{event:n})}}off(t,n,r){const s=J(L(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||J(L(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=J(L(n.path));t.has(r)||t.set(r,new Map(this.directChildren(r).map(({key:s,val:i})=>[s,i])))}return t}fanOut(t,n){if(this.state.childListeners.size===0)return;const r=new Map;for(const s of this.state.childListeners){if(s.spec){this.fanOutQuery(s,n);continue}const i=J(L(s.path)),a=r.get(i)??[];a.push(s),r.set(i,a)}for(const[s,i]of r){const a=t.get(s)??new Map,c=new Map(this.directChildren(s).map(({key:f,val:p})=>[f,p])),l=[...c].map(([f,p])=>({key:f,val:p})),u=[...a].map(([f,p])=>({key:f,val:p})),d={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,p]of c)a.has(f)?ut(a.get(f),p)||d.child_changed.push({key:f,val:p,previousChildName:xt(l,f)}):d.child_added.push({key:f,val:p,previousChildName:xt(l,f)});for(const[f,p]of a)c.has(f)||d.child_removed.push({key:f,val:p,previousChildName:xt(u,f)});const m=ti(s,n);m!==null&&a.has(m)&&c.has(m)&&d.child_moved.push({key:m,val:c.get(m),previousChildName:xt(l,m)});for(const f of i)for(const p of d[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)?[]:Je(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}fanOutQuery(t,n){const r=t.lastWindow??[],s=Je(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(l=>[l.key,l.value])),a=new Map(s.map(l=>[l.key,l.value])),c=[];if(t.event==="child_added")for(const l of s)i.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:et(s,l.key)});else if(t.event==="child_changed")for(const l of s)i.has(l.key)&&!ut(i.get(l.key),l.value)&&c.push({key:l.key,val:l.value,previousChildName:et(s,l.key)});else if(t.event==="child_removed")for(const l of r)a.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:et(r,l.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=t.spec.orderBy.kind==="priority"?ti(t.path,n):null;let u=!1;if(l!==null){const d=s.find(m=>m.key===l);d&&i.has(l)&&(c.push({key:d.key,val:d.value,previousChildName:et(s,d.key)}),u=!0)}if(!u){const d=new Map(r.map(m=>[m.key,m]));for(const m of s){const f=d.get(m.key);if(!f)continue;const p=It(t.spec.orderBy,f.key,f.value,f.priority),y=It(t.spec.orderBy,m.key,m.value,m.priority);hs(p,y)!==0&&c.push({key:m.key,val:m.value,previousChildName:et(s,m.key)})}}}for(const l of c)this.deliver(t,l,{query:!0})}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:n,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function $d(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,a="data"in r;let c=!1;i&&a&&(c=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let m=!1;if(u&&d){const p=typeof l=="object",y=Array.isArray(l);p&&(y||(m=!0))}let f=!1;if(c&&m&&(f=!0),f){const p={},y=Object.entries(l);for(const[j,k]of y){const N=typeof k=="string",A=typeof k=="number";let R=!1;A&&Number.isFinite(k)&&(R=!0);let I=!1;N&&(I=!0),R&&(I=!0),I&&(p[j]=k)}const b=r.data;let v=null;b!==void 0&&b!==null&&(v=b);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const k=typeof w=="object",N=Array.isArray(w);let A=!1;if(k&&(N||(A=!0)),A){const R=w;if("rules"in R){const C=R.rules;if(C!==null&&C!==void 0){const D=typeof C=="object",V=Array.isArray(C);let G=!1;D&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:p,rules:x}}}return{data:e,priorities:{},rules:null}}class Od{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=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=$d(t);let s={};const i=r.data===null,a=r.data===void 0;let c=!1;i||a||(c=!0),c&&(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.values.fanOut(["/"]),this.children.fanOut(n)}reset(){this.state.resetGeneration+=1,this.restore(null)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const ni="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let ri=0;const Be=new Array(12).fill(0);function Td(e=Date.now()){const t=e===ri;ri=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=ni.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&&Be[i]===63;i--)Be[i]=0;if(i<0)for(let a=0;a<12;a++)Be[a]=Math.floor(Math.random()*64);else Be[i]=(Be[i]??0)+1}else for(let i=0;i<12;i++)Be[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ni.charAt(Be[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}const Md=/[\[\].#$/\u0000-\u001F\u007F]/;function Ud(e){return e.length!==0&&!Md.test(e)}function Bd(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Ld(e){return e===".priority"||e===".value"||e===".sv"}function Fd(e,t){Ar(e,t,"set")}function Ar(e,t,n){if(e===void 0)throw new Error(`${n} failed: value argument contains undefined in property '${t}'`);if(typeof e=="function")throw new Error(`${n} failed: value argument contains a function in property '${t}'`);if(Bd(e))throw new Error(`${n} failed: value argument contains ${String(e)} in property '${t}'`);if(!(e===null||typeof e!="object")){if(Array.isArray(e)){for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=e[r];s!==void 0&&Ar(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Ld(r)&&!Ud(r))throw new Error(`${n} failed: value argument contains an invalid key (${r}) in path ${t}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);Ar(s,`${t}/${r}`,n)}}}function Ve(e,t){return Fd(e,t),Ir(e)}function Ir(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=Ir(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const t={};for(const[n,r]of Object.entries(e)){if(n===".sv"){t[n]=r;continue}const s=Ir(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function on(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>on(a));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const a of n)if(/^(0|[1-9]\d*)$/.test(a))s=Math.max(s,Number(a));else{r=!1;break}if(r&&s<2*n.length){const a=[];for(let c=0;c<=s;c++){const l=t[String(c)];a[c]=l===void 0?null:on(l)}return a}const i={};for(const[a,c]of Object.entries(t))i[a]=on(c);return i}function Vd(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function qd(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function xe(e,t,n){if(Vd(e))return t;if(qd(e)){const i=e[".sv"].increment;return(typeof n=="number"?n:0)+i}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((i,a)=>xe(i,t,Array.isArray(n)?n[a]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[i,a]of Object.entries(e))s[i]=xe(a,t,r?r[i]:void 0);return s}function si(){return new Error("permission_denied")}class Wd{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}run(t,n,r,s){const i=s?.applyLocally!==!1,a=L(n),c=a.length===0?null:a[a.length-1];let l=null,u,d=0,m=!1;do{d+=1;const x=this.state.mutations.begin();l=this.state.tree.read(n);const _=l===null?null:on(Ae(l));let j=!1;try{u=r(_),j=this.state.mutations.conflictsSince(x,n)}finally{this.state.mutations.release(x)}if(!j||u===void 0){m=!0;break}}while(d<25);if(!m)throw new Error("maxretry");const f=this.state.events.nextGroupId("transaction");if(u===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:f,groupKind:"transaction",resourceBefore:{data:l,exists:l!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:l,key:c};const p=Date.now(),y=Ve(xe(u,p,l),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),_=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),k=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(k);const N=Date.now(),A=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(A.check!=="allow"){this.state.events.operation(t,"transaction",n,he(A.check),A,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const R=this.children.snapshotParents();throw this.state.tree.restore(x),this.state.priorities.restore(_),this.values.fanOut([n]),this.children.fanOut(R),si()}return this.recordCommit(t,n,u,l,y,f,p,N,!0,A),{committed:!0,val:y,key:c}}const b=Date.now(),v=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:y});if(v.check!=="allow")throw this.state.events.operation(t,"transaction",n,he(v.check),v,{at:b,durationMs:Date.now()-b,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),si();this.state.events.operation(t,"transaction",n,"allow",v,{at:b,durationMs:Date.now()-b,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const g=this.state.priorities.get(n),w=this.children.snapshotParents();return this.state.tree.write(n,y),this.state.priorities.replace(n,g),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(w),this.finishEvents(t,n,u,l,y,f,p,!1),this.state.notifyWrite(),{committed:!0,val:y,key:c}}recordCommit(t,n,r,s,i,a,c,l,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:l,durationMs:Date.now()-l,origin:"transaction",request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:a,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,a,c,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,c,l){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:c},detail:{committed:!0,applyLocally:l}}),this.state.events.mutation(t,"transaction",je(n),{before:s,after:i,detail:{committed:!0}})}}class zd{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(fn(n),this.state.tree.read(t)===null)return;const r=this.children.snapshotParents(),s=this.state.priorities.get(t)!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),s&&this.values.fanOut([t]),this.children.fanOut(r,s?t:void 0),this.state.notifyWrite()}set(t,n,r){fn(r);const s=this.state.tree.read(n),i=Date.now(),a=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:s}),c=this.state.priorities.get(n),l={at:i,durationMs:Date.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:c}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,he(a.check),a,l),we();if(this.state.events.operation(t,"setPriority",n,"allow",a,l),s===null)return;const u=this.children.snapshotParents(),d=c!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u,d?n:void 0),d&&(this.state.events.commit(t,"setPriority",n,{data:r,priorState:c,nextState:r,detail:{priority:r,priorPriority:c}}),this.state.events.mutation(t,"setPriority",je(n),{before:c,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function ii(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class Kd{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new zd(t,n,r)}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t))this.state.tree.write(n,Ve(xe(r,Date.now()),n==="/"?"":n));this.state.mutations.mark("/"),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,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=Je(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:ii(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){fn(r);const i=Date.now(),a=this.state.tree.read(t),c=Ve(xe(n,i,a),t==="/"?"":t),l=c===null?"remove":"set";this.state.events.operation(null,l,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:c,exists:c!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),m=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,c),this.state.priorities.replace(t,c===null?null:r);const f=m!==this.state.priorities.stateAtOrBelow(t);this.changed([t],u,f?t:void 0);const p=this.state.tree.read(t);this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:a,nextState:p,replay:{requestTime:i},detail:s?{admin:!0,priority:r,priorPriority:d}:{admin:!0}}),this.state.notifyWrite()}adminUpdate(t,n){const r=Date.now(),s=this.state.tree.read(t),i=this.resolvePatch(t,n,r),a=Object.keys(n).some(u=>u.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const c=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(i).map(([u,d])=>[L(u).at(-1),d]))),this.state.priorities.applyUpdate(Object.entries(i).map(([u,d])=>({path:u,value:d}))),this.changed(Object.keys(i),c);const l=a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:l}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=Date.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),we();return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=Date.now(),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:s,durationMs:Date.now()-s,request:{query:r}}),we();const a=Je(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:ii(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){fn(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)}validateSet(t,n,r){const s=Ve(xe(r,Date.now(),this.state.tree.read(n)),n==="/"?"":n);if(this.writeEvaluation(t,n,s).check!=="allow")throw we()}validateUpdate(t,n,r){const s=this.state.tree.snapshot(),i=Object.entries(r).map(([a,c])=>{const l=J([...L(n),...L(a)]);return{path:l,value:Ve(xe(c,Date.now(),this.state.tree.read(l)),l)}});for(const a of i)if(this.state.rules.evaluate("write",a.path,{auth:t,mockData:s,newData:a.value,updates:i}).check!=="allow")throw we()}update(t,n,r){const s=Date.now(),i=this.resolvePatch(n,r,s),a=Object.keys(r).some(y=>y.includes("/")),c=this.state.tree.snapshot(),l=Object.entries(i).map(([y,b])=>({path:y,value:b})),u=Object.fromEntries(Object.entries(i).map(([y,b])=>[L(y).at(-1),b])),d=this.state.events.nextGroupId("update");for(const y of l){const b=Date.now(),v=this.state.tree.read(y.path),g=this.state.rules.evaluate("write",y.path,{auth:t,mockData:c,newData:y.value,updates:l}),w={at:b,durationMs:Date.now()-b,origin:"batch",request:{data:y.value,resourceData:y.value},resourceBefore:{data:v,exists:v!==null},resourceAfter:{data:y.value,exists:y.value!==null},groupId:d,groupKind:"batch",detail:a?{multiPath:!0,rootPath:je(n)}:{multiPath:!1,rootPath:je(n),key:L(y.path).at(-1)}};if(g.check!=="allow")throw this.state.events.operation(t,"update",y.path,he(g.check),g,w),we();this.state.events.operation(t,"update",y.path,"allow",g,w)}const m=this.state.tree.read(n),f=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,u),this.state.priorities.applyUpdate(l),this.changed(Object.keys(i),f);const p=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:p,groupId:d,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.events.mutation(t,"update",je(n),{after:a?i:u,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,a){const c=Date.now(),l=Ve(xe(r,c,this.state.tree.read(n)),n==="/"?"":n),u=this.state.tree.read(n),d=this.state.priorities.get(n),m=Date.now(),f=this.writeEvaluation(t,n,l),p={at:m,durationMs:Date.now()-m,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:l,exists:l!==null}};if(f.check!=="allow")throw this.state.events.operation(t,s,n,he(f.check),f,p),we();this.state.events.operation(t,s,n,"allow",f,p);const y=this.children.snapshotParents(),b=this.state.priorities.stateAtOrBelow(n);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i);const v=b!==this.state.priorities.stateAtOrBelow(n);this.changed([n],y,v?n:void 0);const g=this.state.tree.read(n),w=g===null?"remove":s;this.state.events.commit(t,w,n,{data:r,priorState:u,nextState:g,replay:{requestTime:c},...a?{detail:{priority:i,priorPriority:d}}:{}}),this.state.events.mutation(t,w,je(n),{before:u,after:g}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const a=J([...L(t),...L(s)]);return[a,Ve(xe(i,r,this.state.tree.read(a)),a)]}))}changed(t,n,r){this.state.mutations.mark(t),this.values.fanOut(t),this.children.fanOut(n,r)}cancelDeniedListeners(){const t=this.state.tree.snapshot(),n=[];for(const s of[...this.state.valueListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.valueListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener"});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),n.push(s)}const r=[];for(const s of[...this.state.childListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.childListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener",detail:{event:s.event}});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:s.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),r.push(s)}for(const s of[...n,...r]){try{s.onCanceled&&s.onCanceled()}catch{}try{s.cancelCallback&&s.cancelCallback(ps(s.path))}catch{}}}readEvaluation(t,n){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()})}writeEvaluation(t,n,r){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:r})}}class Hd{state;values;children;writes;transactions;persistence;constructor(t){this.state=new Sd(t),this.values=new Id(this.state),this.children=new Pd(this.state),this.writes=new Kd(this.state,this.values,this.children),this.transactions=new Wd(this.state,this.values,this.children),this.persistence=new Od(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){this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){this.writes.adminUpdate(t,n)}adminRemove(t){this.writes.adminRemove(t)}adminSetPriority(t,n){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)}set(t,n,r){this.writes.set(t,n,r)}setWithPriority(t,n,r,s){this.writes.setWithPriority(t,n,r,s)}update(t,n,r){this.writes.update(t,n,r)}remove(t,n){this.writes.remove(t,n)}setPriority(t,n,r){this.writes.setPriority(t,n,r)}validateSet(t,n,r){this.writes.validateSet(t,n,r)}validateUpdate(t,n,r){this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,a){return this.values.onValue(t,n,r,s,i,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,a,c){return this.children.onChild(t,n,r,s,i,a,c)}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(){this.persistence.reset()}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return Td()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const ai=new WeakMap;function Gd(e){let t=ai.get(e);if(t)return t;t=new Hd(e),ai.set(e,t);const n=t;return e.onEvent(r=>{r.kind==="session_boundary"&&r.phase==="reset"&&n.invalidateConnectionQueues()}),e.registerPersistableService("rtdb",{snapshot:()=>n.exportPersistenceState(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.resetTree()}}),t}const Dr=Symbol("pyric/database/target"),Jd=new WeakMap;function Yd(e){let t;if(Dr in e?t=e[Dr]:t=Jd.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}function bo(e){return e&&typeof e=="object"&&Dr in e?Yd(e).backend:Gd(e)}function go(e){return bo(e).getActiveRules()}function oi(e){return bo(e).snapshotState()}const ci=Symbol("pyric/firestore/followsCurrentUser"),li=Symbol("pyric/firestore/authSessionScope"),vo=new WeakMap;function Qd(e){return vo.get(e)?.raw??e}const Xd=new WeakMap,ui=new WeakMap;function Pr(e,t,n,r,s){vo.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function Zd(e,t){const n=xr(e),r=xr(t);return n.isStructurallyEqual?.(r)??n===r}function ef(e,t,n,r){const s=e,i=(ui.get(s)??[]).filter(c=>c.query.deref()!==void 0),a=i.find(c=>{const l=c.query.deref();return l!==void 0&&Zd(l,t)});if(a!==void 0){const c=tf(a.docs,n)&&a.metadata.fromCache===r.fromCache&&a.metadata.hasPendingWrites===r.hasPendingWrites;return a.docs=n,a.metadata=r,c?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),ui.set(s,i),"initial"}function tf(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&uu(n.data,s.data)})}function $r(e,t,n,r,s){const i=t,a=d=>({path:d.ref?.path??"",data:ds(d.data?.(),n)}),c=Object.freeze((i.docs??[]).map(a)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...a(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});Xd.set(e,{target:n,query:r,converter:Rn(r)??null,source:s,...s==="read"?{readPhase:ef(n,r,c,u)}:{},metadata:u,docs:c,changes:l})}function pn(e,t){const n=e,r=n.data.bind(e);return Object.defineProperty(n,"data",{value:()=>to(r()),configurable:!0,writable:!0}),t&&n.ref?.path&&Object.defineProperty(n,"metadata",{value:Pe(t).snapshotMetadata(n.ref.path),configurable:!0}),e}function wo(e,t,n,r){const s={id:e.id,ref:e.ref,exists:e.exists,metadata:Pe(n).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const a=to(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:Pe(n).snapshotMetadata(e.ref.path),data:()=>a};return t.fromFirestore(c)}};return Ke(s,n),Ke(e.ref,n),Or(e.ref,n),Pr(s,e,n,t,r),s}function On(e,t){if(!e||typeof e!="object")return e;Ke(e,t);const n=e;if(n.ref&&(Ke(n.ref,t),Or(n.ref,t)),di(n),Array.isArray(n.docs))for(const r of n.docs)r&&(Ke(r,t),Pr(r,r,t,null,"query-child")),r?.ref&&(Ke(r.ref,t),Or(r.ref,t)),r&&di(r);else n.ref&&Pr(e,e,t,null,"document");return e}function Or(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Vs.get(e),s=r??us(t).doc(n);r===void 0&&Vs.set(e,s),Kl(e,n,t,s),t.kind==="sandbox-live"&&no.set(s,i=>i.doc(n))}catch{}}function di(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{}}async function xo(e){const t=An(e),n=Pe(t);n.markStarted();const r=Rn(e),s=await fu(t,e).get();return n.cachePath(e.path),r?wo(s,r,t,"document"):(On(s,t),pn(s,t))}async function mn(e){const t=An(e),n=Pe(t);n.markStarted();const r=Rn(e),s=await du(t,e).get();if(n.cacheQuery(e),r){const a=r,c=s.docs.map(u=>wo(u,a,t,"query-child")),l=Ke({size:c.length,empty:c.length===0,docs:c,metadata:n.querySnapshotMetadata()},t);for(const u of c)n.cachePath(u.ref.path);return $r(l,s,t,e,"read"),l}On(s,t);const i=s.docs;for(const a of i)n.cachePath(a.ref.path),pn(a,t);return Object.defineProperty(s,"metadata",{value:n.querySnapshotMetadata(),configurable:!0}),$r(s,s,t,e,"read"),s}function jo(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function yn(e,...t){const n=An(e),r=Rn(e),s=hu(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw qs(u)}const c=u=>{let d=s(u);for(const m of i)d=m.applySandbox(d);return d};try{a=c(us(n))}catch(u){throw qs(u)}const l=pu(a,n,u=>c(u));return r?mu(l,n,r):l}function nf(e,t,n){return _o(jo(e),t,n,!1)}function _o(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=ds(n,i,t==="in"||t==="not-in");return _o(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function fi(e,t){const n=jo(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function bn(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function rf(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 sf(...e){return rf(e)?ko(e[0],!1,!0):So(e,!1,!0)}function ko(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=Qd(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return ko(a,t,n,!0)}}}function So(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=>So(e.map(i=>ds(i,s).executionValue),t,n,!0)}}function af(e,t,n,r){const s=An(e);Pe(s).markStarted();const i=cf(s,e),a=lf(t,n,r,s,e),c=uf(a,s),l=c.length===3?i.onSnapshot(c[0],c[1],c[2]):c.length===2?i.onSnapshot(c[0],c[1]):i.onSnapshot(c[0]);if(!s.own)return l;let u=!1;const d=()=>{u||(u=!0,l())},m=()=>{u||(d(),of(c)?.(new mt("aborted","The operation was aborted.")))},f=s.own(m);return()=>{f(),d()}}function of(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 cf(e,t){const n=xr(t);if(e.kind==="sandbox")return n;const r=no.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(us(e))}function Eo(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 lf(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!Eo(e)){const a=t;return typeof a=="function"?[e,hi(a,r,s),n??Tr]:a&&typeof a=="object"?[e,pi(a,r,s)]:[e]}return typeof e=="function"?[hi(e,r,s),t??Tr]:e&&typeof e=="object"?[pi(e,r,s)]:[e]}function uf(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Eo(n)?[{...n,[ci]:!0,...t.authScope?{[li]:t.authScope}:{}},...e.slice(1)]:[{[ci]:!0,...t.authScope?{[li]:t.authScope}:{}},...e]}function Co(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&pn(e,t),Array.isArray(r.docs)){for(const s of r.docs)pn(s,t);$r(e,e,t,n,"listener")}return e}function Tr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function hi(e,t,n){return r=>{e(Co(On(r,t),t,n)),Pe(t).notifySnapshotDelivered()}}function pi(e,t,n){return{...e,next:e.next?r=>{e.next(Co(On(r,t),t,n)),Pe(t).notifySnapshotDelivered()}:void 0,error:e.error??Tr}}const Ce={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"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},df=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],ff={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...df]},value:{}},required:["field","op","value"]};function hf(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:Ce},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=We(s,r.path),a=await xo(i),c=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:c?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:c,data:c?a.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:Ce},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=Nt(s,r.collection),a=[];r.orderBy&&a.push(fi(r.orderBy)),r.limit&&a.push(bn(r.limit));const c=await mn(yn(i,...a));return{ok:!0,summary:`${c.size} docs in ${r.collection}`,data:{docs:c.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:Ce},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await ln(We(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:Ce},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await ro(Nt(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:Ce},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Ws(We(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:Ce},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await jr(We(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:Ce},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 a=We(s,i.path);i.op==="set"?await ln(a,i.data??{}):i.op==="update"?await Ws(a,i.data??{}):await jr(a)}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:ff,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ce},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=Nt(s,r.collection),a=r.where.map(l=>nf(l.field,l.op,l.value));r.orderBy&&a.push(fi(r.orderBy)),r.limit&&a.push(bn(r.limit));const c=await mn(yn(i,...a));return{ok:!0,summary:`${c.size} matches in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function pf(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=Hl(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 mf="modulepreload",yf=function(e){return"/__pyric/ui/"+e},mi={},No=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");s=a(n.map(u=>{if(u=yf(u),u in mi)return;mi[u]=!0;const d=u.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":mf,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,y)=>{f.addEventListener("load",p),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function Ro(e){return e.kind==="session_boundary"&&e.phase==="reset"}function bf(e,t){return Ro(t)?[t]:[...e,t]}const Ao=h.createContext(null),Io={status:"disabled",handles:null,events:[]};function gf({children:e}){return o.jsx(Ao.Provider,{value:Io,children:e})}function Te(){return h.useContext(Ao)??Io}function qe(e,t){return`${e.replace(/\/$/,"")}${t}`}const nr=new Map;let rr=null;function vf(e){return e||(rr||(rr=`studio-writer-${Math.random().toString(36).slice(2)}`),rr)}function Do(e){return{token:e?.token,writerId:e?.writerId}}async function Po(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=nr.get(n);if(r)return r;const s=fetch(qe(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||nr.delete(n),i));return nr.set(n,s),s}async function $o(e,t,n=!1){const r={},{token:s,writerId:i}=Do(t);n&&(r["x-pyric-writer"]=vf(i));const a=await Po(e,s);return a&&(r["x-pyric-session-token"]=a),r}function wf(e,t){const n=e,{token:r}=Do(t),s=(i=!1)=>$o(n,t,i);return{async read(i){const a=await s(!1),c=await fetch(qe(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:a});if(c.status===404)return null;if(!c.ok)throw new Error(`workspace.read(${i}) → ${c.status}`);return c.text()},async write(i,a){const c=await s(!0),l=await fetch(qe(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:c,body:a});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const a=await s(!1),c=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch(qe(n,`/__pyric/workspace/list${c}`),{headers:a});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async remove(i){const a=await s(!0),c=await fetch(qe(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:a});if(!c.ok)throw new Error(`workspace.remove(${i}) → ${c.status}`)},watch(i){let a=null,c=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Po(n,r).then(u=>{if(c)return;const d=u?qe(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):qe(n,"/__pyric/workspace/watch");a=new EventSource(d),a.addEventListener("change",l)}),()=>{c=!0,a&&(a.removeEventListener("change",l),a.close())}}}}function jt(e,t){return`${e.replace(/\/$/,"")}${t}`}function xf(e,t){const n=e,r=(s=!1)=>$o(n,t,s);return{async list(){const s=await r(!1),i=await fetch(jt(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),a=await fetch(jt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!a.ok)throw new Error(`projects.open(${s}) → ${a.status}`);return{meta:await a.json(),workspace:wf(n,t)}},async create(s){const a={...await r(!0),"content-type":"application/json"},c=await fetch(jt(n,"/__pyric/projects"),{method:"POST",headers:a,body:JSON.stringify(s)});if(!c.ok)throw new Error(`projects.create() → ${c.status}`);return await c.json()},async update(s,i){const c={...await r(!0),"content-type":"application/json"},l=await fetch(jt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:c,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),a=await fetch(jt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!a.ok)throw new Error(`projects.remove(${s}) → ${a.status}`)}}}function jf(e,t){return`${e.replace(/\/$/,"")}${t}`}function sr(e){return/auth/i.test(e)?"auth":"firestore"}function _f(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=l=>jf(t,`/__pyric/state?section=${sr(l)}`),a=async l=>{const u=sr(l),d=s.get(u);if(d)return d;const m=await fetch(i(l));let f=new Map;if(m.ok){const p=await m.text();p&&p!=="null"&&(f=Gl(p))}else if(m.status!==404)throw new Error(`persistence.read(${l}) → ${m.status}`);return s.set(u,f),f},c=async(l,u)=>{const d=await fetch(i(l),{method:"POST",headers:r,body:Jl(u)});if(d.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!d.ok)throw new Error(`persistence.write(${l}) → ${d.status}`)};return{async getRecord(l,u){return(await a(l)).get(u)??null},async listRecords(l){return[...(await a(l)).keys()]},async putRecords(l,u){const d=await a(l);for(const[m,f]of u)d.set(m,f);await c(l,d)},async deleteRecords(l,u){const d=await a(l);for(const m of u)d.delete(m);await c(l,d)},async clear(l){s.set(sr(l),new Map);const u=await fetch(i(l),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${l}) → ${u.status}`)}}}const kf="local";function Sf(){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 a of e.keys())s&&!a.startsWith(s)||i.push({path:a,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},watch(r){return t.add(r),()=>t.delete(r)}}}function Ef(){const e=Sf();let t={id:kf,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(){}}}const Cf="/__pyric/sdk/worker.js",Re="pyric-shared-worker",Nf="/__pyric/ui/studio";function Oo(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:Nf,worker:{url:Cf,name:Re,servedEpoch:t}}}const gn="pyric:worker-generation",_t="pyric:worker-generation-probe";function Rf(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Re}:${n}`:Re;try{const r=t.getItem(gn);return r&&/^[a-f0-9]{16}$/.test(r)?`${Re}:${r}`:n?(t.setItem(gn,n),`${Re}:${n}`):Re}catch{return n?`${Re}:${n}`:Re}}function Af(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(gn,e),t.getItem(gn)!==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 If(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(_t);if(e.setItem(_t,"ok"),e.getItem(_t)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(_t):e.setItem(_t,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 Df(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}}function Pf(){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 To=new WeakMap;let Mr;function $f(e,t,n=Pf()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,c={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(c.deleted)throw new mt("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;c.assertAlive();const m=u();return i.set(l,m),m},onDelete(l){return c.deleted?(l(),()=>{}):(a.add(l),()=>a.delete(l))},deleted:!1};return To.set(e,c),c}function Of(e){Mr=e}yu({resolve(e,t){const n=typeof e=="object"&&e!==null?To.get(e):void 0;if(n)return n},defaultApp(){if(!Mr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Mr()}});const Tf="[DEFAULT]",Mf=new Map;function Uf(e,t){return new mt(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function Bf(e){return Uf("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function Lf(e=Tf){const t=Mf.get(e);if(!t)throw Bf(e);return t.app}Of(Lf);let Ff=0,Vf=0;function M(){return`op-${++Ff}`}function yt(){return`sub-${++Vf}`}const dt=new Map,Dt=new Map,Pt=new Map,bt=new WeakSet,Ur=new Set;function qf(e){return Ur.add(e),()=>Ur.delete(e)}function Mo(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Bt(e,t,n,r){return bt.has(e)?!1:(Dt.set(t,n),e.postMessage(r),!0)}function Wf(e,t,n,r){return bt.has(e)?!1:(Pt.set(t,{port:e,next:n}),e.postMessage(r),!0)}function Lt(e,t){Dt.delete(t),Pt.delete(t),bt.has(e)||e.postMessage({t:"unsub",subId:t})}function zf(e){bt.add(e);const t=Mo();for(const[n,r]of[...dt])r.port===e&&(dt.delete(n),r.reject(t));for(const[n,r]of[...Dt])r.port===e&&(Dt.delete(n),r.service==="firestore"&&r.error?.(new mt("aborted","The operation was aborted.")));for(const[n,r]of[...Pt])r.port===e&&Pt.delete(n);e.onmessage=null}function yi(e,t){if(t.denialContext===void 0||typeof fetch!="function")return;const n={kind:e,code:t.code,message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function ms(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=dt.get(n.id);if(!r)return;if(dt.delete(n.id),n.ok)r.resolve(n.value);else{const s=new Error(n.error.message);s.code=n.error.code,n.error.denialContext!==void 0&&(s.denialContext=n.error.denialContext),n.error.aiEnvelope!==void 0&&(s.aiEnvelope=n.error.aiEnvelope),yi("read",s),r.reject(s)}}else if(n.t==="snap"){const r=Dt.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const i=s.__error,a=new Error(i.message);a.code=i.code,i.denialContext!==void 0&&(a.denialContext=i.denialContext),i.aiEnvelope!==void 0&&(a.aiEnvelope=i.aiEnvelope),yi("listener",a),r.error?r.error(a):console.error("pyric/firestore: Uncaught Error in snapshot listener:",a);return}r.next(n.value)}else if(n.t==="event"){const r=Pt.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of Ur)r(n)}}const At="pyric:auth-lens";function Kf(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"?!0:t.mode==="as"&&typeof t.uid=="string"}function Uo(e){if(Kf(e))return e}function Hf(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(At);if(!e)return;const t=JSON.parse(e),n=Uo(t);if(n)return n;sessionStorage.removeItem(At);return}catch{try{sessionStorage.removeItem(At)}catch{}return}}let _e=Hf();const Gf=new Set;function bi(e){if(_e=Uo(e),typeof sessionStorage<"u")try{_e?sessionStorage.setItem(At,JSON.stringify(_e)):sessionStorage.removeItem(At)}catch{}for(const t of[...Gf])try{t(_e)}catch(n){console.error("Error in subscribeLens listener:",n)}}function Jf(){return _e}let Br;function Yf(e){Br=e}function ys(e){return Br&&(e.t==="op"||e.t==="sub")?{...e,issuer:Br}:e}function bs(e,t){return bt.has(e)?Promise.reject(Mo()):new Promise((n,r)=>{const s=t;dt.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function z(e,t){return bs(e,ys(t))}function Bo(e,t,n,r){const s=t.id;let i;const a=new Promise((c,l)=>{i=setTimeout(()=>{dt.delete(s)&&l(new Error(r))},n)});return Promise.race([z(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function de(e,t){if(bt.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new mt("failed-precondition","The client has already been terminated."));const n=_e?{...t,actAs:_e}:t;return z(e,n)}async function Qf(e,t,n={}){const r=n.timeoutMs??12e3;await Bo(e.port,{t:"op",id:M(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function Xf(e){return qf(t=>e(t.epoch))}function Zf(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 a=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${a}`))});const s=r.port;return ms(s),s.start(),{__kind:"client-db",port:s}}async function eh(e,t={}){const n=M(),r=t.timeoutMs??2e3;return(await Bo(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function th(e){return(await z(e.port,{t:"op",id:M(),method:"getVersion"})).instanceId??""}async function nh(e){return(await z(e.port,{t:"op",id:M(),method:"exportState"})).bundle}async function rh(e,t){await z(e.port,{t:"op",id:M(),method:"importState",bundle:t})}async function sh(e,t){await z(e.port,{t:"op",id:M(),method:"saveBranch",name:t})}async function ih(e){return(await z(e.port,{t:"op",id:M(),method:"listBranches"})).branches??[]}async function ah(e,t){await z(e.port,{t:"op",id:M(),method:"switchBranch",name:t})}async function oh(e,t){await z(e.port,{t:"op",id:M(),method:"deleteBranch",name:t})}async function ch(e,t,n){return await z(e.port,{t:"tool",id:M(),name:t,args:n})}function lh(e,t){return bs(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:M()})}function uh(e,t,n){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=yt();return Bt(e.port,r,{port:e.port,next:n,error:i=>n({__error:{code:i.code??"unknown",message:i instanceof Error?i.message:String(i)}})},{...t,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Lt(e.port,r)}}function dh(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const fh=[];function hh(e){for(const t of[...fh])t.port===e&&t.close()}const ph=5e3;function mh(){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 yh(e,t={}){let n;try{const r=bs(e.port,{t:"disconnect",id:M()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(mh()),t.ackTimeoutMs??ph)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),hh(e.port),zf(e.port),e.port.close()}}function gs(e){return e.split("/").at(-1)??e}function bh(e,...t){const n=("port"in e,e.port);let r;if(e.__kind==="client-db"){if(t.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const i=e.descriptor.path;r=t.length>0?`${i}/${t.join("/")}`:i}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:gs(r),path:r}}function gh(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("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:gs(r),path:r}}function vh(e){return{_descriptor:{kind:"limit",n:e}}}function wh(...e){return{_descriptor:{kind:"startAfter",values:e}}}function xh(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),r=e.__kind==="query"?e.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...t.map(i=>i._descriptor)]},port:e.port}}function jh(e){return Yl(JSON.parse(e.json))}const Lo=8*1024*1024;function _h(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Lo/1048576} MiB storage op cap (MAX_STORAGE_OP_BYTES). Streaming/resumable transfers are not supported on the sandbox backend; split the object or keep it under the cap.`);return n.code="payload-too-large",n}function kh(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 Sh(e){return jh(e)}function vs(e,t){const n=e.exists&&e.data?Sh(e.data):void 0,r=e.path??e.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:t,id:e.id,path:r};return{id:e.id,path:r,ref:s,exists:()=>e.exists,data:()=>n}}function Fo(e,t){const n=e.docs.map(r=>vs(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function Eh(e){const t=await de(e.port,{t:"op",id:M(),method:"getDoc",path:e.descriptor.path});return vs(t,e.port)}async function Ch(e){const t=await de(e.port,{t:"op",id:M(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return Fo(t,e.port)}async function Nh(e){return(await de(e.port,{t:"op",id:M(),method:"listRootCollections"})).ids}async function Rh(e,t){return(await de(e.port,{t:"op",id:M(),method:"listSubcollections",docPath:t})).ids}function Ah(e,t,n){const r=yt(),s=e.port,i={port:s,service:"firestore",next:l=>{const u=l;"docs"in u?t(Fo(u,s)):t(vs(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!Bt(s,r,i,ys(_e?{t:"sub",subId:r,target:a,actAs:_e}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Lt(s,r)}}async function Ih(e,t,n){await de(e.port,{t:"op",id:M(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function Dh(e){await de(e.port,{t:"op",id:M(),method:"deleteDoc",path:e.descriptor.path})}async function Ph(e,t){const n=await de(e.port,{t:"op",id:M(),method:"addDoc",collectionPath:e.descriptor.path,data:t});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:e.port,id:n.id,path:n.path}}async function $h(e,t){return await z(e.port,{t:"op",id:M(),method:"admin.listDocuments",path:t})}function Oh(e,t){const n=yt(),r=e.port;return Wf(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{Lt(r,n)}}async function Th(e){return await z(e.port,{t:"op",id:M(),method:"getSnapshot"})}async function Mh(e){return await z(e.port,{t:"op",id:M(),method:"resetAll"})??{errors:[]}}const Uh=15e3;function Bh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function gi(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function vi(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function Lh(){return Bh()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function wi(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function xi(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function Fh(e){const{db:t,kind:n}=e,r=e.clientId??Lh(),s=e.heartbeatIntervalMs??Uh;let i=!1,a=null;const c=()=>{z(t.port,{t:"op",id:M(),method:"presence.register",clientId:r,kind:n,route:wi(),visibility:xi()}).catch(()=>{})},l=()=>{z(t.port,{t:"op",id:M(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{z(t.port,{t:"op",id:M(),method:"presence.update",clientId:r,route:wi(),visibility:xi()}).catch(()=>{})},d=()=>{z(t.port,{t:"op",id:M(),method:"presence.disconnect",clientId:r}).catch(()=>{})};c(),gi()&&document.addEventListener("visibilitychange",u),vi()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",m),a=setInterval(()=>{i||l()},s));function m(){f()}function f(){i||(i=!0,a!=null&&(clearInterval(a),a=null),gi()&&document.removeEventListener("visibilitychange",u),vi()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",m)),d())}return{clientId:r,kind:n,stop:f}}function Vh(e,t){const n=yt();return Bt(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Lt(e.port,n)}}const qh=Symbol("pyric.clientUser.port");function Wh(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:t.photoURL,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await z(e,{t:"op",id:M(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await z(e,{t:"op",id:M(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,qh,{value:e,enumerable:!1}),n}function zh(e,t){return t?Wh(e,t):null}function Kh(e,t){let n;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")n=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 (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),ms(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=yt();return Bt(n,s,{port:n,next:i=>{r.currentUser=zh(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function Hh(e){return await z(e.port,{t:"op",id:M(),method:"auth.listUsers"})}async function Gh(e,t){return await z(e.port,{t:"op",id:M(),method:"auth.adminCreateUser",request:t})}async function Jh(e,t,n){return await z(e.port,{t:"op",id:M(),method:"auth.adminUpdateUser",uid:t,request:n})}async function Yh(e,t){await z(e.port,{t:"op",id:M(),method:"auth.adminDeleteUser",uid:t})}async function Qh(e){await z(e.port,{t:"op",id:M(),method:"auth.adminClearUsers"})}async function Xh(e){return await z(e.port,{t:"op",id:M(),method:"auth.getProviderConfig"})}async function Zh(e,t,n){await z(e.port,{t:"op",id:M(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const Lr="pyric-storage";function ep(e){return e?`${Lr}:${e}`:Lr}const tp=1,me="blobs",ae="metadata";async function np(e=Lr){try{const t=await ip(e);return new sp(t)}catch{return new rp}}class rp{blobs=new Map;metadata=new Map;async put(t,n,r){this.blobs.set(t,n),this.metadata.set(t,r)}async getBlob(t){return this.blobs.get(t)}async getMetadata(t){return this.metadata.get(t)}async putMetadata(t,n){this.metadata.set(t,n)}async delete(t){this.blobs.delete(t),this.metadata.delete(t)}async listByPrefix(t){const n=[],r=Array.from(this.metadata.keys()).sort();for(const s of r)if(s.startsWith(t)){const i=this.metadata.get(s);i&&n.push(i)}return n}async reset(){this.blobs.clear(),this.metadata.clear()}close(){}}class sp{db;constructor(t){this.db=t}async put(t,n,r){const s=this.db.transaction([me,ae],"readwrite");s.objectStore(me).put(n,t),s.objectStore(ae).put(r,t),await Kt(s)}async getBlob(t){const n=this.db.transaction(me,"readonly");return ir(n.objectStore(me).get(t))}async getMetadata(t){const n=this.db.transaction(ae,"readonly");return ir(n.objectStore(ae).get(t))}async putMetadata(t,n){const r=this.db.transaction(ae,"readwrite");r.objectStore(ae).put(n,t),await Kt(r)}async delete(t){const n=this.db.transaction([me,ae],"readwrite");n.objectStore(me).delete(t),n.objectStore(ae).delete(t),await Kt(n)}async listByPrefix(t){const n=this.db.transaction(ae,"readonly"),r=IDBKeyRange.bound(t,t+"￿",!1,!1);return ir(n.objectStore(ae).getAll(r))}async reset(){const t=this.db.transaction([me,ae],"readwrite");t.objectStore(me).clear(),t.objectStore(ae).clear(),await Kt(t)}close(){this.db.close()}}function ip(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,tp);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(me)||s.createObjectStore(me),s.objectStoreNames.contains(ae)||s.createObjectStore(ae)}),r.addEventListener("success",()=>t(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${e}"`)))}catch(r){n(r)}})}function ir(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Kt(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")))})}function ji(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const ap=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function Vo(e){return{segments:e.path.segments.map(op),children:e.children.map(Vo),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(Fr)}}function op(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 Fr(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>({name:t.name,value:H(t.value)})),body:H(e.body)}}function H(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Se(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:H(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:H(e.object),method:e.method,args:e.args.map(H)};case"bracketAccess":return{kind:"index",target:H(e.object),index:H(e.index)};case"sliceAccess":return{kind:"slice",target:H(e.object),start:H(e.start),end:H(e.end)};case"binaryOp":if(!ap.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:H(e.left),right:H(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:H(e.operand)};case"ternary":return{kind:"ternary",cond:H(e.condition),then:H(e.consequent),else:H(e.alternate)};case"inExpr":return{kind:"in",element:H(e.element),collection:H(e.collection)};case"isExpr":return{kind:"is",value:H(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(H)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:H(t.key),value:H(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:H(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(H)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function Vr(e){const t=Ql(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: expected ${t.error.expected}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[Vo(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(i=>({name:i,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Fr),...(n.service.functions??[]).map(Fr)]};return qo(r,new Map),{_root:r,_version:n.version}}function qo(e,t){const n=new Map(t);for(const r of e.functions)n.set(r.name,r);e.visibleFuncs=n;for(const r of e.functions)r.declScope=n;for(const r of e.children)qo(r,n)}function X(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 X(e.target,t);case"index":return X(e.target,t)||X(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>X(n,t));case"unary":return X(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>X(n,t));case"in":return X(e.element,t)||X(e.collection,t);case"is":return X(e.value,t);case"list":return e.elements.some(n=>X(n,t));case"map":return e.entries.some(({key:n,value:r})=>X(n,t)||X(r,t));case"binary":return X(e.left,t)||X(e.right,t);case"call":return e.args.some(n=>X(n,t));case"methodcall":return X(e.target,t)||e.args.some(n=>X(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&X(n.expr,t));case"ident":case"literal":return!1}}function Wo(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&&X(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(X(i.value,s))return!0;s.add(i.name)}if(X(r.body,s))return!0}return e.children.some(r=>Wo(r,n))}function cp(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return Wo(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 lp="pyric-default",Tn=Symbol("pyric/storage/target");function Ye(e){return e.currentAuth?.()??e.context.auth}class up{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}const _i=new WeakMap;function ki(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 dp(e,t,n){const r=_i.get(e);if(r)return ki("rules","rules source",t.rules,r.rulesSource,n),ki("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let s=null,i=null;if(t.rules){let l=t.rules,u=[],d=[],m=[];if(s=Vr(l),s._version==="2+modules"){const f=eo(l);if(!f.success)throw new SyntaxError(`Storage rules module resolution failed (${f.error.code}): ${f.error.message}`);l=f.data.resolved,u=f.data.modules,d=f.data.bundledModules,m=f.data.evidenceIds,s=Vr(l)}i=cp(l,u,d,m,s)}const a=t.crossServiceIam??"granted",c=np(t.dbName??ep(t.projectId)).then(l=>new up(l,s,a));return _i.set(e,{service:c,rulesSource:t.rules??null,rulesResolution:i,crossServiceIam:a}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await c).backend.reset()}}),c}function ar(e){return e instanceof Zl}const Si=new WeakMap,Ei=new WeakMap;function fp(e,t={}){const n=!ar(e),r=ar(e)?e.sandbox:e,s=dp(r,t,"getAdminStorageSandbox");if(n){const d=Ei.get(r);if(d)return d}const i=ar(e)?e:r.withAuth(null),a=i.operationContext.authLens.mode==="admin"?i:Qa(i,{source:i.operationContext.source,authLens:{mode:"admin"},...i.operationContext.planId===void 0?{}:{planId:i.operationContext.planId}}),c=Si.get(i);if(c)return c;const l={kind:"sandbox",sandbox:r,context:a,bucket:t.bucket??lp,servicePromise:s,admin:!0},u=Object.freeze({[Tn]:l});return Si.set(i,u),n&&Ei.set(r,u),u}function gt(e,t){const n=Xl(t,Fs(e.context.operationContext));return{...t,...Fs(n),service:"storage"}}function Ee(e){const t=e[Tn];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Ft(e){return Ee(e).servicePromise}class U extends Error{}class ke extends U{}class ws extends U{}function hp(e){return e instanceof U&&!(e instanceof ke)&&!(e instanceof ws)}class Z{message;constructor(t){this.message=t}}function W(e){return e instanceof Z}function $e(e){if(typeof e=="number")return e;if(e instanceof Se)return e.value}function Oe(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ct(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=$e(e),r=$e(t);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((s,i)=>ct(s,t[i]));if(Oe(e)&&Oe(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&ct(e[a],t[a]))}return!1}function se(e){return e===null?"null":e===void 0?"undefined":e instanceof Se?"float":typeof e}function pp(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return gp(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return bp(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return mp(e,t);if(e.method==="matches")return vp(e,t);if(e.method==="split")return wp(e,t);if(e.method==="size")return xp(e,t);if(e.method==="keys")return jp(e,t);if(e.method==="hasAll")return _p(e,t);if(e.method==="get")return kp(e,t);throw new ke(`unsupported method .${e.method}()`)}function mp(e,t){if(e.method!=="get"&&e.method!=="exists")throw new ke(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new U(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new ke(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];if(n.kind!=="path")throw new ke(`firestore.${e.method}() requires a /databases/.../documents/... path literal`);const r=yp(n,t);if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new ws("firestore access limit exceeded: at most two distinct documents");t.firestoreAccesses.add(r)}if(e.method==="exists")return t.firestoreLookup.exists(r);const s=t.firestoreLookup.get(r);return s===null?new Z(`firestore.get() targeted a nonexistent document: ${r}`):{data:s}}function yp(e,t){const n=e.segments.map(s=>{if(s.kind==="literal")return s.value;const i=B(s.expr,t);if(typeof i=="string")return i;if(typeof i=="number")return String(i);throw new U(`Firestore path interpolation resolved to ${se(i)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new U(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);if(n[1]!=="(default)")throw new U(`Storage rules may access only the default Firestore database, got ${n[1]}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new U(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const Ci={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function bp(e,t){if(e.method!=="value")throw new U(`unsupported duration.${e.method}()`);const n=e.args.map(a=>B(a,t));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new U("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,i=Ci[s];if(i===void 0)throw new U(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(Ci).join(", ")}`);return r*i}function gp(e,t){const n=e.args.map(r=>B(r,t));if(e.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new U("timestamp.value() expects (epochMillis: number)");return n[0]}if(e.method==="date"){if(n.length!==3||!n.every(a=>typeof a=="number"))throw new U("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;return Date.UTC(r,s-1,i)}throw new U(`unsupported timestamp.${e.method}()`)}function vp(e,t){const n=B(e.target,t);if(W(n))return n;if(typeof n!="string")throw new U(`matches() requires a string target, got ${se(n)}`);if(e.args.length!==1)throw new U("matches() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("matches() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(`^(?:${r})$`)}catch(c){throw new U(`matches() invalid regex pattern: ${c.message}`)}return a.test(n)}function wp(e,t){const n=B(e.target,t);if(W(n))return n;if(typeof n!="string")throw new U(`split() requires a string target, got ${se(n)}`);if(e.args.length!==1)throw new U("split() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("split() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(r)}catch(c){throw new U(`split() invalid regex pattern: ${c.message}`)}return n.split(a)}function xp(e,t){const n=B(e.target,t);if(W(n))return n;if(e.args.length!==0)throw new U("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(Oe(n))return Object.keys(n).length;throw new U(`size() requires a string, list, or map target, got ${se(n)}`)}function jp(e,t){const n=B(e.target,t);if(W(n))return n;if(e.args.length!==0)throw new U("keys() expects no arguments");if(!Oe(n))throw new U(`keys() requires a map target, got ${se(n)}`);return Object.keys(n)}function _p(e,t){const n=B(e.target,t);if(W(n))return n;if(!Array.isArray(n))throw new U(`hasAll() requires a list or set target, got ${se(n)}`);if(e.args.length!==1)throw new U("hasAll() expects one list or set argument");const r=B(e.args[0],t);if(W(r))return r;if(!Array.isArray(r))throw new U("hasAll() argument must be a list or set");return r.every(s=>n.some(i=>ct(i,s)))}function kp(e,t){const n=B(e.target,t);if(W(n))return n;if(!Oe(n))throw new U(`get() requires a map target, got ${se(n)}`);if(e.args.length!==2)throw new U("get() expects a key and default value");const r=B(e.args[0],t);if(W(r))return r;if(typeof r!="string")throw new U("get() key must be a string");const s=B(e.args[1],t);return W(s)?s:Object.prototype.hasOwnProperty.call(n,r)?n[r]:s}function Sp(e){return e.split("/").filter(t=>t.length>0)}function or(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function Ep(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="wildcard")return s[a.name]=t.slice(r),{left:[],params:s};if(r>=t.length)return null;if(a.kind==="literal"){if(t[r]!==a.value)return null;r++}else s[a.name]=t[r],r++}return{left:t.slice(r),params:s}}function zo(e,t,n=new Date,r){const s=n.getTime(),i=Sp(t.request.path),a=[],c=new Set,l=new Set(ji(t.request.method));function u(m,f,p){const y=Ep(m.segments,f,p);if(!y)return!1;const b=y.params,v=y.left;if(v.length===0)for(const g of m.allows){const w=new Set(g.verbs.flatMap(ji));if(![...l].some(j=>w.has(j)))continue;let _;try{const j=g.condition?B(g.condition,{input:t,now:s,params:b,locals:{},funcs:m.visibleFuncs??new Map,depth:0,firestoreLookup:r,firestoreAccesses:c}):!0;if(W(j)){a.push(`match ${or(m.segments)} ${t.request.method}: ${j.message}`);continue}_=Ko(j)}catch(j){if(j instanceof U){a.push(`match ${or(m.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(_)return!0;a.push(`match ${or(m.segments)} ${t.request.method}: condition false`)}for(const g of m.children)if(u(g,v,b))return!0;return!1}const d=u(e._root,i,{});return!d&&a.length===0&&a.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:d,reasons:a}}function Ni(e,t){if(!Oe(e)&&!Array.isArray(e))return new Z(`Property ${t} is undefined on ${se(e)}.`);if(!Object.hasOwn(e,t))return new Z(`Property ${t} is undefined on object.`);const n=e[t];return n===void 0?new Z(`Property ${t} is undefined on object.`):n}function Ko(e){return W(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const Ri=20;function B(e,t){switch(e.kind){case"literal":return e.value;case"ident":return e.name in t.locals?t.locals[e.name]:e.name==="request"?Ap(t.input,t.now):e.name==="resource"?t.input.resource===null?new Z("Null value error."):Rp(t.input.resource):e.name in t.params?t.params[e.name]:void 0;case"member":{const n=B(e.target,t);return W(n)?n:n==null?new Z("Null value error."):Ni(n,e.name)}case"index":{const n=B(e.target,t);if(W(n))return n;if(n==null)return new Z("Null value error.");const r=B(e.index,t);return W(r)?r:Ni(n,String(r))}case"call":return Cp(e,t);case"methodcall":return pp(e,t);case"path":throw new ke("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=B(e.arg,t);if(e.op==="!"){if(W(n))throw new U(n.message);if(typeof n!="boolean")throw new U(`Unary '!' expects a boolean, got ${se(n)}.`);return!n}return W(n)?n:e.op==="-"?n instanceof Se?new Se(-n.value):typeof n!="number"?new Z(`Unary '-' applied to ${se(n)}.`):-n:void 0}case"ternary":{const n=B(e.cond,t);return W(n)?n:Ko(n)?B(e.then,t):B(e.else,t)}case"in":{const n=B(e.element,t);if(W(n))return n;const r=B(e.collection,t);return W(r)?r:Array.isArray(r)?r.some(s=>ct(s,n)):Oe(r)?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new Z(`'in' applied to ${se(r)} (expected a list or map).`)}case"is":{const n=B(e.value,t);return W(n)?n:Np(n,e.typeName)}case"list":{const n=[];for(const r of e.elements){const s=B(r,t);if(W(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of e.entries){const s=B(r.key,t);if(W(s))return s;if(typeof s!="string")return new Z(`Map literal key is ${se(s)} (expected a string).`);const i=B(r.value,t);if(W(i))return i;n[s]=i}return n}case"slice":{const n=B(e.target,t);if(W(n))return n;const r=B(e.start,t);if(W(r))return r;const s=B(e.end,t);return W(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new Z("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new Z(`Slice bounds [${r}:${s}] out of range for ${se(n)} of size ${n.length}.`):n.slice(r,s):new Z(`Slice applied to ${se(n)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return Ai(e.left,e.right,!1,t);if(e.op==="||")return Ai(e.left,e.right,!0,t);const n=B(e.left,t);if(W(n))return n;const r=B(e.right,t);if(W(r))return r;switch(e.op){case"==":return ct(n,r);case"!=":return!ct(n,r);case"<":return Ht(n,r)<0;case">":return Ht(n,r)>0;case"<=":return Ht(n,r)<=0;case">=":return Ht(n,r)>=0;case"+":return Le(n,r,(s,i)=>s+i);case"-":return Le(n,r,(s,i)=>s-i);case"*":return Le(n,r,(s,i)=>s*i);case"/":return st(n)||st(r)?Le(n,r,(s,i)=>s/i):$e(r)===0?new Z("Division by zero."):Le(n,r,(s,i)=>Math.trunc(s/i));case"%":return st(n)||st(r)?Le(n,r,(s,i)=>s%i):$e(r)===0?new Z("Modulo by zero."):Le(n,r,(s,i)=>s%i)}}}}function Ai(e,t,n,r){const s=Ii(e,r);if(s===n)return n;const i=Ii(t,r);return i===n?n:W(s)?s:i}function Ii(e,t){let n;try{n=B(e,t)}catch(r){if(hp(r))return new Z(r.message);throw r}return W(n)?n:typeof n!="boolean"?new Z(`Expected a boolean '&&'/'||' operand, got ${se(n)}.`):n}function Cp(e,t){const n=t.funcs.get(e.name);if(!n)throw new ke(`undefined function ${e.name}()`);if(n.unresolvedImport!==void 0)throw new ke(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)throw new ke(`function ${e.name}() expects ${n.params.length} argument(s), got ${e.args.length}`);const r=t.depth+1;if(r>Ri)throw new ws(`function ${e.name}() exceeded max call depth ${Ri}`);const s=e.args.map(c=>B(c,t)),i={};n.params.forEach((c,l)=>{i[c]=s[l]});const a={input:t.input,now:t.now,params:{},locals:i,funcs:n.declScope??new Map,depth:r,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses};for(const c of n.lets)i[c.name]=B(c.value,a);return B(n.body,a)}function Np(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 Se||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Se||typeof e=="number";case"list":return Array.isArray(e);case"map":return Oe(e);default:return new Z(`'is ${t}' is not supported by the storage evaluator.`)}}function st(e){return e instanceof Se}function Ht(e,t){const n=$e(e),r=$e(t);return n!==void 0&&r!==void 0?n-r:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:Number.NaN}function Le(e,t,n){const r=$e(e),s=$e(t);if(r===void 0||s===void 0)return;const i=n(r,s);return st(e)||st(t)?new Se(i):i}function Rp(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Di(e.timeCreated),updated:Di(e.updated)}}function Di(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Ap(e,t){return{auth:e.request.auth??new Z("Property auth is undefined on object."),resource:e.request.resource??new Z("Property resource is undefined on object."),method:e.request.method,path:e.request.path,time:t}}function Ip(e){return`storage/${e}`}class vt extends Error{code;constructor(t,n){const r=Ip(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,vt.prototype)}}function Ho(e){return new vt("object-not-found",`no object at "${e}".`)}function Pi(e,t,n){return new vt("unauthorized",`${e} "${t}" denied by rules${n}.`)}function Mn(e){return new vt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Dp(){return new vt("canceled","User canceled the upload/download.")}function Vt(e,t,n,r){const s=n?.kind==="sandbox"?gt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Gt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules)throw Gt(n,t,"deny",["No Storage rules configured; default deny."],"user",!1,s),Pi(t.request.method,t.request.path," — No Storage rules configured; default deny.");const i=n?Pp(t,n.bucket):t,a=zo(e.rules,i,void 0,$p(n,e.crossServiceIam));if(!a.allowed){Gt(n,t,"deny",a.reasons,"user",!0,s);const c=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw Pi(t.request.method,t.request.path,c)}Gt(n,t,"allow",a.reasons,"user",!0,s)}function Pp(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Gt(e,t,n,r,s,i,a){if(e)try{Ie(e.sandbox,Ja({service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,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}),{...a,service:"storage"})}catch{}}function $p(e,t){if(!e)return;if(t==="denied")return Op();const n=e.sandbox.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function Op(){const e=t=>{throw new U(`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 Un(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Tp(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:$i(e.generation),metageneration:$i(e.metageneration)}:null}function Tp(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 $i(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Mp(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function xs(e){return{...e}}async function Up(e){Bp(e,"getMetadata");const t=Ee(e.storage),n=gt(t),r=await Ft(e.storage),s=await r.backend.getMetadata(e.fullPath);if(Vt(r,{request:{auth:Ye(t),method:"get",path:e.fullPath},resource:Un(s)},t,n),!s)throw Ho(e.fullPath);return xs(s)}function Bp(e,t){if(e.fullPath==="")throw Mn(t)}const Lp="application/octet-stream";async function Go(e,t,n,r){qp(e,"uploadBytes");const s=Ee(e.storage),i=gt(s,r),a=Fp(t,n?.contentType),c=Jo({ref:e,blob:a,settable:n}),l=await Ft(e.storage),u=await l.backend.getMetadata(e.fullPath);Vt(l,{request:{auth:Ye(s),method:u?"update":"create",path:e.fullPath,resource:Mp({size:c.size,contentType:c.contentType,customMetadata:c.customMetadata})},resource:Un(u)},s,i),await l.backend.put(e.fullPath,a,c);try{Ie(s.sandbox,Cn({service:"storage",op:"object_put",path:e.fullPath,auth:Ye(s),before:u??void 0,after:c,detail:{bucket:e.bucket,size:c.size,contentType:c.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:xs(c)}}function Jo(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=Vp(e.now??new Date),a=t.name;return{fullPath:t.fullPath,name:a,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Lp,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Fp(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Vp(e){return String(e.getTime())}function qp(e,t){if(e.fullPath==="")throw Mn(t)}function Wp(e){return e instanceof Blob?e.size:e.byteLength}function zp(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function Kp(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class Hp{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_data;_metadata;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=Wp(n),i=new Date().toISOString();let a="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(a=n.type),r!==void 0&&r.contentType!==void 0){const m=r.contentType;m!==void 0&&(a=m)}const u={fullPath:t.fullPath,name:t.name,bucket:"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:a};this._promise=new Promise((d,m)=>{this._resolve=d,this._reject=m}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,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(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=zp(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,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&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const g=a,w=this._error;try{g(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}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 c=i.next;try{c(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 c=i.complete;try{c()}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(){if(this._snapshot.state==="running")try{const n=await Yo(this._ref,this._data,this._metadata);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await Qo(this._ref)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function Gp(e,t,n){if(e.fullPath==="")throw Kp();return new Hp(e,t,n)}class $t{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=gs(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 $t(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new $t(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Jp(e){return e.replace(/^\/+|\/+$/g,"")}function Yp(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(),ms(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function Qp(e,t){const n=Jp(t??"");let r,s,i="pyric-default",a;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,a=e;else{const c=e.fullPath;r=n?c?`${c}/${n}`:n:c,s=e.port,i=e.bucket,a=e.storage}return new $t(s,i,r,a)}async function Xp(e){const t=await de(e.port,{t:"op",id:M(),method:"storage.listAll",path:e.fullPath}),n=r=>new $t(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function Zp(e){return await de(e.port,{t:"op",id:M(),method:"storage.getMetadata",path:e.fullPath})}async function em(e){return await de(e.port,{t:"op",id:M(),method:"storage.getBlob",path:e.fullPath})}async function Yo(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>Lo)throw _h(r.byteLength,`uploadBytes payload for '${e.fullPath}'`);const s=n?.contentType??(t instanceof Blob&&t.type?t.type:void 0),i=await de(e.port,{t:"op",id:M(),method:"storage.putBytes",path:e.fullPath,dataB64:kh(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function Qo(e){await de(e.port,{t:"op",id:M(),method:"storage.deleteObject",path:e.fullPath})}async function tm(e){return z(e.port,{t:"op",id:M(),method:"rtdb.adminSnapshot"})}async function nm(e,t,n){await z(e.port,{t:"op",id:M(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function rm(e,t,n){await z(e.port,{t:"op",id:M(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function sm(e,t){await z(e.port,{t:"op",id:M(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function im(e,t,n,r){const s=yt();return!Bt(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},ys({t:"sub",subId:s,target:{service:"rtdb",path:dh(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>Lt(e.port,s)}function am(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 a=null;const c=()=>i?(a??=Df({targetEpoch:i,retire:()=>e.retire?e.retire(i):Qf(e.db,i),subscribeReload:e.subscribeReload??Xf,preflight:e.preflight??(()=>If(s)),commitGeneration:e.remember??(l=>Af(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}:{}}),a):null;return(e.readVersion??(()=>eh(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),c(),()=>{t.delete(l),t.size===0&&(a?.dispose(),a=null)}},async update(){const l=c();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(),a?.dispose(),a=null}}}function om(e={}){const t=Oo(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:Rf(t.worker.servedEpoch,n)}}const cm="/__pyric/sdk/worker.js";function lm(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=Oh(e,a=>{const c=!n;n=!0;const l=c?[]:[...t];for(const u of a)Ro(u)&&(l.length=0),l.push(u);t=l;for(const u of a)for(const d of r)d(u)}))}return{history:()=>t,subscribe:a=>(r.add(a),i(),()=>{r.delete(a),r.size===0&&s&&(s(),s=null,n=!1,t=[])})}}function um(e=cm){if(typeof SharedWorker>"u")return null;Yf("studio");let t;try{const l=om({workerUrl:e});t=Zf(l.url,l.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=am({db:t,servedEpoch:Oo(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});bi({mode:"admin"});const s=Fh({db:t,kind:"studio"}),i=lm(t),a=Kh(t);let c=!1;return{db:t,runtime:r,dispose:async()=>{c||(c=!0,s.stop(),r.dispose(),await yh(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:l=>Vh(t,l),instanceId:()=>th(t),exportState:()=>nh(t),importState:l=>rh(t,l),saveBranch:l=>sh(t,l),listBranches:()=>ih(t),switchBranch:l=>ah(t,l),deleteBranch:l=>oh(t,l),feed:i,setLens:l=>bi(l),getLens:()=>Jf(),listRootCollections:()=>Nh(t),listSubcollections:l=>Rh(t,l),listDocuments:async l=>(await $h(t,l)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>tm(t),setRtdbValue:(l,u)=>nm(t,l,u),updateRtdbValue:(l,u)=>rm(t,l,u),deleteRtdbValue:l=>sm(t,l),subscribeRtdbValue:(l,u,d)=>im(t,l,u,d),firestoreApi:{collection:gh,doc:bh,getDoc:Eh,getDocs:Ch,onSnapshot:Ah,setDoc:Ih,deleteDoc:Dh,addDoc:Ph,query:xh,limit:vh,startAfter:wh},auth:a,authApi:{listUsers:()=>Hh(a),subscribeUsers:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(l,u)=>Gh(a,u),updateUser:(l,u,d)=>Jh(a,u,d),deleteUser:(l,u)=>Yh(a,u),clearUsers:()=>Qh(a),getAuthProviderConfig:()=>Xh(a),setAuthProviderConfig:(l,u,d)=>Zh(a,u,d),subscribeAuthProviderConfig:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:Yp(t),storageApi:{ref:Qp,listAll:Xp,getMetadata:Zp,getBlob:em,uploadBytes:Yo,uploadBytesResumable:Gp,deleteObject:Qo},getSnapshot:()=>Th(t),resetAll:()=>Mh(t)}}const Oi=5174,Ti="/sandbox",dm=4001,fm="worker-relay";function hm(e){if(e===null||typeof e!="object")return!1;const t=e.type;return t==="hello"||t==="hello-ack"||t==="attach"||t==="attach-ack"||t==="tool-call"||t==="tool-result"||t==="worker-op"||t==="worker-res"||t==="worker-sub"||t==="worker-unsub"||t==="worker-snap"||t==="ping"||t==="pong"}function qr(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=qr(t);if(n)return n}return null}for(const t of Object.values(e)){const n=qr(t);if(n)return n}return null}function Mi(e,t){const n=qr(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 pm={transport:"in-process",order:60,tools:["pyric_can_i_use"]},mm={transport:"forwarded",order:20,tools:["firestore_get_document","firestore_list_documents","firestore_create_document","firestore_add_document","firestore_update_document","firestore_delete_document","firestore_batch_write","firestore_query_where"]},ym={transport:"forwarded",order:30,tools:["sandbox_inspect"]},bm={transport:"in-process",order:50,tools:["firestore_simulate_rules","firestore_rules_stdlib_list","firestore_rules_stdlib_get","firestore_lint_rules","firestore_resolve_modules","rules_stdlib_list","rules_stdlib_get","rules_resolve_modules"]},gm={transport:"forwarded",order:10,tools:["firestore_simulator_create","firestore_simulator_execute","firestore_simulator_read","firestore_simulator_batch","firestore_create_with_auto_id","firestore_simulator_undo","firestore_simulator_redo","firestore_simulator_events","firestore_simulator_transaction"]},vm={transport:"forwarded",order:40,tools:["rtdb_simulate_access","rtdb_crawl_structure"]},wm=[{key:"conformance",...pm},{key:"firestore-data",...mm},{key:"firestore-inspect",...ym},{key:"firestore-rules",...bm},{key:"firestore-simulator",...gm},{key:"rtdb-inspection",...vm}];function cr(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 xm(e){return cr("key",e.map(t=>t.key)),cr("order",e.map(t=>t.order)),cr("tool name",e.flatMap(t=>t.tools)),[...e].sort((t,n)=>t.order-n.order)}const jm=xm(wm);function Xo(e){return jm.filter(t=>t.transport===e)}function _m(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,a)=>i!==s[a]))throw new Error(`${e} drifted from the default MCP contract
106
+ `;let ei;function po(){return ei??=Hl(sd),ei}function Mn(e){return po().match(e.trim())}function Un(){return po().createSemantics()}let tr;function id(){if(tr)return tr;const e=Un();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,a){return[...t.identifiers(),...i.asIteration().children.flatMap(c=>c.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),tr=e,e}function ad(e){const t=Mn(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=id()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const od=new Set(["__proto__","prototype","constructor"]);function L(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(od.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 J(e){return e.length===0?"/":"/"+e.join("/")}function De(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>De(n));const t={};for(const[n,r]of Object.entries(e))t[n]=De(r);return t}function ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(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)=>ht(s,t[i]));if(!ti(e)||!ti(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&ht(e[s],t[s]))}class cd{root={};snapshot(){return De(this.root)}restore(t){this.root=De(t)}read(t){const n=L(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 a=s;if(!Object.hasOwn(a,i))return null;s=a[i]}return De(s)}write(t,n){const r=L(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=De(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let c=0;c<r.length-1;c++){const l=r[c],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 a=r[r.length-1];return n===null?(delete i[a],this.trim(r)):i[a]=De(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,a])=>({path:J(L(i)),value:a}));for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){const c=r[i].path,l=r[a].path;if(c===l)throw new Error(`multi-path update: duplicate path '${c}'.`);const u=c==="/"?"/":c+"/",d=l==="/"?"/":l+"/";if(c!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`);if(l!=="/"&&c.startsWith(d))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:a}of r){const c=this.write(i,a);s.push({path:i,prior:c})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const c=[...s,...L(i)],l=J(c),u=this.write(l,a);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 c=0;c<r.length-1;c++){const l=i[r[c]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const a=i[s];if(a!==void 0&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0){delete i[s];continue}return}}}function ld(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class ud{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=>J(L(n)))})}conflictsSince(t,n){const r=J(L(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>ld(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 ye(e){return e==="unsupported"?"unsupported":"deny"}function _e(e){return J(L(e))}class dd{sandbox;nextId=0;constructor(t){this.sandbox=t}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{Pe(this.sandbox,In({service:"rtdb",op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,a={}){if(this.sandbox)try{let c;i&&(c={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let l="user";a.origin&&(l=a.origin),Pe(this.sandbox,eo({service:"rtdb",method:n,path:_e(r),auth:t,result:s,origin:l,durationMs:a.durationMs,reasons:i?.reasons,rules:c,request:a.request,resourceBefore:a.resourceBefore,resourceAfter:a.resourceAfter,groupId:a.groupId,groupKind:a.groupKind,triggeredBy:a.triggeredBy,detail:a.detail,at:a.at}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{Pe(this.sandbox,Gl({service:"rtdb",method:n,path:_e(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),Pe(this.sandbox,Jl({service:"rtdb",phase:t,listenerId:n.id,target:{kind:i,path:_e(n.path)},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}),{service:"rtdb"})}catch{}}}class fd{values=new Map;get(t){return this.values.get(J(L(t)))??null}forChild(t){const n=L(t);return r=>this.get(J([...n,r]))}clear(){this.values.clear()}clearAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n){this.clearAtOrBelow(t),n!==null&&this.values.set(J(L(t)),n)}set(t,n){const r=J(L(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t){for(const n of t){const r=this.get(n.path);this.clearAtOrBelow(n.path),n.value!==null&&r!==null&&this.values.set(J(L(n.path)),r)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(J(L(n)),r)}}function mn(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)")}let Ye=[],Ir=!1,Dr=!1,Pr=!1,nr;function hd(){if(nr)return nr;const e=Un();return e.addOperation("lint",{_nonterminal(...t){t.forEach(n=>n.lint())},_iter(...t){t.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.lint(),i.asIteration().children.forEach(c=>c.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(Pr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(Ir=!0),s==="newData"&&(Dr=!0)},bool_true(t){Ye.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){Ye.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){Ye.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){Ye.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),nr=e,e}function pd(e,t="read"){const n=Mn(e);return n.failed()?[]:(Ye=[],Ir=!1,Dr=!1,Pr=!1,hd()(n).lint(),t==="write"&&Ir&&!Dr&&!Pr&&Ye.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Ye])}const md={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},yd=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),bd=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),gd=new Set([...yd,...bd]);let Dt=[],ln="read",mo=new Set,rr;function vd(){if(rr)return rr;const e=Un();return e.addOperation("validate",{_nonterminal(...t){t.forEach(n=>n.validate())},_iter(...t){t.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.validate();const c=r.sourceString;gd.has(c)||Dt.push({code:"UNKNOWN_METHOD",message:`Unknown method '${c}'`}),i.asIteration().children.forEach(l=>l.validate())},CallExpr_memberAccess(t,n,r){t.validate()},CallExpr_indexAccess(t,n,r,s){t.validate(),r.validate()},ident(t,n,r){const s=this.sourceString;if(t.sourceString==="$")return;const a=md[ln];a&&(!a.has(s)&&!mo.has(s)&&Dt.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${ln}' context`}),s==="newData"&&ln==="read"&&Dt.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),rr=e,e}function wd(e,t,n=[]){const r=Mn(e);return r.failed()?[]:(Dt=[],ln=t,mo=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),vd()(r).validate(),[...Dt])}const xd=new Set(["__proto__","prototype","constructor"]);function ni(e,t){return xd.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 jd(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="\\"||n===e.length-1){t+=r;continue}const s=e[++n];switch(s){case"\\":t+="\\";break;case"'":t+="'";break;case'"':t+='"';break;case"n":t+=`
107
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"b":t+="\b";break;case"f":t+="\f";break;case"/":t+="/";break;default:t+="\\"+s;break}}return t}class ve{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(t){return this.child(t).exists()}hasChildren(t){return Array.isArray(t)?t.every(n=>this.hasChild(String(n))):typeof this._value=="object"&&this._value!==null&&Object.keys(this._value).length>0}isString(){return typeof this._value=="string"}isNumber(){return typeof this._value=="number"}isBoolean(){return typeof this._value=="boolean"}child(t){const n=t.split("/").filter(a=>a.length>0);if(n.length===0)return this;let r=this._value;for(const a of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,a)?r[a]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new ve(r,i,this._root)}parent(){if(this._path==="/")return null;const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new ve(this._root,"/"):new ve(this._root,"/").child(t.join("/"))}getPriority(){return null}}class kd{value;constructor(t){this.value=t}matches(t){return(t instanceof RegExp?t:new RegExp(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){if(t instanceof RegExp){const r=t.flags.includes("g")?t.flags:`${t.flags}g`;return this.value.replace(new RegExp(t.source,r),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}}let Ae={auth:null,data:new ve(null),newData:new ve(null),root:new ve(null),now:Date.now(),pathVariableBindings:{}},sr;function _d(){if(sr)return sr;const e=Un();return e.addOperation("eval",{Expr(t){return t.eval()},Ternary_ternary(t,n,r,s,i){return t.eval()?r.eval():i.eval()},Ternary(t){return t.eval()},Logical_and(t,n,r){return t.eval()&&r.eval()},Logical_or(t,n,r){return t.eval()||r.eval()},Logical(t){return t.eval()},Comparison_strictEq(t,n,r){return t.eval()===r.eval()},Comparison_strictNeq(t,n,r){return t.eval()!==r.eval()},Comparison_gte(t,n,r){return t.eval()>=r.eval()},Comparison_lte(t,n,r){return t.eval()<=r.eval()},Comparison_gt(t,n,r){return t.eval()>r.eval()},Comparison_lt(t,n,r){return t.eval()<r.eval()},Comparison_looseEq(t,n,r){return t.eval()==r.eval()},Comparison_looseNeq(t,n,r){return t.eval()!=r.eval()},Comparison(t){return t.eval()},Additive_add(t,n,r){return t.eval()+r.eval()},Additive_sub(t,n,r){return t.eval()-r.eval()},Additive(t){return t.eval()},Multiplicative_mul(t,n,r){return t.eval()*r.eval()},Multiplicative_div(t,n,r){return t.eval()/r.eval()},Multiplicative_mod(t,n,r){return t.eval()%r.eval()},Multiplicative(t){return t.eval()},UnaryExpr_not(t,n){return!n.eval()},UnaryExpr_neg(t,n){return-n.eval()},UnaryExpr(t){return t.eval()},CallExpr_methodCall(t,n,r,s,i,a){const c=t.eval(),l=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(c instanceof ve)switch(l){case"val":return c.val();case"exists":return c.exists();case"hasChild":return c.hasChild(String(u[0]));case"hasChildren":return c.hasChildren(u.length>0?u[0]:void 0);case"isString":return c.isString();case"isNumber":return c.isNumber();case"isBoolean":return c.isBoolean();case"child":return c.child(String(u[0]));case"parent":return c.parent();case"getPriority":return c.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof c=="string"){const d=new kd(c);switch(l){case"matches":return d.matches(u[0]);case"contains":return d.contains(String(u[0]));case"beginsWith":return d.beginsWith(String(u[0]));case"endsWith":return d.endsWith(String(u[0]));case"replace":return d.replace(u[0],String(u[1]));case"toLowerCase":return d.toLowerCase();case"toUpperCase":return d.toUpperCase();default:throw new Error(`Unknown string method: ${l}`)}}throw new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:ni(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:ni(i,String(a))},CallExpr(t){return t.eval()},Primary_paren(t,n,r){return n.eval()},Primary(t){return t.eval()},Array(t,n,r){return n.asIteration().children.map(s=>s.eval())},literal(t){return t.eval()},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()},string_double(t,n,r){return JSON.parse(this.sourceString)},string_single(t,n,r){return jd(n.sourceString)},string(t){return t.eval()},regex(t,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval()},null(t){return null},ident(t,n,r){const s=this.sourceString;if(s in Ae.pathVariableBindings)return Ae.pathVariableBindings[s];switch(s){case"auth":return Ae.auth;case"data":return Ae.data;case"newData":return Ae.newData;case"root":return Ae.root;case"now":return Ae.now;default:return}}}),sr=e,e}function yo(e,t){const n=Mn(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ae=t,_d()(n).eval()}const Sd=cn({operation:to(["read","write","validate"]),path:Ge().min(1).startsWith("/"),auth:Ql([cn({uid:Ge(),token:Er(Gt())}),Xl()]),mockData:Er(Gt()),newData:Gt().optional(),updates:Yl(cn({path:Ge().min(1).startsWith("/"),value:Gt()})).optional()});to(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);cn({allowed:Ks(),unsupported:Ks().optional(),matchedPath:Ge(),matchedRule:Ge(),reason:Ge(),pathVariableBindings:Er(Ge())});function ir(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function $r(e){return e.validate?!0:e.children.some($r)}function ri(e,t,n){return e.length>0||t||n.some(r=>r.length===1)}function Ed(e,t,n,r,s,i,a){let c=null;const l=new Set;if(a&&a.length>0)for(const f of a)l.add(f.path.split("/").filter(Boolean).join("/"));l.add(i.filter(Boolean).join("/"));const u=Array.from(l).map(f=>f.split("/").filter(Boolean));function d(f,p,y,b,v,g){if(y.exists()){const k=f.validate;if(k){if(!k.parsed.valid)c||(c={node:f,rule:k,bindings:b,unsupported:!0});else if(!yo(k.raw,s(p,y,b)))return{node:f,rule:k,bindings:b}}}const w=u.some(k=>k.length<=v.length&&k.every((j,_)=>j===v[_])),x=ir(p).some(k=>!y.child(k).exists());for(const k of f.children){const j=k.path.split("/").filter(Boolean);if(j.length===0)continue;const _=j[j.length-1],N=_.startsWith("$");if(w||g){if(N)for(const A of ir(y)){const R=d(k,p.child(A),y.child(A),{...b,[_]:A},[...v,A],!0);if(R)return R}else if(y.child(_).exists()){const A=d(k,p.child(_),y.child(_),b,[...v,_],!0);if(A)return A}}else if(N){const A=new Set;for(const R of u)R.length>v.length&&v.every((I,C)=>I===R[C])&&A.add(R[v.length]);for(const R of A){const I=d(k,p.child(R),y.child(R),{...b,[_]:R},[...v,R],!1);if(I)return I}if($r(k)&&ri(v,x,u))for(const R of ir(y)){if(A.has(R))continue;const I=d(k,p.child(R),y.child(R),{...b,[_]:R},[...v,R],!0);if(I)return I}}else{const A=_;if(u.some(I=>I.length>v.length&&I[v.length]===A&&v.every((C,S)=>C===I[S]))){const I=d(k,p.child(A),y.child(A),b,[...v,A],!1);if(I)return I}else if(y.child(A).exists()&&$r(k)&&ri(v,x,u)){const I=d(k,p.child(A),y.child(A),b,[...v,A],!0);if(I)return I}}}return null}return d(e,t,n,r,[],!1)??c}function bo(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;for(const i of e.children){const a=i.path.split("/").filter(Boolean);if(a.length===0)continue;const c=a[a.length-1],l=c.startsWith("$");if(l||t[0]===c){const u=l?{...n,[c]:t[0]}:{...n},d=bo(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function Or(e,t,n){if(t.length===0)return n??null;const[r,...s]=t,i=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},a=Object.hasOwn(i,r)?i[r]:null,c=Or(a,s,n);return c==null?delete i[r]:i[r]=c,i}function Cd(e,t,n,r){if(!r||r.length===0)return Or(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=Or(s,a,i.value??null)}return s}class Nd{execute(t,n){const r=Sd.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:i,auth:a,mockData:c,newData:l,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),m=t,f=bo(m,d,{}),p=new ve(c,"/"),y=s==="read"?c:Cd(c,d,l,u),b=new ve(y,"/"),v=(k,j,_)=>{const N={};for(const[A,R]of Object.entries(_))N[A]=R,N[A.slice(1)]=R;return{auth:a?{uid:a.uid,token:a.token}:null,data:k,newData:j,root:p,now:Date.now(),pathVariableBindings:N}};let g;for(const k of f){const j=k.node[s];if(!j)continue;if(!j.parsed.valid){g||(g=k);continue}const _=d.slice(0,k.depth).join("/"),N=p.child(_),A=b.child(_);if(yo(j.raw,v(N,A,k.pathVariableBindings))){if(s==="write"){const I=Ed(m,p,b,{},v,d,u);if(I)return{success:!0,data:{allowed:!1,unsupported:I.unsupported===!0,matchedPath:I.node.path,matchedRule:I.rule.raw,reason:I.unsupported?`Validation rule at '${I.node.path}' contains an expression the simulator cannot evaluate: ${I.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:I.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:k.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:k.pathVariableBindings}}}}if(g){const k=g.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:g.node.path,matchedRule:k.raw,reason:`'${s}' rule at '${g.node.path}' contains an expression the simulator cannot evaluate: ${k.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:g.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const Rd=new Set([".read",".write",".validate",".indexOn"]);function go(e,t,n=[]){const r=ad(e),s=r.valid?wd(e,t,n):r.errors,i=r.valid?pd(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function vo(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const c=e[i];c!==void 0&&(r[a]=go(String(c),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(Rd.has(i)||typeof a!="object"||a===null)continue;const c=t==="/"?`/${i}`:`${t}/${i}`,l=i.startsWith("$")?[...n,i]:[...n];r.children.push(vo(a,c,l))}return r}function wo(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)throw new Error('Invalid rules JSON: "rules" must be an object');return vo(t.rules,"/",[])}function ar(e){return e==="true"?!0:e==="false"?!1:e}function xo(e){const t={};e.read&&(t[".read"]=ar(e.read.raw)),e.write&&(t[".write"]=ar(e.write.raw)),e.validate&&(t[".validate"]=ar(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]]=xo(n)}return t}function Ad(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:xo(e)}}function gs(e,t){return new Nd().execute(e,t)}function je(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class Id{compiled=null;defaultPolicy="deny";setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=wo(t)}hasRules(){return this.compiled!==null}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."]};const i=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},a=gs(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates});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}:{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}:a.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class Dd{tree=new cd;rules=new Id;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new fd;mutations=new ud;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new dd(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function vs(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=si(e),r=si(t);return n!==r?n-r:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===t?0:e?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function si(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const Pd=/^-?(0*)\d{1,10}$/,$d=-2147483648,Od=2147483647;function ii(e){if(Pd.test(e)){const t=Number(e);if(t>=$d&&t<=Od)return t}return null}function yn(e,t){if(e===t)return 0;const n=ii(e),r=ii(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function $t(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 i=s.path.split("/").filter(c=>c.length>0);let a=n;for(const c of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[c]??null}return a}}}function Xe(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,c])=>({key:a,value:c,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,c)=>{if(i)return yn(a.key,c.key);const l=$t(t.orderBy,a.key,a.value,a.priority),u=$t(t.orderBy,c.key,c.value,c.priority),d=vs(l,u);return d!==0?d:yn(a.key,c.key)});for(const a of t.bounds)s=s.filter(c=>Td(a,c,t.orderBy));if(t.limit){const a=t.limit.n;t.limit.kind==="limitToFirst"?s=s.slice(0,a):s=a>=s.length?s:s.slice(s.length-a)}return s}function Td(e,t,n){const s=n?.kind==="key"?yn(t.key,String(e.value)):vs($t(n,t.key,t.value,t.priority),e.value),i=a=>yn(t.key,a);switch(e.kind){case"startAt":return s>0?!0:s<0?!1:e.key===void 0||i(e.key)>=0;case"startAfter":return s>0?!0:s<0||e.key===void 0?!1:i(e.key)>0;case"endAt":return s<0?!0:s>0?!1:e.key===void 0||i(e.key)<=0;case"endBefore":return s<0?!0:s>0||e.key===void 0?!1:i(e.key)<0;case"equalTo":return s!==0?!1:e.key===void 0||i(e.key)===0}}function ai(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Md(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&ht(n.value,s.value)})}function ws(e){const t=new Error(`permission_denied at ${J(L(e))}: Client doesn't have permission to access the desired data.`);return t.code="PERMISSION_DENIED",t}class Ud{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const c=Date.now(),l=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(l.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,ye(l.check),l,{at:c,durationMs:Date.now()-c,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:l.matchedPath,matchedRule:l.matchedRule,pathVariableBindings:l.pathVariableBindings,reason:l.reason,errorCode:l.errorCode};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:l.reasons},reasons:l.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(ws(n))}),()=>{};throw je()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:l,at:c},i,a)}adminOnValue(t,n,r){return this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attach(t,n,r,s,i,a,c){const l=this.state.events.nextListenerId();this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:Date.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const u={id:l,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:c};if(this.state.valueListeners.add(u),this.state.events.listener("attach",u,t,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const d=Xe(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:ai(d),exists:d.length>0,key:this.key(n),rows:d},{initial:!0,query:!0})}else{const d=this.snapshot(n);u.lastValue=d.val,u.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(u,d,{initial:!0})}return()=>{this.state.valueListeners.delete(u),this.state.events.listener("detach",u,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>J(L(r)));for(const r of this.state.valueListeners){const s=J(L(r.path));if(!n.some(c=>Bd(s,c)))continue;if(r.query){const c=Xe(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Md(r.lastWindow??[],c)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=c,this.deliver(r,{val:ai(c),exists:c.length>0,key:this.key(r.path),rows:c},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(ht(r.lastValue??null,i.val)&&r.lastPriorityState===a){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=a,this.deliver(r,i,{})}}off(t,n){const r=J(L(t));for(const s of[...this.state.valueListeners])J(L(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=L(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r});try{t.cb(n)}catch(s){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){try{t.cb(n),this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r})}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function Bd(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function rt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function _t(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function oi(e,t){if(t===void 0)return null;const n=L(e),r=L(t);return r.length!==n.length+1||!n.every((s,i)=>r[i]===s)?null:r[r.length-1]??null}class Ld{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,c){const l=Date.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.tree.snapshot()});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,ye(d.check),d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const f={engine:"rtdb",matchedPath:d.matchedPath,matchedRule:d.matchedRule,pathVariableBindings:d.pathVariableBindings,reason:d.reason,errorCode:d.errorCode};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:f}),a)return queueMicrotask(()=>{c&&c(),a(ws(r))}),()=>{};throw je()}this.state.events.operation(t,"listen",r,"allow",d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const m={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:c};if(this.state.childListeners.add(m),this.state.events.listener("attach",m,t,{event:n,result:"allow",detail:i?{query:i}:void 0}),i){const f=Xe(this.state.tree.read(r),i,this.state.priorities.forChild(r));if(m.lastWindow=f,n==="child_added")for(const{key:p,value:y}of f)this.deliver(m,{key:p,val:y,previousChildName:rt(f,p)},{initial:!0,query:!0})}else if(n==="child_added")for(const{key:f,val:p}of this.directChildren(r)){const y=this.directChildren(r);this.deliver(m,{key:f,val:p,previousChildName:_t(y,f)},{initial:!0})}return()=>{this.state.childListeners.delete(m),this.state.events.listener("detach",m,t,{event:n})}}off(t,n,r){const s=J(L(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||J(L(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=J(L(n.path));t.has(r)||t.set(r,new Map(this.directChildren(r).map(({key:s,val:i})=>[s,i])))}return t}fanOut(t,n){if(this.state.childListeners.size===0)return;const r=new Map;for(const s of this.state.childListeners){if(s.spec){this.fanOutQuery(s,n);continue}const i=J(L(s.path)),a=r.get(i)??[];a.push(s),r.set(i,a)}for(const[s,i]of r){const a=t.get(s)??new Map,c=new Map(this.directChildren(s).map(({key:f,val:p})=>[f,p])),l=[...c].map(([f,p])=>({key:f,val:p})),u=[...a].map(([f,p])=>({key:f,val:p})),d={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,p]of c)a.has(f)?ht(a.get(f),p)||d.child_changed.push({key:f,val:p,previousChildName:_t(l,f)}):d.child_added.push({key:f,val:p,previousChildName:_t(l,f)});for(const[f,p]of a)c.has(f)||d.child_removed.push({key:f,val:p,previousChildName:_t(u,f)});const m=oi(s,n);m!==null&&a.has(m)&&c.has(m)&&d.child_moved.push({key:m,val:c.get(m),previousChildName:_t(l,m)});for(const f of i)for(const p of d[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)?[]:Xe(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}fanOutQuery(t,n){const r=t.lastWindow??[],s=Xe(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(l=>[l.key,l.value])),a=new Map(s.map(l=>[l.key,l.value])),c=[];if(t.event==="child_added")for(const l of s)i.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:rt(s,l.key)});else if(t.event==="child_changed")for(const l of s)i.has(l.key)&&!ht(i.get(l.key),l.value)&&c.push({key:l.key,val:l.value,previousChildName:rt(s,l.key)});else if(t.event==="child_removed")for(const l of r)a.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:rt(r,l.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=t.spec.orderBy.kind==="priority"?oi(t.path,n):null;let u=!1;if(l!==null){const d=s.find(m=>m.key===l);d&&i.has(l)&&(c.push({key:d.key,val:d.value,previousChildName:rt(s,d.key)}),u=!0)}if(!u){const d=new Map(r.map(m=>[m.key,m]));for(const m of s){const f=d.get(m.key);if(!f)continue;const p=$t(t.spec.orderBy,f.key,f.value,f.priority),y=$t(t.spec.orderBy,m.key,m.value,m.priority);vs(p,y)!==0&&c.push({key:m.key,val:m.value,previousChildName:rt(s,m.key)})}}}for(const l of c)this.deliver(t,l,{query:!0})}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:n,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function Fd(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,a="data"in r;let c=!1;i&&a&&(c=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let m=!1;if(u&&d){const p=typeof l=="object",y=Array.isArray(l);p&&(y||(m=!0))}let f=!1;if(c&&m&&(f=!0),f){const p={},y=Object.entries(l);for(const[j,_]of y){const N=typeof _=="string",A=typeof _=="number";let R=!1;A&&Number.isFinite(_)&&(R=!0);let I=!1;N&&(I=!0),R&&(I=!0),I&&(p[j]=_)}const b=r.data;let v=null;b!==void 0&&b!==null&&(v=b);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const _=typeof w=="object",N=Array.isArray(w);let A=!1;if(_&&(N||(A=!0)),A){const R=w;if("rules"in R){const C=R.rules;if(C!==null&&C!==void 0){const D=typeof C=="object",V=Array.isArray(C);let G=!1;D&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:p,rules:x}}}return{data:e,priorities:{},rules:null}}class Vd{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=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=Fd(t);let s={};const i=r.data===null,a=r.data===void 0;let c=!1;i||a||(c=!0),c&&(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.values.fanOut(["/"]),this.children.fanOut(n)}reset(){this.state.resetGeneration+=1,this.restore(null)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const ci="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let li=0;const Fe=new Array(12).fill(0);function qd(e=Date.now()){const t=e===li;li=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=ci.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&&Fe[i]===63;i--)Fe[i]=0;if(i<0)for(let a=0;a<12;a++)Fe[a]=Math.floor(Math.random()*64);else Fe[i]=(Fe[i]??0)+1}else for(let i=0;i<12;i++)Fe[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ci.charAt(Fe[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}const Wd=/[\[\].#$/\u0000-\u001F\u007F]/;function zd(e){return e.length!==0&&!Wd.test(e)}function Kd(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Hd(e){return e===".priority"||e===".value"||e===".sv"}function Gd(e,t){Tr(e,t,"set")}function Tr(e,t,n){if(e===void 0)throw new Error(`${n} failed: value argument contains undefined in property '${t}'`);if(typeof e=="function")throw new Error(`${n} failed: value argument contains a function in property '${t}'`);if(Kd(e))throw new Error(`${n} failed: value argument contains ${String(e)} in property '${t}'`);if(!(e===null||typeof e!="object")){if(Array.isArray(e)){for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=e[r];s!==void 0&&Tr(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Hd(r)&&!zd(r))throw new Error(`${n} failed: value argument contains an invalid key (${r}) in path ${t}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);Tr(s,`${t}/${r}`,n)}}}function ze(e,t){return Gd(e,t),Mr(e)}function Mr(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=Mr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const t={};for(const[n,r]of Object.entries(e)){if(n===".sv"){t[n]=r;continue}const s=Mr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function un(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>un(a));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const a of n)if(/^(0|[1-9]\d*)$/.test(a))s=Math.max(s,Number(a));else{r=!1;break}if(r&&s<2*n.length){const a=[];for(let c=0;c<=s;c++){const l=t[String(c)];a[c]=l===void 0?null:un(l)}return a}const i={};for(const[a,c]of Object.entries(t))i[a]=un(c);return i}function Jd(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function Yd(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function ke(e,t,n){if(Jd(e))return t;if(Yd(e)){const i=e[".sv"].increment;return(typeof n=="number"?n:0)+i}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((i,a)=>ke(i,t,Array.isArray(n)?n[a]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[i,a]of Object.entries(e))s[i]=ke(a,t,r?r[i]:void 0);return s}function ui(){return new Error("permission_denied")}class Qd{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}run(t,n,r,s){const i=s?.applyLocally!==!1,a=L(n),c=a.length===0?null:a[a.length-1];let l=null,u,d=0,m=!1;do{d+=1;const x=this.state.mutations.begin();l=this.state.tree.read(n);const k=l===null?null:un(De(l));let j=!1;try{u=r(k),j=this.state.mutations.conflictsSince(x,n)}finally{this.state.mutations.release(x)}if(!j||u===void 0){m=!0;break}}while(d<25);if(!m)throw new Error("maxretry");const f=this.state.events.nextGroupId("transaction");if(u===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:f,groupKind:"transaction",resourceBefore:{data:l,exists:l!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:l,key:c};const p=Date.now(),y=ze(ke(u,p,l),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),k=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),_=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(_);const N=Date.now(),A=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(A.check!=="allow"){this.state.events.operation(t,"transaction",n,ye(A.check),A,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const R=this.children.snapshotParents();throw this.state.tree.restore(x),this.state.priorities.restore(k),this.values.fanOut([n]),this.children.fanOut(R),ui()}return this.recordCommit(t,n,u,l,y,f,p,N,!0,A),{committed:!0,val:y,key:c}}const b=Date.now(),v=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:y});if(v.check!=="allow")throw this.state.events.operation(t,"transaction",n,ye(v.check),v,{at:b,durationMs:Date.now()-b,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),ui();this.state.events.operation(t,"transaction",n,"allow",v,{at:b,durationMs:Date.now()-b,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const g=this.state.priorities.get(n),w=this.children.snapshotParents();return this.state.tree.write(n,y),this.state.priorities.replace(n,g),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(w),this.finishEvents(t,n,u,l,y,f,p,!1),this.state.notifyWrite(),{committed:!0,val:y,key:c}}recordCommit(t,n,r,s,i,a,c,l,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:l,durationMs:Date.now()-l,origin:"transaction",request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:a,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,a,c,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,c,l){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:c},detail:{committed:!0,applyLocally:l}}),this.state.events.mutation(t,"transaction",_e(n),{before:s,after:i,detail:{committed:!0}})}}class Xd{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(mn(n),this.state.tree.read(t)===null)return;const r=this.children.snapshotParents(),s=this.state.priorities.get(t)!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),s&&this.values.fanOut([t]),this.children.fanOut(r,s?t:void 0),this.state.notifyWrite()}set(t,n,r){mn(r);const s=this.state.tree.read(n),i=Date.now(),a=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:s}),c=this.state.priorities.get(n),l={at:i,durationMs:Date.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:c}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,ye(a.check),a,l),je();if(this.state.events.operation(t,"setPriority",n,"allow",a,l),s===null)return;const u=this.children.snapshotParents(),d=c!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u,d?n:void 0),d&&(this.state.events.commit(t,"setPriority",n,{data:r,priorState:c,nextState:r,detail:{priority:r,priorPriority:c}}),this.state.events.mutation(t,"setPriority",_e(n),{before:c,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function di(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class Zd{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new Xd(t,n,r)}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t))this.state.tree.write(n,ze(ke(r,Date.now()),n==="/"?"":n));this.state.mutations.mark("/"),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,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=Xe(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:di(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){mn(r);const i=Date.now(),a=this.state.tree.read(t),c=ze(ke(n,i,a),t==="/"?"":t),l=c===null?"remove":"set";this.state.events.operation(null,l,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:c,exists:c!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),m=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,c),this.state.priorities.replace(t,c===null?null:r);const f=m!==this.state.priorities.stateAtOrBelow(t);this.changed([t],u,f?t:void 0);const p=this.state.tree.read(t);this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:a,nextState:p,replay:{requestTime:i},detail:s?{admin:!0,priority:r,priorPriority:d}:{admin:!0}}),this.state.notifyWrite()}adminUpdate(t,n){const r=Date.now(),s=this.state.tree.read(t),i=this.resolvePatch(t,n,r),a=Object.keys(n).some(u=>u.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const c=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(i).map(([u,d])=>[L(u).at(-1),d]))),this.state.priorities.applyUpdate(Object.entries(i).map(([u,d])=>({path:u,value:d}))),this.changed(Object.keys(i),c);const l=a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:l}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=Date.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,ye(i.check),i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),je();return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=Date.now(),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,ye(i.check),i,{at:s,durationMs:Date.now()-s,request:{query:r}}),je();const a=Xe(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:di(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){mn(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)}validateSet(t,n,r){const s=ze(ke(r,Date.now(),this.state.tree.read(n)),n==="/"?"":n);if(this.writeEvaluation(t,n,s).check!=="allow")throw je()}validateUpdate(t,n,r){const s=this.state.tree.snapshot(),i=Object.entries(r).map(([a,c])=>{const l=J([...L(n),...L(a)]);return{path:l,value:ze(ke(c,Date.now(),this.state.tree.read(l)),l)}});for(const a of i)if(this.state.rules.evaluate("write",a.path,{auth:t,mockData:s,newData:a.value,updates:i}).check!=="allow")throw je()}update(t,n,r){const s=Date.now(),i=this.resolvePatch(n,r,s),a=Object.keys(r).some(y=>y.includes("/")),c=this.state.tree.snapshot(),l=Object.entries(i).map(([y,b])=>({path:y,value:b})),u=Object.fromEntries(Object.entries(i).map(([y,b])=>[L(y).at(-1),b])),d=this.state.events.nextGroupId("update");for(const y of l){const b=Date.now(),v=this.state.tree.read(y.path),g=this.state.rules.evaluate("write",y.path,{auth:t,mockData:c,newData:y.value,updates:l}),w={at:b,durationMs:Date.now()-b,origin:"batch",request:{data:y.value,resourceData:y.value},resourceBefore:{data:v,exists:v!==null},resourceAfter:{data:y.value,exists:y.value!==null},groupId:d,groupKind:"batch",detail:a?{multiPath:!0,rootPath:_e(n)}:{multiPath:!1,rootPath:_e(n),key:L(y.path).at(-1)}};if(g.check!=="allow")throw this.state.events.operation(t,"update",y.path,ye(g.check),g,w),je();this.state.events.operation(t,"update",y.path,"allow",g,w)}const m=this.state.tree.read(n),f=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,u),this.state.priorities.applyUpdate(l),this.changed(Object.keys(i),f);const p=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:p,groupId:d,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.events.mutation(t,"update",_e(n),{after:a?i:u,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,a){const c=Date.now(),l=ze(ke(r,c,this.state.tree.read(n)),n==="/"?"":n),u=this.state.tree.read(n),d=this.state.priorities.get(n),m=Date.now(),f=this.writeEvaluation(t,n,l),p={at:m,durationMs:Date.now()-m,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:l,exists:l!==null}};if(f.check!=="allow")throw this.state.events.operation(t,s,n,ye(f.check),f,p),je();this.state.events.operation(t,s,n,"allow",f,p);const y=this.children.snapshotParents(),b=this.state.priorities.stateAtOrBelow(n);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i);const v=b!==this.state.priorities.stateAtOrBelow(n);this.changed([n],y,v?n:void 0);const g=this.state.tree.read(n),w=g===null?"remove":s;this.state.events.commit(t,w,n,{data:r,priorState:u,nextState:g,replay:{requestTime:c},...a?{detail:{priority:i,priorPriority:d}}:{}}),this.state.events.mutation(t,w,_e(n),{before:u,after:g}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const a=J([...L(t),...L(s)]);return[a,ze(ke(i,r,this.state.tree.read(a)),a)]}))}changed(t,n,r){this.state.mutations.mark(t),this.values.fanOut(t),this.children.fanOut(n,r)}cancelDeniedListeners(){const t=this.state.tree.snapshot(),n=[];for(const s of[...this.state.valueListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.valueListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,ye(i.check),i,{origin:"listener"});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),n.push(s)}const r=[];for(const s of[...this.state.childListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.childListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,ye(i.check),i,{origin:"listener",detail:{event:s.event}});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:s.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),r.push(s)}for(const s of[...n,...r]){try{s.onCanceled&&s.onCanceled()}catch{}try{s.cancelCallback&&s.cancelCallback(ws(s.path))}catch{}}}readEvaluation(t,n){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()})}writeEvaluation(t,n,r){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:r})}}class ef{state;values;children;writes;transactions;persistence;constructor(t){this.state=new Dd(t),this.values=new Ud(this.state),this.children=new Ld(this.state),this.writes=new Zd(this.state,this.values,this.children),this.transactions=new Qd(this.state,this.values,this.children),this.persistence=new Vd(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){this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){this.writes.adminUpdate(t,n)}adminRemove(t){this.writes.adminRemove(t)}adminSetPriority(t,n){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)}set(t,n,r){this.writes.set(t,n,r)}setWithPriority(t,n,r,s){this.writes.setWithPriority(t,n,r,s)}update(t,n,r){this.writes.update(t,n,r)}remove(t,n){this.writes.remove(t,n)}setPriority(t,n,r){this.writes.setPriority(t,n,r)}validateSet(t,n,r){this.writes.validateSet(t,n,r)}validateUpdate(t,n,r){this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,a){return this.values.onValue(t,n,r,s,i,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,a,c){return this.children.onChild(t,n,r,s,i,a,c)}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(){this.persistence.reset()}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return qd()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const fi=new WeakMap;function tf(e){let t=fi.get(e);if(t)return t;t=new ef(e),fi.set(e,t);const n=t;return e.onEvent(r=>{r.kind==="session_boundary"&&r.phase==="reset"&&n.invalidateConnectionQueues()}),e.registerPersistableService("rtdb",{snapshot:()=>n.exportPersistenceState(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.resetTree()}}),t}const Ur=Symbol("pyric/database/target"),nf=new WeakMap;function rf(e){let t;if(Ur in e?t=e[Ur]:t=nf.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}function jo(e){return e&&typeof e=="object"&&Ur in e?rf(e).backend:tf(e)}function ko(e){return jo(e).getActiveRules()}function hi(e){return jo(e).snapshotState()}const pi=Symbol("pyric/firestore/followsCurrentUser"),mi=Symbol("pyric/firestore/authSessionScope"),_o=new WeakMap;function sf(e){return _o.get(e)?.raw??e}const af=new WeakMap,yi=new WeakMap;function Br(e,t,n,r,s){_o.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function of(e,t){const n=Cr(e),r=Cr(t);return n.isStructurallyEqual?.(r)??n===r}function cf(e,t,n,r){const s=e,i=(yi.get(s)??[]).filter(c=>c.query.deref()!==void 0),a=i.find(c=>{const l=c.query.deref();return l!==void 0&&of(l,t)});if(a!==void 0){const c=lf(a.docs,n)&&a.metadata.fromCache===r.fromCache&&a.metadata.hasPendingWrites===r.hasPendingWrites;return a.docs=n,a.metadata=r,c?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),yi.set(s,i),"initial"}function lf(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&bu(n.data,s.data)})}function Lr(e,t,n,r,s){const i=t,a=d=>({path:d.ref?.path??"",data:bs(d.data?.(),n)}),c=Object.freeze((i.docs??[]).map(a)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...a(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});af.set(e,{target:n,query:r,converter:Pn(r)??null,source:s,...s==="read"?{readPhase:cf(n,r,c,u)}:{},metadata:u,docs:c,changes:l})}function bn(e,t){const n=e,r=n.data.bind(e);return Object.defineProperty(n,"data",{value:()=>ao(r()),configurable:!0,writable:!0}),t&&n.ref?.path&&Object.defineProperty(n,"metadata",{value:Oe(t).snapshotMetadata(n.ref.path),configurable:!0}),e}function So(e,t,n,r){const s={id:e.id,ref:e.ref,exists:e.exists,metadata:Oe(n).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const a=ao(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:Oe(n).snapshotMetadata(e.ref.path),data:()=>a};return t.fromFirestore(c)}};return Je(s,n),Je(e.ref,n),Fr(e.ref,n),Br(s,e,n,t,r),s}function Bn(e,t){if(!e||typeof e!="object")return e;Je(e,t);const n=e;if(n.ref&&(Je(n.ref,t),Fr(n.ref,t)),bi(n),Array.isArray(n.docs))for(const r of n.docs)r&&(Je(r,t),Br(r,r,t,null,"query-child")),r?.ref&&(Je(r.ref,t),Fr(r.ref,t)),r&&bi(r);else n.ref&&Br(e,e,t,null,"document");return e}function Fr(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Gs.get(e),s=r??ys(t).doc(n);r===void 0&&Gs.set(e,s),Zl(e,n,t,s),t.kind==="sandbox-live"&&oo.set(s,i=>i.doc(n))}catch{}}function bi(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{}}async function Eo(e){const t=$n(e),n=Oe(t);n.markStarted();const r=Pn(e),s=await vu(t,e).get();return n.cachePath(e.path),r?So(s,r,t,"document"):(Bn(s,t),bn(s,t))}async function gn(e){const t=$n(e),n=Oe(t);n.markStarted();const r=Pn(e),s=await gu(t,e).get();if(n.cacheQuery(e),r){const a=r,c=s.docs.map(u=>So(u,a,t,"query-child")),l=Je({size:c.length,empty:c.length===0,docs:c,metadata:n.querySnapshotMetadata()},t);for(const u of c)n.cachePath(u.ref.path);return Lr(l,s,t,e,"read"),l}Bn(s,t);const i=s.docs;for(const a of i)n.cachePath(a.ref.path),bn(a,t);return Object.defineProperty(s,"metadata",{value:n.querySnapshotMetadata(),configurable:!0}),Lr(s,s,t,e,"read"),s}function Co(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function vn(e,...t){const n=$n(e),r=Pn(e),s=wu(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw Js(u)}const c=u=>{let d=s(u);for(const m of i)d=m.applySandbox(d);return d};try{a=c(ys(n))}catch(u){throw Js(u)}const l=xu(a,n,u=>c(u));return r?ju(l,n,r):l}function uf(e,t,n){return No(Co(e),t,n,!1)}function No(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=bs(n,i,t==="in"||t==="not-in");return No(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function gi(e,t){const n=Co(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function wn(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function df(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 ff(...e){return df(e)?Ro(e[0],!1,!0):Ao(e,!1,!0)}function Ro(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=sf(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Ro(a,t,n,!0)}}}function Ao(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=>Ao(e.map(i=>bs(i,s).executionValue),t,n,!0)}}function hf(e,t,n,r){const s=$n(e);Oe(s).markStarted();const i=mf(s,e),a=yf(t,n,r,s,e),c=bf(a,s),l=c.length===3?i.onSnapshot(c[0],c[1],c[2]):c.length===2?i.onSnapshot(c[0],c[1]):i.onSnapshot(c[0]);if(!s.own)return l;let u=!1;const d=()=>{u||(u=!0,l())},m=()=>{u||(d(),pf(c)?.(new gt("aborted","The operation was aborted.")))},f=s.own(m);return()=>{f(),d()}}function pf(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 mf(e,t){const n=Cr(t);if(e.kind==="sandbox")return n;const r=oo.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ys(e))}function Io(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 yf(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!Io(e)){const a=t;return typeof a=="function"?[e,vi(a,r,s),n??Vr]:a&&typeof a=="object"?[e,wi(a,r,s)]:[e]}return typeof e=="function"?[vi(e,r,s),t??Vr]:e&&typeof e=="object"?[wi(e,r,s)]:[e]}function bf(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Io(n)?[{...n,[pi]:!0,...t.authScope?{[mi]:t.authScope}:{}},...e.slice(1)]:[{[pi]:!0,...t.authScope?{[mi]:t.authScope}:{}},...e]}function Do(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&bn(e,t),Array.isArray(r.docs)){for(const s of r.docs)bn(s,t);Lr(e,e,t,n,"listener")}return e}function Vr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function vi(e,t,n){return r=>{e(Do(Bn(r,t),t,n)),Oe(t).notifySnapshotDelivered()}}function wi(e,t,n){return{...e,next:e.next?r=>{e.next(Do(Bn(r,t),t,n)),Oe(t).notifySnapshotDelivered()}:void 0,error:e.error??Vr}}const Re={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"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},gf=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],vf={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...gf]},value:{}},required:["field","op","value"]};function wf(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:Re},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=He(s,r.path),a=await Eo(i),c=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:c?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:c,data:c?a.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:Re},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=It(s,r.collection),a=[];r.orderBy&&a.push(gi(r.orderBy)),r.limit&&a.push(wn(r.limit));const c=await gn(vn(i,...a));return{ok:!0,summary:`${c.size} docs in ${r.collection}`,data:{docs:c.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:Re},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await fn(He(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:Re},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await co(It(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:Re},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Ys(He(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:Re},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await Nr(He(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:Re},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 a=He(s,i.path);i.op==="set"?await fn(a,i.data??{}):i.op==="update"?await Ys(a,i.data??{}):await Nr(a)}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:vf,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Re},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=It(s,r.collection),a=r.where.map(l=>uf(l.field,l.op,l.value));r.orderBy&&a.push(gi(r.orderBy)),r.limit&&a.push(wn(r.limit));const c=await gn(vn(i,...a));return{ok:!0,summary:`${c.size} matches in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function xf(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=eu(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 jf="modulepreload",kf=function(e){return"/__pyric/ui/"+e},xi={},Po=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");s=a(n.map(u=>{if(u=kf(u),u in xi)return;xi[u]=!0;const d=u.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":jf,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,y)=>{f.addEventListener("load",p),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function $o(e){return e.kind==="session_boundary"&&e.phase==="reset"}function _f(e,t){return $o(t)?[t]:[...e,t]}const Oo=h.createContext(null),To={status:"disabled",handles:null,events:[]};function Sf({children:e}){return o.jsx(Oo.Provider,{value:To,children:e})}function Ue(){return h.useContext(Oo)??To}function Ke(e,t){return`${e.replace(/\/$/,"")}${t}`}const or=new Map;let cr=null;function Ef(e){return e||(cr||(cr=`studio-writer-${Math.random().toString(36).slice(2)}`),cr)}function Mo(e){return{token:e?.token,writerId:e?.writerId}}async function Uo(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=or.get(n);if(r)return r;const s=fetch(Ke(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||or.delete(n),i));return or.set(n,s),s}async function Bo(e,t,n=!1){const r={},{token:s,writerId:i}=Mo(t);n&&(r["x-pyric-writer"]=Ef(i));const a=await Uo(e,s);return a&&(r["x-pyric-session-token"]=a),r}function Cf(e,t){const n=e,{token:r}=Mo(t),s=(i=!1)=>Bo(n,t,i);return{async read(i){const a=await s(!1),c=await fetch(Ke(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:a});if(c.status===404)return null;if(!c.ok)throw new Error(`workspace.read(${i}) → ${c.status}`);return c.text()},async write(i,a){const c=await s(!0),l=await fetch(Ke(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:c,body:a});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const a=await s(!1),c=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch(Ke(n,`/__pyric/workspace/list${c}`),{headers:a});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async remove(i){const a=await s(!0),c=await fetch(Ke(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:a});if(!c.ok)throw new Error(`workspace.remove(${i}) → ${c.status}`)},watch(i){let a=null,c=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Uo(n,r).then(u=>{if(c)return;const d=u?Ke(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):Ke(n,"/__pyric/workspace/watch");a=new EventSource(d),a.addEventListener("change",l)}),()=>{c=!0,a&&(a.removeEventListener("change",l),a.close())}}}}function St(e,t){return`${e.replace(/\/$/,"")}${t}`}function Nf(e,t){const n=e,r=(s=!1)=>Bo(n,t,s);return{async list(){const s=await r(!1),i=await fetch(St(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),a=await fetch(St(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!a.ok)throw new Error(`projects.open(${s}) → ${a.status}`);return{meta:await a.json(),workspace:Cf(n,t)}},async create(s){const a={...await r(!0),"content-type":"application/json"},c=await fetch(St(n,"/__pyric/projects"),{method:"POST",headers:a,body:JSON.stringify(s)});if(!c.ok)throw new Error(`projects.create() → ${c.status}`);return await c.json()},async update(s,i){const c={...await r(!0),"content-type":"application/json"},l=await fetch(St(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:c,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),a=await fetch(St(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!a.ok)throw new Error(`projects.remove(${s}) → ${a.status}`)}}}function Rf(e,t){return`${e.replace(/\/$/,"")}${t}`}function lr(e){return/auth/i.test(e)?"auth":"firestore"}function Af(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=l=>Rf(t,`/__pyric/state?section=${lr(l)}`),a=async l=>{const u=lr(l),d=s.get(u);if(d)return d;const m=await fetch(i(l));let f=new Map;if(m.ok){const p=await m.text();p&&p!=="null"&&(f=tu(p))}else if(m.status!==404)throw new Error(`persistence.read(${l}) → ${m.status}`);return s.set(u,f),f},c=async(l,u)=>{const d=await fetch(i(l),{method:"POST",headers:r,body:nu(u)});if(d.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!d.ok)throw new Error(`persistence.write(${l}) → ${d.status}`)};return{async getRecord(l,u){return(await a(l)).get(u)??null},async listRecords(l){return[...(await a(l)).keys()]},async putRecords(l,u){const d=await a(l);for(const[m,f]of u)d.set(m,f);await c(l,d)},async deleteRecords(l,u){const d=await a(l);for(const m of u)d.delete(m);await c(l,d)},async clear(l){s.set(lr(l),new Map);const u=await fetch(i(l),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${l}) → ${u.status}`)}}}const If="local";function Df(){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 a of e.keys())s&&!a.startsWith(s)||i.push({path:a,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},watch(r){return t.add(r),()=>t.delete(r)}}}function Pf(){const e=Df();let t={id:If,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(){}}}const $f="/__pyric/sdk/worker.js",Ie="pyric-shared-worker",Of="/__pyric/ui/studio";function Lo(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:Of,worker:{url:$f,name:Ie,servedEpoch:t}}}const xn="pyric:worker-generation",Et="pyric:worker-generation-probe";function Tf(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Ie}:${n}`:Ie;try{const r=t.getItem(xn);return r&&/^[a-f0-9]{16}$/.test(r)?`${Ie}:${r}`:n?(t.setItem(xn,n),`${Ie}:${n}`):Ie}catch{return n?`${Ie}:${n}`:Ie}}function Mf(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(xn,e),t.getItem(xn)!==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 Uf(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(Et);if(e.setItem(Et,"ok"),e.getItem(Et)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(Et):e.setItem(Et,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 Bf(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}}function Lf(){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 Fo=new WeakMap;let qr;function Ff(e,t,n=Lf()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,c={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(c.deleted)throw new gt("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;c.assertAlive();const m=u();return i.set(l,m),m},onDelete(l){return c.deleted?(l(),()=>{}):(a.add(l),()=>a.delete(l))},deleted:!1};return Fo.set(e,c),c}function Vf(e){qr=e}ku({resolve(e,t){const n=typeof e=="object"&&e!==null?Fo.get(e):void 0;if(n)return n},defaultApp(){if(!qr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return qr()}});const qf="[DEFAULT]",Wf=new Map;function zf(e,t){return new gt(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function Kf(e){return zf("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function Hf(e=qf){const t=Wf.get(e);if(!t)throw Kf(e);return t.app}Vf(Hf);let Gf=0,Jf=0;function M(){return`op-${++Gf}`}function vt(){return`sub-${++Jf}`}const pt=new Map,Ot=new Map,Tt=new Map,wt=new WeakSet,Wr=new Set;function Yf(e){return Wr.add(e),()=>Wr.delete(e)}function Vo(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Vt(e,t,n,r){return wt.has(e)?!1:(Ot.set(t,n),e.postMessage(r),!0)}function Qf(e,t,n,r){return wt.has(e)?!1:(Tt.set(t,{port:e,next:n}),e.postMessage(r),!0)}function qt(e,t){Ot.delete(t),Tt.delete(t),wt.has(e)||e.postMessage({t:"unsub",subId:t})}function Xf(e){wt.add(e);const t=Vo();for(const[n,r]of[...pt])r.port===e&&(pt.delete(n),r.reject(t));for(const[n,r]of[...Ot])r.port===e&&(Ot.delete(n),r.service==="firestore"&&r.error?.(new gt("aborted","The operation was aborted.")));for(const[n,r]of[...Tt])r.port===e&&Tt.delete(n);e.onmessage=null}function ji(e,t){if(t.denialContext===void 0||typeof fetch!="function")return;const n={kind:e,code:t.code,message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function xs(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=pt.get(n.id);if(!r)return;if(pt.delete(n.id),n.ok)r.resolve(n.value);else{const s=new Error(n.error.message);s.code=n.error.code,n.error.denialContext!==void 0&&(s.denialContext=n.error.denialContext),n.error.aiEnvelope!==void 0&&(s.aiEnvelope=n.error.aiEnvelope),ji("read",s),r.reject(s)}}else if(n.t==="snap"){const r=Ot.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const i=s.__error,a=new Error(i.message);a.code=i.code,i.denialContext!==void 0&&(a.denialContext=i.denialContext),i.aiEnvelope!==void 0&&(a.aiEnvelope=i.aiEnvelope),ji("listener",a),r.error?r.error(a):console.error("pyric/firestore: Uncaught Error in snapshot listener:",a);return}r.next(n.value)}else if(n.t==="event"){const r=Tt.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of Wr)r(n)}}const Pt="pyric:auth-lens";function Zf(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"?!0:t.mode==="as"&&typeof t.uid=="string"}function qo(e){if(Zf(e))return e}function eh(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(Pt);if(!e)return;const t=JSON.parse(e),n=qo(t);if(n)return n;sessionStorage.removeItem(Pt);return}catch{try{sessionStorage.removeItem(Pt)}catch{}return}}let Se=eh();const th=new Set;function ki(e){if(Se=qo(e),typeof sessionStorage<"u")try{Se?sessionStorage.setItem(Pt,JSON.stringify(Se)):sessionStorage.removeItem(Pt)}catch{}for(const t of[...th])try{t(Se)}catch(n){console.error("Error in subscribeLens listener:",n)}}function nh(){return Se}let zr;function rh(e){zr=e}function js(e){return zr&&(e.t==="op"||e.t==="sub")?{...e,issuer:zr}:e}function ks(e,t){return wt.has(e)?Promise.reject(Vo()):new Promise((n,r)=>{const s=t;pt.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function z(e,t){return ks(e,js(t))}function Wo(e,t,n,r){const s=t.id;let i;const a=new Promise((c,l)=>{i=setTimeout(()=>{pt.delete(s)&&l(new Error(r))},n)});return Promise.race([z(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function he(e,t){if(wt.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new gt("failed-precondition","The client has already been terminated."));const n=Se?{...t,actAs:Se}:t;return z(e,n)}async function sh(e,t,n={}){const r=n.timeoutMs??12e3;await Wo(e.port,{t:"op",id:M(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function ih(e){return Yf(t=>e(t.epoch))}function ah(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 a=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${a}`))});const s=r.port;return xs(s),s.start(),{__kind:"client-db",port:s}}async function oh(e,t={}){const n=M(),r=t.timeoutMs??2e3;return(await Wo(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function ch(e){return(await z(e.port,{t:"op",id:M(),method:"getVersion"})).instanceId??""}async function lh(e){return(await z(e.port,{t:"op",id:M(),method:"exportState"})).bundle}async function uh(e,t){await z(e.port,{t:"op",id:M(),method:"importState",bundle:t})}async function dh(e,t){await z(e.port,{t:"op",id:M(),method:"saveBranch",name:t})}async function fh(e){return(await z(e.port,{t:"op",id:M(),method:"listBranches"})).branches??[]}async function hh(e,t){await z(e.port,{t:"op",id:M(),method:"switchBranch",name:t})}async function ph(e,t){await z(e.port,{t:"op",id:M(),method:"deleteBranch",name:t})}async function mh(e,t,n){return await z(e.port,{t:"tool",id:M(),name:t,args:n})}function yh(e,t){return ks(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:M()})}function bh(e,t,n){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=vt();return Vt(e.port,r,{port:e.port,next:n,error:i=>n({__error:{code:i.code??"unknown",message:i instanceof Error?i.message:String(i)}})},{...t,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{qt(e.port,r)}}function gh(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const vh=[];function wh(e){for(const t of[...vh])t.port===e&&t.close()}const xh=5e3;function jh(){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 kh(e,t={}){let n;try{const r=ks(e.port,{t:"disconnect",id:M()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(jh()),t.ackTimeoutMs??xh)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),wh(e.port),Xf(e.port),e.port.close()}}function _s(e){return e.split("/").at(-1)??e}function _h(e,...t){const n=("port"in e,e.port);let r;if(e.__kind==="client-db"){if(t.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const i=e.descriptor.path;r=t.length>0?`${i}/${t.join("/")}`:i}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:_s(r),path:r}}function Sh(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("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:_s(r),path:r}}function Eh(e){return{_descriptor:{kind:"limit",n:e}}}function Ch(...e){return{_descriptor:{kind:"startAfter",values:e}}}function Nh(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),r=e.__kind==="query"?e.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...t.map(i=>i._descriptor)]},port:e.port}}function Rh(e){return ru(JSON.parse(e.json))}const zo=8*1024*1024;function Ah(e,t){const n=new Error(`${t} is ${e} bytes — over the ${zo/1048576} MiB storage op cap (MAX_STORAGE_OP_BYTES). Streaming/resumable transfers are not supported on the sandbox backend; split the object or keep it under the cap.`);return n.code="payload-too-large",n}function Ih(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 Dh(e){return Rh(e)}function Ss(e,t){const n=e.exists&&e.data?Dh(e.data):void 0,r=e.path??e.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:t,id:e.id,path:r};return{id:e.id,path:r,ref:s,exists:()=>e.exists,data:()=>n}}function Ko(e,t){const n=e.docs.map(r=>Ss(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function Ph(e){const t=await he(e.port,{t:"op",id:M(),method:"getDoc",path:e.descriptor.path});return Ss(t,e.port)}async function $h(e){const t=await he(e.port,{t:"op",id:M(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return Ko(t,e.port)}async function Oh(e){return(await he(e.port,{t:"op",id:M(),method:"listRootCollections"})).ids}async function Th(e,t){return(await he(e.port,{t:"op",id:M(),method:"listSubcollections",docPath:t})).ids}function Mh(e,t,n){const r=vt(),s=e.port,i={port:s,service:"firestore",next:l=>{const u=l;"docs"in u?t(Ko(u,s)):t(Ss(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!Vt(s,r,i,js(Se?{t:"sub",subId:r,target:a,actAs:Se}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{qt(s,r)}}async function Uh(e,t,n){await he(e.port,{t:"op",id:M(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function Bh(e){await he(e.port,{t:"op",id:M(),method:"deleteDoc",path:e.descriptor.path})}async function Lh(e,t){const n=await he(e.port,{t:"op",id:M(),method:"addDoc",collectionPath:e.descriptor.path,data:t});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:e.port,id:n.id,path:n.path}}async function Fh(e,t){return await z(e.port,{t:"op",id:M(),method:"admin.listDocuments",path:t})}function Vh(e,t){const n=vt(),r=e.port;return Qf(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{qt(r,n)}}async function qh(e){return await z(e.port,{t:"op",id:M(),method:"getSnapshot"})}async function Wh(e){return await z(e.port,{t:"op",id:M(),method:"resetAll"})??{errors:[]}}const zh=15e3;function Kh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function _i(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function Si(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function Hh(){return Kh()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ei(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Ci(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function Gh(e){const{db:t,kind:n}=e,r=e.clientId??Hh(),s=e.heartbeatIntervalMs??zh;let i=!1,a=null;const c=()=>{z(t.port,{t:"op",id:M(),method:"presence.register",clientId:r,kind:n,route:Ei(),visibility:Ci()}).catch(()=>{})},l=()=>{z(t.port,{t:"op",id:M(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{z(t.port,{t:"op",id:M(),method:"presence.update",clientId:r,route:Ei(),visibility:Ci()}).catch(()=>{})},d=()=>{z(t.port,{t:"op",id:M(),method:"presence.disconnect",clientId:r}).catch(()=>{})};c(),_i()&&document.addEventListener("visibilitychange",u),Si()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",m),a=setInterval(()=>{i||l()},s));function m(){f()}function f(){i||(i=!0,a!=null&&(clearInterval(a),a=null),_i()&&document.removeEventListener("visibilitychange",u),Si()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",m)),d())}return{clientId:r,kind:n,stop:f}}function Jh(e,t){const n=vt();return Vt(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{qt(e.port,n)}}const Yh=Symbol("pyric.clientUser.port");function Qh(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:t.photoURL,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await z(e,{t:"op",id:M(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await z(e,{t:"op",id:M(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,Yh,{value:e,enumerable:!1}),n}function Xh(e,t){return t?Qh(e,t):null}function Zh(e,t){let n;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")n=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 (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),xs(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=vt();return Vt(n,s,{port:n,next:i=>{r.currentUser=Xh(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function ep(e){return await z(e.port,{t:"op",id:M(),method:"auth.listUsers"})}async function tp(e,t){return await z(e.port,{t:"op",id:M(),method:"auth.adminCreateUser",request:t})}async function np(e,t,n){return await z(e.port,{t:"op",id:M(),method:"auth.adminUpdateUser",uid:t,request:n})}async function rp(e,t){await z(e.port,{t:"op",id:M(),method:"auth.adminDeleteUser",uid:t})}async function sp(e){await z(e.port,{t:"op",id:M(),method:"auth.adminClearUsers"})}async function ip(e){return await z(e.port,{t:"op",id:M(),method:"auth.getProviderConfig"})}async function ap(e,t,n){await z(e.port,{t:"op",id:M(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const Kr="pyric-storage",ee="pyric-default";function ne(e,t){return`${e}/${t}`}function jn(e){const t=e.indexOf("/");return t===-1?null:{bucket:e.slice(0,t),path:e.slice(t+1)}}function op(e){return e?`${Kr}:${e}`:Kr}const cp=1,pe="blobs",ae="metadata";async function lp(e=Kr,t){try{const n=await fp(e);return new dp(n,t)}catch{return new up(t)}}class up{blobs=new Map;metadata=new Map;_defaultBucket;constructor(t){this._defaultBucket=t}async put(t,n,r){const s=r.bucket||this._defaultBucket||ee;this._defaultBucket||(this._defaultBucket=s),r.bucket||(r.bucket=s);const i=ne(s,t);this.blobs.set(i,n),this.metadata.set(i,r)}async getBlob(t,n){if(n)return this.blobs.get(ne(n,t));const r=this._defaultBucket??ee,s=this.blobs.get(ne(r,t));if(s!==void 0)return s;if(r!==ee){const i=this.blobs.get(ne(ee,t));if(i!==void 0)return i}for(const[i,a]of this.blobs.entries()){const c=jn(i);if(c&&c.path===t)return a}}async getMetadata(t,n){if(n)return this.metadata.get(ne(n,t));const r=this._defaultBucket??ee,s=this.metadata.get(ne(r,t));if(s!==void 0)return s;if(r!==ee){const i=this.metadata.get(ne(ee,t));if(i!==void 0)return i}for(const[i,a]of this.metadata.entries()){const c=jn(i);if(c&&c.path===t)return a}}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??ee;n.bucket||(n.bucket=s),this.metadata.set(ne(s,t),n)}async delete(t,n){const r=n??this._defaultBucket??ee;this.blobs.delete(ne(r,t)),this.metadata.delete(ne(r,t))}async listByPrefix(t,n){const s=`${n??this._defaultBucket??ee}/${t}`,i=[],a=Array.from(this.metadata.keys()).sort();for(const c of a)if(c.startsWith(s)){const l=this.metadata.get(c);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)}close(){}scoped(t){return new Ln(this,t)}}class dp{db;_defaultBucket;constructor(t,n){this.db=t,this._defaultBucket=n}async put(t,n,r){const s=r.bucket||this._defaultBucket||ee;this._defaultBucket||(this._defaultBucket=s),r.bucket||(r.bucket=s);const i=ne(s,t),a=this.db.transaction([pe,ae],"readwrite");a.objectStore(pe).put(n,i),a.objectStore(ae).put(r,i),await Jt(a)}async getBlob(t,n){const s=this.db.transaction(pe,"readonly").objectStore(pe);if(n)return Ve(s.get(ne(n,t)));const i=this._defaultBucket??ee,a=await Ve(s.get(ne(i,t)));if(a!==void 0)return a;if(i!==ee){const c=await Ve(s.get(ne(ee,t)));if(c!==void 0)return c}return new Promise((c,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){c(void 0);return}const m=String(d.key),f=jn(m);if(f&&f.path===t){c(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getMetadata(t,n){const s=this.db.transaction(ae,"readonly").objectStore(ae);if(n)return Ve(s.get(ne(n,t)));const i=this._defaultBucket??ee,a=await Ve(s.get(ne(i,t)));if(a!==void 0)return a;if(i!==ee){const c=await Ve(s.get(ne(ee,t)));if(c!==void 0)return c}return new Promise((c,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){c(void 0);return}const m=String(d.key),f=jn(m);if(f&&f.path===t){c(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??ee;n.bucket||(n.bucket=s);const i=ne(s,t),a=this.db.transaction(ae,"readwrite");a.objectStore(ae).put(n,i),await Jt(a)}async delete(t,n){const r=n??this._defaultBucket??ee,s=ne(r,t),i=this.db.transaction([pe,ae],"readwrite");i.objectStore(pe).delete(s),i.objectStore(ae).delete(s),await Jt(i)}async listByPrefix(t,n){const r=n??this._defaultBucket??ee,s=this.db.transaction(ae,"readonly"),i=`${r}/${t}`,a=IDBKeyRange.bound(i,i+"�",!1,!1);return Ve(s.objectStore(ae).getAll(a))}async reset(t){const n=this.db.transaction([pe,ae],"readwrite");if(!t)n.objectStore(pe).clear(),n.objectStore(ae).clear(),this._defaultBucket=void 0;else{const r=`${t}/`,s=IDBKeyRange.bound(r,r+"�",!1,!1);n.objectStore(pe).delete(s),n.objectStore(ae).delete(s)}await Jt(n)}close(){this.db.close()}scoped(t){return new Ln(this,t)}}class Ln{underlying;bucket;constructor(t,n){this.underlying=t,this.bucket=n}put(t,n,r){const s=r.bucket?r:{...r,bucket:this.bucket};return this.underlying.put(t,n,s)}getBlob(t,n){return this.underlying.getBlob(t,n??this.bucket)}getMetadata(t,n){return this.underlying.getMetadata(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)}close(){this.underlying.close()}scoped(t){return t===this.bucket?this:this.underlying.scoped?this.underlying.scoped(t):new Ln(this.underlying,t)}}function fp(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,cp);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(pe)||s.createObjectStore(pe),s.objectStoreNames.contains(ae)||s.createObjectStore(ae)}),r.addEventListener("success",()=>t(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${e}"`)))}catch(r){n(r)}})}function Ve(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Jt(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")))})}function Ni(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const hp=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function Ho(e){return{segments:e.path.segments.map(pp),children:e.children.map(Ho),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(Hr)}}function pp(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 Hr(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>({name:t.name,value:H(t.value)})),body:H(e.body)}}function H(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Ce(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:H(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:H(e.object),method:e.method,args:e.args.map(H)};case"bracketAccess":return{kind:"index",target:H(e.object),index:H(e.index)};case"sliceAccess":return{kind:"slice",target:H(e.object),start:H(e.start),end:H(e.end)};case"binaryOp":if(!hp.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:H(e.left),right:H(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:H(e.operand)};case"ternary":return{kind:"ternary",cond:H(e.condition),then:H(e.consequent),else:H(e.alternate)};case"inExpr":return{kind:"in",element:H(e.element),collection:H(e.collection)};case"isExpr":return{kind:"is",value:H(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(H)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:H(t.key),value:H(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:H(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(H)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function Gr(e){const t=su(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: expected ${t.error.expected}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[Ho(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(i=>({name:i,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Hr),...(n.service.functions??[]).map(Hr)]};return Go(r,new Map),{_root:r,_version:n.version}}function Go(e,t){const n=new Map(t);for(const r of e.functions)n.set(r.name,r);e.visibleFuncs=n;for(const r of e.functions)r.declScope=n;for(const r of e.children)Go(r,n)}function X(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 X(e.target,t);case"index":return X(e.target,t)||X(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>X(n,t));case"unary":return X(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>X(n,t));case"in":return X(e.element,t)||X(e.collection,t);case"is":return X(e.value,t);case"list":return e.elements.some(n=>X(n,t));case"map":return e.entries.some(({key:n,value:r})=>X(n,t)||X(r,t));case"binary":return X(e.left,t)||X(e.right,t);case"call":return e.args.some(n=>X(n,t));case"methodcall":return X(e.target,t)||e.args.some(n=>X(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&X(n.expr,t));case"ident":case"literal":return!1}}function Jo(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&&X(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(X(i.value,s))return!0;s.add(i.name)}if(X(r.body,s))return!0}return e.children.some(r=>Jo(r,n))}function mp(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return Jo(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 Yo="pyric-default",Fn=Symbol("pyric/storage/target");function Ze(e){return e.currentAuth?.()??e.context.auth}class Qo{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}const Ri=new WeakMap,Ai=new WeakMap;function yp(e,t,n){let r=Ai.get(e);r||(r=new Map,Ai.set(e,r));let s=r.get(t);return s||(s=n.then(i=>{const a=i.backend.scoped?i.backend.scoped(t):i.backend;return new Qo(a,i.rules,i.crossServiceIam)}),r.set(t,s)),s}function Ii(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 bp(e,t,n){const r=Ri.get(e);if(r)return Ii("rules","rules source",t.rules,r.rulesSource,n),Ii("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let s=null,i=null;if(t.rules){let l=t.rules,u=[],d=[],m=[];if(s=Gr(l),s._version==="2+modules"){const f=io(l);if(!f.success)throw new SyntaxError(`Storage rules module resolution failed (${f.error.code}): ${f.error.message}`);l=f.data.resolved,u=f.data.modules,d=f.data.bundledModules,m=f.data.evidenceIds,s=Gr(l)}i=mp(l,u,d,m,s)}const a=t.crossServiceIam??"granted",c=lp(t.dbName??op(t.projectId),t.bucket??Yo).then(l=>new Qo(l,s,a));return Ri.set(e,{service:c,rulesSource:t.rules??null,rulesResolution:i,crossServiceIam:a}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await c).backend.reset()}}),c}function ur(e){return e instanceof au}const dr=new WeakMap,fr=new WeakMap;function gp(e,t={}){const n=!ur(e),r=ur(e)?e.sandbox:e,s=bp(r,t,"getAdminStorageSandbox"),i=t.bucket??Yo;if(n){const p=fr.get(r)?.get(i);if(p)return p}const a=ur(e)?e:r.withAuth(null),c=a.operationContext.authLens.mode==="admin"?a:no(a,{source:a.operationContext.source,authLens:{mode:"admin"},...a.operationContext.planId===void 0?{}:{planId:a.operationContext.planId}}),l=dr.get(a)?.get(i);if(l)return l;const u=yp(r,i,s),d={kind:"sandbox",sandbox:r,context:c,bucket:i,servicePromise:u,admin:!0},m=Object.freeze({[Fn]:d});let f=dr.get(a);if(f||(f=new Map,dr.set(a,f)),f.set(i,m),n){let p=fr.get(r);p||(p=new Map,fr.set(r,p)),p.set(i,m)}return m}function xt(e,t){const n=iu(t,Hs(e.context.operationContext));return{...t,...Hs(n),service:"storage"}}function Ne(e){const t=e[Fn];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Wt(e){return Ne(e).servicePromise}class U extends Error{}class Ee extends U{}class Es extends U{}function vp(e){return e instanceof U&&!(e instanceof Ee)&&!(e instanceof Es)}class Z{message;constructor(t){this.message=t}}function W(e){return e instanceof Z}function Te(e){if(typeof e=="number")return e;if(e instanceof Ce)return e.value}function Me(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function dt(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=Te(e),r=Te(t);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((s,i)=>dt(s,t[i]));if(Me(e)&&Me(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&dt(e[a],t[a]))}return!1}function oe(e){return e===null?"null":e===void 0?"undefined":e instanceof Ce?"float":typeof e}function wp(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return _p(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return kp(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return xp(e,t);if(e.method==="matches")return Sp(e,t);if(e.method==="split")return Ep(e,t);if(e.method==="size")return Cp(e,t);if(e.method==="keys")return Np(e,t);if(e.method==="hasAll")return Rp(e,t);if(e.method==="get")return Ap(e,t);throw new Ee(`unsupported method .${e.method}()`)}function xp(e,t){if(e.method!=="get"&&e.method!=="exists")throw new Ee(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new U(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new Ee(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];if(n.kind!=="path")throw new Ee(`firestore.${e.method}() requires a /databases/.../documents/... path literal`);const r=jp(n,t);if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new Es("firestore access limit exceeded: at most two distinct documents");t.firestoreAccesses.add(r)}if(e.method==="exists")return t.firestoreLookup.exists(r);const s=t.firestoreLookup.get(r);return s===null?new Z(`firestore.get() targeted a nonexistent document: ${r}`):{data:s}}function jp(e,t){const n=e.segments.map(s=>{if(s.kind==="literal")return s.value;const i=B(s.expr,t);if(typeof i=="string")return i;if(typeof i=="number")return String(i);throw new U(`Firestore path interpolation resolved to ${oe(i)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new U(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);if(n[1]!=="(default)")throw new U(`Storage rules may access only the default Firestore database, got ${n[1]}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new U(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const Di={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function kp(e,t){if(e.method!=="value")throw new U(`unsupported duration.${e.method}()`);const n=e.args.map(a=>B(a,t));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new U("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,i=Di[s];if(i===void 0)throw new U(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(Di).join(", ")}`);return r*i}function _p(e,t){const n=e.args.map(r=>B(r,t));if(e.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new U("timestamp.value() expects (epochMillis: number)");return n[0]}if(e.method==="date"){if(n.length!==3||!n.every(a=>typeof a=="number"))throw new U("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;return Date.UTC(r,s-1,i)}throw new U(`unsupported timestamp.${e.method}()`)}function Sp(e,t){const n=B(e.target,t);if(W(n))return n;if(typeof n!="string")throw new U(`matches() requires a string target, got ${oe(n)}`);if(e.args.length!==1)throw new U("matches() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("matches() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(`^(?:${r})$`)}catch(c){throw new U(`matches() invalid regex pattern: ${c.message}`)}return a.test(n)}function Ep(e,t){const n=B(e.target,t);if(W(n))return n;if(typeof n!="string")throw new U(`split() requires a string target, got ${oe(n)}`);if(e.args.length!==1)throw new U("split() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("split() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(r)}catch(c){throw new U(`split() invalid regex pattern: ${c.message}`)}return n.split(a)}function Cp(e,t){const n=B(e.target,t);if(W(n))return n;if(e.args.length!==0)throw new U("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(Me(n))return Object.keys(n).length;throw new U(`size() requires a string, list, or map target, got ${oe(n)}`)}function Np(e,t){const n=B(e.target,t);if(W(n))return n;if(e.args.length!==0)throw new U("keys() expects no arguments");if(!Me(n))throw new U(`keys() requires a map target, got ${oe(n)}`);return Object.keys(n)}function Rp(e,t){const n=B(e.target,t);if(W(n))return n;if(!Array.isArray(n))throw new U(`hasAll() requires a list or set target, got ${oe(n)}`);if(e.args.length!==1)throw new U("hasAll() expects one list or set argument");const r=B(e.args[0],t);if(W(r))return r;if(!Array.isArray(r))throw new U("hasAll() argument must be a list or set");return r.every(s=>n.some(i=>dt(i,s)))}function Ap(e,t){const n=B(e.target,t);if(W(n))return n;if(!Me(n))throw new U(`get() requires a map target, got ${oe(n)}`);if(e.args.length!==2)throw new U("get() expects a key and default value");const r=B(e.args[0],t);if(W(r))return r;if(typeof r!="string")throw new U("get() key must be a string");const s=B(e.args[1],t);return W(s)?s:Object.prototype.hasOwnProperty.call(n,r)?n[r]:s}function Ip(e){return e.split("/").filter(t=>t.length>0)}function hr(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function Dp(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="wildcard")return s[a.name]=t.slice(r),{left:[],params:s};if(r>=t.length)return null;if(a.kind==="literal"){if(t[r]!==a.value)return null;r++}else s[a.name]=t[r],r++}return{left:t.slice(r),params:s}}function Xo(e,t,n=new Date,r){const s=n.getTime(),i=Ip(t.request.path),a=[],c=new Set,l=new Set(Ni(t.request.method));function u(m,f,p){const y=Dp(m.segments,f,p);if(!y)return!1;const b=y.params,v=y.left;if(v.length===0)for(const g of m.allows){const w=new Set(g.verbs.flatMap(Ni));if(![...l].some(j=>w.has(j)))continue;let k;try{const j=g.condition?B(g.condition,{input:t,now:s,params:b,locals:{},funcs:m.visibleFuncs??new Map,depth:0,firestoreLookup:r,firestoreAccesses:c}):!0;if(W(j)){a.push(`match ${hr(m.segments)} ${t.request.method}: ${j.message}`);continue}k=Zo(j)}catch(j){if(j instanceof U){a.push(`match ${hr(m.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(k)return!0;a.push(`match ${hr(m.segments)} ${t.request.method}: condition false`)}for(const g of m.children)if(u(g,v,b))return!0;return!1}const d=u(e._root,i,{});return!d&&a.length===0&&a.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:d,reasons:a}}function Pi(e,t){if(!Me(e)&&!Array.isArray(e))return new Z(`Property ${t} is undefined on ${oe(e)}.`);if(!Object.hasOwn(e,t))return new Z(`Property ${t} is undefined on object.`);const n=e[t];return n===void 0?new Z(`Property ${t} is undefined on object.`):n}function Zo(e){return W(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const $i=20;function B(e,t){switch(e.kind){case"literal":return e.value;case"ident":return e.name in t.locals?t.locals[e.name]:e.name==="request"?Tp(t.input,t.now):e.name==="resource"?t.input.resource===null?new Z("Null value error."):Op(t.input.resource):e.name in t.params?t.params[e.name]:void 0;case"member":{const n=B(e.target,t);return W(n)?n:n==null?new Z("Null value error."):Pi(n,e.name)}case"index":{const n=B(e.target,t);if(W(n))return n;if(n==null)return new Z("Null value error.");const r=B(e.index,t);return W(r)?r:Pi(n,String(r))}case"call":return Pp(e,t);case"methodcall":return wp(e,t);case"path":throw new Ee("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=B(e.arg,t);if(e.op==="!"){if(W(n))throw new U(n.message);if(typeof n!="boolean")throw new U(`Unary '!' expects a boolean, got ${oe(n)}.`);return!n}return W(n)?n:e.op==="-"?n instanceof Ce?new Ce(-n.value):typeof n!="number"?new Z(`Unary '-' applied to ${oe(n)}.`):-n:void 0}case"ternary":{const n=B(e.cond,t);return W(n)?n:Zo(n)?B(e.then,t):B(e.else,t)}case"in":{const n=B(e.element,t);if(W(n))return n;const r=B(e.collection,t);return W(r)?r:Array.isArray(r)?r.some(s=>dt(s,n)):Me(r)?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new Z(`'in' applied to ${oe(r)} (expected a list or map).`)}case"is":{const n=B(e.value,t);return W(n)?n:$p(n,e.typeName)}case"list":{const n=[];for(const r of e.elements){const s=B(r,t);if(W(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of e.entries){const s=B(r.key,t);if(W(s))return s;if(typeof s!="string")return new Z(`Map literal key is ${oe(s)} (expected a string).`);const i=B(r.value,t);if(W(i))return i;n[s]=i}return n}case"slice":{const n=B(e.target,t);if(W(n))return n;const r=B(e.start,t);if(W(r))return r;const s=B(e.end,t);return W(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new Z("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new Z(`Slice bounds [${r}:${s}] out of range for ${oe(n)} of size ${n.length}.`):n.slice(r,s):new Z(`Slice applied to ${oe(n)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return Oi(e.left,e.right,!1,t);if(e.op==="||")return Oi(e.left,e.right,!0,t);const n=B(e.left,t);if(W(n))return n;const r=B(e.right,t);if(W(r))return r;switch(e.op){case"==":return dt(n,r);case"!=":return!dt(n,r);case"<":return Yt(n,r)<0;case">":return Yt(n,r)>0;case"<=":return Yt(n,r)<=0;case">=":return Yt(n,r)>=0;case"+":return qe(n,r,(s,i)=>s+i);case"-":return qe(n,r,(s,i)=>s-i);case"*":return qe(n,r,(s,i)=>s*i);case"/":return ot(n)||ot(r)?qe(n,r,(s,i)=>s/i):Te(r)===0?new Z("Division by zero."):qe(n,r,(s,i)=>Math.trunc(s/i));case"%":return ot(n)||ot(r)?qe(n,r,(s,i)=>s%i):Te(r)===0?new Z("Modulo by zero."):qe(n,r,(s,i)=>s%i)}}}}function Oi(e,t,n,r){const s=Ti(e,r);if(s===n)return n;const i=Ti(t,r);return i===n?n:W(s)?s:i}function Ti(e,t){let n;try{n=B(e,t)}catch(r){if(vp(r))return new Z(r.message);throw r}return W(n)?n:typeof n!="boolean"?new Z(`Expected a boolean '&&'/'||' operand, got ${oe(n)}.`):n}function Pp(e,t){const n=t.funcs.get(e.name);if(!n)throw new Ee(`undefined function ${e.name}()`);if(n.unresolvedImport!==void 0)throw new Ee(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)throw new Ee(`function ${e.name}() expects ${n.params.length} argument(s), got ${e.args.length}`);const r=t.depth+1;if(r>$i)throw new Es(`function ${e.name}() exceeded max call depth ${$i}`);const s=e.args.map(c=>B(c,t)),i={};n.params.forEach((c,l)=>{i[c]=s[l]});const a={input:t.input,now:t.now,params:{},locals:i,funcs:n.declScope??new Map,depth:r,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses};for(const c of n.lets)i[c.name]=B(c.value,a);return B(n.body,a)}function $p(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 Ce||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Ce||typeof e=="number";case"list":return Array.isArray(e);case"map":return Me(e);default:return new Z(`'is ${t}' is not supported by the storage evaluator.`)}}function ot(e){return e instanceof Ce}function Yt(e,t){const n=Te(e),r=Te(t);return n!==void 0&&r!==void 0?n-r:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:Number.NaN}function qe(e,t,n){const r=Te(e),s=Te(t);if(r===void 0||s===void 0)return;const i=n(r,s);return ot(e)||ot(t)?new Ce(i):i}function Op(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Mi(e.timeCreated),updated:Mi(e.updated)}}function Mi(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Tp(e,t){return{auth:e.request.auth??new Z("Property auth is undefined on object."),resource:e.request.resource??new Z("Property resource is undefined on object."),method:e.request.method,path:e.request.path,time:t}}function Mp(e){return`storage/${e}`}class jt extends Error{code;constructor(t,n){const r=Mp(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,jt.prototype)}}function ec(e){return new jt("object-not-found",`no object at "${e}".`)}function Ui(e,t,n){return new jt("unauthorized",`${e} "${t}" denied by rules${n}.`)}function Vn(e){return new jt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Up(){return new jt("canceled","User canceled the upload/download.")}function zt(e,t,n,r){const s=n?.kind==="sandbox"?xt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Qt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules)throw Qt(n,t,"deny",["No Storage rules configured; default deny."],"user",!1,s),Ui(t.request.method,t.request.path," — No Storage rules configured; default deny.");const i=n?Bp(t,n.bucket):t,a=Xo(e.rules,i,void 0,Lp(n,e.crossServiceIam));if(!a.allowed){Qt(n,t,"deny",a.reasons,"user",!0,s);const c=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw Ui(t.request.method,t.request.path,c)}Qt(n,t,"allow",a.reasons,"user",!0,s)}function Bp(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Qt(e,t,n,r,s,i,a){if(e)try{Pe(e.sandbox,eo({service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,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}),{...a,service:"storage"})}catch{}}function Lp(e,t){if(!e)return;if(t==="denied")return Fp();const n=e.sandbox.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function Fp(){const e=t=>{throw new U(`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 qn(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Vp(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:Bi(e.generation),metageneration:Bi(e.metageneration)}:null}function Vp(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 Bi(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function qp(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function Cs(e){return{...e}}async function Wp(e){zp(e,"getMetadata");const t=Ne(e.storage),n=xt(t),r=await Wt(e.storage),s=await r.backend.getMetadata(e.fullPath);if(zt(r,{request:{auth:Ze(t),method:"get",path:e.fullPath},resource:qn(s)},t,n),!s)throw ec(e.fullPath);return Cs(s)}function zp(e,t){if(e.fullPath==="")throw Vn(t)}const Kp="application/octet-stream";async function tc(e,t,n,r){Jp(e,"uploadBytes");const s=Ne(e.storage),i=xt(s,r),a=Hp(t,n?.contentType),c=nc({ref:e,blob:a,settable:n}),l=await Wt(e.storage),u=await l.backend.getMetadata(e.fullPath);zt(l,{request:{auth:Ze(s),method:u?"update":"create",path:e.fullPath,resource:qp({size:c.size,contentType:c.contentType,customMetadata:c.customMetadata})},resource:qn(u)},s,i),await l.backend.put(e.fullPath,a,c);try{Pe(s.sandbox,In({service:"storage",op:"object_put",path:e.fullPath,auth:Ze(s),before:u??void 0,after:c,detail:{bucket:e.bucket,size:c.size,contentType:c.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:Cs(c)}}function nc(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=Gp(e.now??new Date),a=t.name;return{fullPath:t.fullPath,name:a,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Kp,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Hp(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Gp(e){return String(e.getTime())}function Jp(e,t){if(e.fullPath==="")throw Vn(t)}function Yp(e){return e instanceof Blob?e.size:e.byteLength}function Qp(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function Xp(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class Zp{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_data;_metadata;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=Yp(n),i=new Date().toISOString();let a="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(a=n.type),r!==void 0&&r.contentType!==void 0){const m=r.contentType;m!==void 0&&(a=m)}const u={fullPath:t.fullPath,name:t.name,bucket:"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:a};this._promise=new Promise((d,m)=>{this._resolve=d,this._reject=m}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,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(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Qp(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,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&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const g=a,w=this._error;try{g(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}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 c=i.next;try{c(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 c=i.complete;try{c()}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(){if(this._snapshot.state==="running")try{const n=await rc(this._ref,this._data,this._metadata);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await sc(this._ref)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function em(e,t,n){if(e.fullPath==="")throw Xp();return new Zp(e,t,n)}class Mt{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=_s(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 Mt(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Mt(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function tm(e){return e.replace(/^\/+|\/+$/g,"")}function nm(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(),xs(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function rm(e,t){const n=tm(t??"");let r,s,i="pyric-default",a;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,a=e;else{const c=e.fullPath;r=n?c?`${c}/${n}`:n:c,s=e.port,i=e.bucket,a=e.storage}return new Mt(s,i,r,a)}async function sm(e){const t=await he(e.port,{t:"op",id:M(),method:"storage.listAll",path:e.fullPath}),n=r=>new Mt(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function im(e){return await he(e.port,{t:"op",id:M(),method:"storage.getMetadata",path:e.fullPath})}async function am(e){return await he(e.port,{t:"op",id:M(),method:"storage.getBlob",path:e.fullPath})}async function rc(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>zo)throw Ah(r.byteLength,`uploadBytes payload for '${e.fullPath}'`);const s=n?.contentType??(t instanceof Blob&&t.type?t.type:void 0),i=await he(e.port,{t:"op",id:M(),method:"storage.putBytes",path:e.fullPath,dataB64:Ih(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function sc(e){await he(e.port,{t:"op",id:M(),method:"storage.deleteObject",path:e.fullPath})}async function om(e){return z(e.port,{t:"op",id:M(),method:"rtdb.adminSnapshot"})}async function cm(e,t,n){await z(e.port,{t:"op",id:M(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function lm(e,t,n){await z(e.port,{t:"op",id:M(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function um(e,t){await z(e.port,{t:"op",id:M(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function dm(e,t,n,r){const s=vt();return!Vt(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},js({t:"sub",subId:s,target:{service:"rtdb",path:gh(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>qt(e.port,s)}function fm(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 a=null;const c=()=>i?(a??=Bf({targetEpoch:i,retire:()=>e.retire?e.retire(i):sh(e.db,i),subscribeReload:e.subscribeReload??ih,preflight:e.preflight??(()=>Uf(s)),commitGeneration:e.remember??(l=>Mf(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}:{}}),a):null;return(e.readVersion??(()=>oh(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),c(),()=>{t.delete(l),t.size===0&&(a?.dispose(),a=null)}},async update(){const l=c();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(),a?.dispose(),a=null}}}function hm(e={}){const t=Lo(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:Tf(t.worker.servedEpoch,n)}}const pm="/__pyric/sdk/worker.js";function mm(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=Vh(e,a=>{const c=!n;n=!0;const l=c?[]:[...t];for(const u of a)$o(u)&&(l.length=0),l.push(u);t=l;for(const u of a)for(const d of r)d(u)}))}return{history:()=>t,subscribe:a=>(r.add(a),i(),()=>{r.delete(a),r.size===0&&s&&(s(),s=null,n=!1,t=[])})}}function ym(e=pm){if(typeof SharedWorker>"u")return null;rh("studio");let t;try{const l=hm({workerUrl:e});t=ah(l.url,l.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=fm({db:t,servedEpoch:Lo(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});ki({mode:"admin"});const s=Gh({db:t,kind:"studio"}),i=mm(t),a=Zh(t);let c=!1;return{db:t,runtime:r,dispose:async()=>{c||(c=!0,s.stop(),r.dispose(),await kh(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:l=>Jh(t,l),instanceId:()=>ch(t),exportState:()=>lh(t),importState:l=>uh(t,l),saveBranch:l=>dh(t,l),listBranches:()=>fh(t),switchBranch:l=>hh(t,l),deleteBranch:l=>ph(t,l),feed:i,setLens:l=>ki(l),getLens:()=>nh(),listRootCollections:()=>Oh(t),listSubcollections:l=>Th(t,l),listDocuments:async l=>(await Fh(t,l)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>om(t),setRtdbValue:(l,u)=>cm(t,l,u),updateRtdbValue:(l,u)=>lm(t,l,u),deleteRtdbValue:l=>um(t,l),subscribeRtdbValue:(l,u,d)=>dm(t,l,u,d),firestoreApi:{collection:Sh,doc:_h,getDoc:Ph,getDocs:$h,onSnapshot:Mh,setDoc:Uh,deleteDoc:Bh,addDoc:Lh,query:Nh,limit:Eh,startAfter:Ch},auth:a,authApi:{listUsers:()=>ep(a),subscribeUsers:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(l,u)=>tp(a,u),updateUser:(l,u,d)=>np(a,u,d),deleteUser:(l,u)=>rp(a,u),clearUsers:()=>sp(a),getAuthProviderConfig:()=>ip(a),setAuthProviderConfig:(l,u,d)=>ap(a,u,d),subscribeAuthProviderConfig:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:nm(t),storageApi:{ref:rm,listAll:sm,getMetadata:im,getBlob:am,uploadBytes:rc,uploadBytesResumable:em,deleteObject:sc},getSnapshot:()=>qh(t),resetAll:()=>Wh(t)}}const Li=5174,Fi="/sandbox",bm=4001,gm="worker-relay";function vm(e){if(e===null||typeof e!="object")return!1;const t=e.type;return t==="hello"||t==="hello-ack"||t==="attach"||t==="attach-ack"||t==="tool-call"||t==="tool-result"||t==="worker-op"||t==="worker-res"||t==="worker-sub"||t==="worker-unsub"||t==="worker-snap"||t==="ping"||t==="pong"}function Jr(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=Jr(t);if(n)return n}return null}for(const t of Object.values(e)){const n=Jr(t);if(n)return n}return null}function Vi(e,t){const n=Jr(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 wm={transport:"in-process",order:60,tools:["pyric_can_i_use"]},xm={transport:"forwarded",order:20,tools:["firestore_get_document","firestore_list_documents","firestore_create_document","firestore_add_document","firestore_update_document","firestore_delete_document","firestore_batch_write","firestore_query_where"]},jm={transport:"forwarded",order:30,tools:["sandbox_inspect"]},km={transport:"in-process",order:50,tools:["firestore_simulate_rules","firestore_rules_stdlib_list","firestore_rules_stdlib_get","firestore_lint_rules","firestore_resolve_modules","rules_stdlib_list","rules_stdlib_get","rules_resolve_modules"]},_m={transport:"forwarded",order:10,tools:["firestore_simulator_create","firestore_simulator_execute","firestore_simulator_read","firestore_simulator_batch","firestore_create_with_auto_id","firestore_simulator_undo","firestore_simulator_redo","firestore_simulator_events","firestore_simulator_transaction"]},Sm={transport:"forwarded",order:40,tools:["rtdb_simulate_access","rtdb_crawl_structure"]},Em=[{key:"conformance",...wm},{key:"firestore-data",...xm},{key:"firestore-inspect",...jm},{key:"firestore-rules",...km},{key:"firestore-simulator",..._m},{key:"rtdb-inspection",...Sm}];function pr(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 Cm(e){return pr("key",e.map(t=>t.key)),pr("order",e.map(t=>t.order)),pr("tool name",e.flatMap(t=>t.tools)),[...e].sort((t,n)=>t.order-n.order)}const Nm=Cm(Em);function ic(e){return Nm.filter(t=>t.transport===e)}function Rm(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,a)=>i!==s[a]))throw new Error(`${e} drifted from the default MCP contract
108
108
  expected: ${n.join(", ")}
109
- actual: ${t.join(", ")}`)}function Ui(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const ve=e=>e,Bi=(...e)=>ve(e.map(t=>`(${t})`).join(" && ")),km=(...e)=>ve(e.map(t=>`(${t})`).join(" || ")),Zo=e=>e,Sm=()=>Zo("newData.hasChildren()"),Em=e=>Zo(`newData.hasChild("${e}")`);function ec(e,t){const n=e.shape,r=[],s={};for(const[c,l]of Object.entries(n)){const u=l,d=u instanceof eu,m=d?u.unwrap():u;d||r.push(c);const f=tc(m,c),p=t?.[c];if(p&&p.length>0?s[c]={validate:Bi(f,...p)}:s[c]={validate:f},m instanceof Xa){const y=ec(m);s[c]={validate:y.validate,children:y.children}}}const i=[Sm()];for(const c of r)i.push(Em(c));return{validate:Bi(...i),children:s}}function tc(e,t){if(e instanceof tu)return ve("newData.isString()");if(e instanceof nu)return ve("newData.isNumber()");if(e instanceof ru)return ve("newData.isBoolean()");if(e instanceof su){const n=e.options;return ve(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof iu){const n=e.value;return ve(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof au){const n=e._def.options;return km(...n.map(r=>tc(r,t)))}if(e instanceof Xa)return ve("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function Cm(e){let t;if(typeof e=="function"){const s=[];e({path:(i,a)=>s.push([i,a])}),t=s}else t=Object.entries(e);const n=nc(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,c=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-c||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&Nm(r,s);for(const[s,i]of n){const a=s==="/"?r:js(r,s);a&&Rm(r,a,i,s)}return r}function Nm(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("/"),a=n.slice(0,s+1).filter(l=>l.startsWith("$"));let c=r.children.find(l=>l.path===i);c||(c={path:i,pathVariables:a,children:[]},r.children.push(c)),r=c}}function Rm(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=tt(n.read,"read",s)),n.write&&(t.write=tt(n.write,"write",s)),n.validate&&(t.validate=tt(n.validate,"validate",s)),n.schema){const i=ec(n.schema,n.fieldConstraints);t.validate||(t.validate=tt(i.validate,"validate",s));for(const[a,c]of Object.entries(i.children)){const l=`${r}/${a}`;let u=t.children.find(d=>d.path===l);if(u||(u={path:l,pathVariables:s,children:[]},t.children.push(u)),u.validate=tt(c.validate,"validate",s),"children"in c&&c.children)for(const[d,m]of Object.entries(c.children)){const f=`${l}/${d}`;let p=u.children.find(y=>y.path===f);p||(p={path:f,pathVariables:s,children:[]},u.children.push(p)),p.validate=tt(m.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const c="/"+i.slice(0,-1).join("/"),l=js(e,c);l&&(l.indexOn=n.indexOn)}}}function nc(e){const t=[];for(const[n,r]of e){const{children:s,...i}=r;if(t.push([n,i]),s){const a=Object.entries(s).map(([c,l])=>[n+c,l]);t.push(...nc(a))}}return t}function tt(e,t,n){return ho(String(e),t,n)}function js(e,t){if(e.path===t)return e;for(const n of e.children){const r=js(n,t);if(r)return r}return null}function Am(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function Im(e){return{operation:e.operation,path:e.path,auth:Am(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function lr(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Wr(e,t){const n=[...lr(e.path,".read",e.read,t),...lr(e.path,".write",e.write,t),...lr(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...Wr(r,t));return n}class Dm{definition;constructor(t){this.definition=t}compile(){return Cm(this.definition.paths)}toJSON(){return _d(this.compile())}check(){try{const t=this.compile(),n=Wr(t,"errors"),r=Wr(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(t){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:t instanceof Error?t.message:String(t)}],warnings:[]}}}simulate(t){return fs(this.compile(),Im(t))}}function Pm(e){return new Dm(e)}function $m(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function Om(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class ur{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>Ui(n,"error")),...t.warnings.map(n=>Ui(n,"warning"))]}runOne(t){const n=this.doc.simulate({operation:t.operation,path:t.path,auth:t.auth??null,...t.data!==void 0?{data:t.data}:{},...t.newData!==void 0?{newData:t.newData}:{}});if(!n.success)return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:t.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,i=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",a=!s&&i===t.expectation;return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:i,passed:a,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(t){const n=t.map(a=>this.runOne(a));let r=0,s=0,i=0;for(const a of n)a.unsupported?i++:a.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n}}explain(t){const n=this.runOne(t);return{decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason}}toJSON(){return this.doc.toJSON()}}function Tm(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class Mm{json;compiled;constructor(t){this.json=t,this.compiled=mo(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return fs(this.compiled,{operation:t.operation,path:t.path,auth:Tm(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function Um(e){return $m(e)?new ur(e):Om(e)?new ur(new Mm(e)):new ur(Pm(e))}function Bm(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function Li(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Lm(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Fm(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 rc(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:Li(e)};const i=Object.entries(e).sort(([m],[f])=>m.localeCompare(f)),a={},c=[];for(const[m,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?c.push([m,f]):a[m]=Li(f);const l=n>=r&&c.length>0,u=i.length>s,d=n>=r?[]:c.slice(0,s).map(([m,f])=>rc(f,Bm(t,m),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:a}}function Vm(e,t={}){const n=Lm(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return rc(Fm(e,n),n,0,r,s)}function sc(e){return e.children.reduce((t,n)=>t+1+sc(n),0)}function qm(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, or validate operation against the RTDB rules and data currently loaded in the local sandbox. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=go(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=oi(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},c={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:a,...n.newData!==void 0?{newData:n.newData}:{}},l=Um(s).simulate([c]).cases[0];return{ok:!l.unsupported,summary:l.unsupported?`Simulation unsupported: ${l.reason}`:`Simulation: ${l.decision.toLowerCase()}`,data:{decision:l.decision,allowed:l.decision==="ALLOW",unsupported:l.unsupported,matchedPath:l.matchedPath,matchedRule:l.matchedRule,reason:l.reason}}}},{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=Vm(oi(r),n);return{ok:!0,summary:`Crawled ${sc(s)} object paths from ${s.path}`,data:s}}}]}const Wm={"firestore-simulator":({env:e})=>Yu({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>hf({resolveDb:e}),"firestore-inspect":({sandbox:e})=>pf({resolveSandbox:()=>e}),"rtdb-inspection":({sandbox:e})=>qm({resolveSandbox:()=>e})};function zm(e){const t={sandbox:e,env:Nn(e),resolveDb:n=>n&&n!=="admin"?so(e.withAuth({uid:n.uid,token:n.claims})):io(e)};return Xo("forwarded").flatMap(n=>Wm[n.key](t))}function Km(e){const t=zm(e);_m("sandbox dispatcher tools",t.map(r=>r.name),ic);const n=new Map(t.map(r=>[r.name,r]));return async(r,s)=>{const i=n.get(r);if(!i)throw new Gm(r);const a={signal:new AbortController().signal},c=await i.execute(s,a);return{ok:c.ok,summary:c.summary,data:c.data}}}const Fi=new WeakMap;async function Hm(e,t,n){let r=Fi.get(e);return r||(r=Km(e),Fi.set(e,r)),r(t,n)}const ic=Xo("forwarded").flatMap(e=>e.tools);class Gm extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const Jm=500,Ym=3e4,Qm=2e3,Xm=.5,Zm=3;function ey(e,t={}){const n=ty(t.url),r=t.sandboxId??ny(),s=t.dispatcher??Hm,i=t.toolNames??[...ic],a=t.initialReconnectDelayMs??Jm,c=t.maxReconnectDelayMs??Ym,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??Qm,m=t.fetchImpl??(P=>fetch(P)),f=t.workerRelay??null;let p=null,y=!1,b=0,v=null,g=null,w=0,x={kind:"connecting"};const _=new Map;function j(){for(const P of _.values())try{P()}catch{}_.clear()}function k(P){x=P;try{u(P)}catch{}}function N(P){if(p&&p.readyState===WebSocket.OPEN)try{p.send(JSON.stringify(P))}catch{}}function A(){if(y)return;k({kind:"connecting"});let P;try{P=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}p=P,P.onopen=()=>{b=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[fm]}:{}};N(O)},P.onmessage=O=>{let T;try{T=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(hm(T)){if(T.type==="hello-ack"){k({kind:"connected",bridgeVersion:T.bridgeVersion});return}if(T.type==="tool-call"){R(T);return}if(T.type==="worker-op"){I(T);return}if(T.type==="worker-sub"){C(T);return}if(T.type==="worker-unsub"){const $=_.get(T.subId);if($){_.delete(T.subId);try{$()}catch{}}return}if(T.type==="ping"){N({type:"pong",id:T.id});return}}},P.onclose=O=>{const T=O.reason||`closed (code ${O.code})`;if(p=null,j(),O.code===dm){E();return}G(T)},P.onerror=()=>{}}async function R(P){let O;try{const T=await s(e,P.name,P.args??{});O={type:"tool-result",id:P.id,ok:!0,result:T}}catch(T){O={type:"tool-result",id:P.id,ok:!1,error:{code:T instanceof Error?T.name:"Error",message:T instanceof Error?T.message:String(T)}}}N(O)}async function I(P){if(f)try{const O=await f.op(P.op);Mi(`op '${P.op.method}'`,O),N({type:"worker-res",id:P.id,ok:!0,value:O})}catch(O){const T=O.denialContext;N({type:"worker-res",id:P.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...T!==void 0?{denialContext:T}:{}}})}}function C(P){if(f&&!_.has(P.subId))try{const O=f.subscribe(P.sub,T=>{try{Mi(`subscription '${P.subId}'`,T)}catch($){N({type:"worker-snap",subId:P.subId,value:{__error:{code:$.code??"invalid-argument",message:$ instanceof Error?$.message:String($)}}});return}N({type:"worker-snap",subId:P.subId,value:T})});_.set(P.subId,O)}catch(O){const T=O.denialContext;N({type:"worker-snap",subId:P.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...T!==void 0?{denialContext:T}:{}}}})}}function S(){try{const P=new URL(n);P.protocol=P.protocol==="wss:"?"https:":"http:";const O=P.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(l){k({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}b=0,w=0,k({kind:"standby"}),D()}}function D(){if(y)return;const P=d*(1+Math.random()*Xm);g=setTimeout(()=>{g=null,V()},P)}async function V(){if(y)return;let P=null;for(const O of S())try{const T=await m(O);if(!T.ok)continue;const $=await T.json();if(typeof $.sandboxConnected=="boolean"){P=!$.sandboxConnected;break}}catch{}if(!y){if(P===!0){A();return}if(P===!1){w=0,D();return}if(w+=1,w>=Zm){G("standby health poll unreachable");return}D()}}function G(P){if(y)return;if(l){k({kind:"disconnected",reason:P});return}b+=1;const O=Math.min(a*2**(b-1),c);k({kind:"reconnecting",attempt:b,delayMs:O}),v=setTimeout(()=>{v=null,A()},O)}return A(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),g&&(clearTimeout(g),g=null),p){try{p.close()}catch{}p=null}k({kind:"disconnected",reason:"client closed"})},state(){return x}}}function ty(e){if(e)return e;if(typeof window<"u"){const t=window.__PYRIC_BRIDGE_URL__;if(t)return t;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${Oi}${Ti}`}return`ws://localhost:${Oi}${Ti}`}function ny(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function ry(e,t){try{const n=new URL(e,t.href),r=new URL(t.href),s=t.protocol==="https:"?"wss:":"ws:",i=r.port.length>0,a=n.port.length>0,l=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${l}${n.pathname}`}catch{return e}}function sy(e,t){return{url:t,dispatcher:(n,r,s)=>ch(e,r,s),workerRelay:{op:n=>lh(e,n),subscribe:(n,r)=>uh(e,n,r)}}}async function iy(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 a=t.locationLike??(typeof window<"u"?window.location:null),c=a?ry(i,a):i,l=ey(null,{...sy(e,c),...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",c),l}const ay={};function oy(){return!1}function cy(){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 ly(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=oy(),s=t.persistence==="memory"||r?ou():_f(n),i=t.disableLive?null:um(t.workerUrl),a=i?cy():null;let c=!1,l=null;return i&&a&&iy(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{c?u?.disconnect():l=u}),{mode:e,projects:r?Ef():xf(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){c=!0,l?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const ac=h.createContext(null),uy={status:"pending",env:null,error:null};function dy(e){try{return{status:"ready",env:ly(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function fy({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=dy(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:uy;return o.jsx(ac.Provider,{value:s,children:t})}function pe(){const e=h.useContext(ac);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const hy="pyric-studio:theme",cn="dark";function py(){return cn}function my(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const yy=h.createContext(null);function by({children:e}){const[t,n]=h.useState(py);h.useEffect(()=>{my();try{localStorage.setItem(hy,cn)}catch{}},[t]);const r="dark",s=h.useCallback(c=>n(cn),[]),i=h.useCallback(()=>n(cn),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(yy.Provider,{value:a,children:e})}function Bn(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function gy(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 _s(e,t="",n=Bn()){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)),[a="",...c]=i;return{tab:a,rest:c,query:gy(t)}}function vy(e,t=Bn()){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 oc="studio",wy=[{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 xy({assuranceEnabled:e=!1}={}){return wy.filter(t=>t.id!=="assurance"||e)}const Qe=xy({assuranceEnabled:!1}),jy=Qe.map(e=>e.id);function _y(e){return Qe.find(t=>t.id===e)??Qe[0]}const zr="pyric:studio:navigated",ky={tab:"",rest:[],query:{}};function cc(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Sy(e){return e===""||e===oc?"home":e}function ge(){if(typeof window>"u")return ky;const e=_s(window.location.pathname,window.location.search);return{...e,tab:Sy(e.tab)}}function Ey(e){return e.tab==="home"?{...e,tab:oc}:e}function ft(e){return vy(Ey(e))}function lc(){typeof window<"u"&&window.dispatchEvent(new Event(zr))}function le(e){if(typeof window>"u")return;const t=ft(e);cc()!==t&&(window.history.pushState(null,"",t),lc())}function vn(e){typeof window>"u"||(window.history.replaceState(null,"",ft(e)),lc())}function qt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(zr,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(zr,e)})}function Cy(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(qt,()=>n(ge().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const c=i.slice(1),l=c.indexOf("?"),u=_s(`/${l===-1?c:c.slice(0,l)}`,l===-1?"":c.slice(l),"/");if(e.includes(u.tab)){vn(u);return}}const a=ge();e.includes(a.tab)||vn({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&le({tab:a})},[n,r]);return[r,s]}let Kr=null;function Ny(e){Kr=e}function Ry(){return Kr?(Kr(),!0):!1}function Ay(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function Iy(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 Dy=7;function Py(e,t){const n=e.trim();if(!n)return[];const r=t.filter(m=>m.id!=="settings"),s=[],i=[],a=[],[c="",...l]=n.split(/\s+/),u=l.join(" ");for(const m of r){const f={id:`tab:${m.id}`,label:`Go to ${m.label}`,hint:m.description,target:{tab:m.id}},p=m.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):Iy(n,m.label)&&i.push(f),u&&(p===c.toLowerCase()||p.startsWith(c.toLowerCase()))){const y=u.split("/").filter(Boolean);m.id==="firestore"||m.id==="storage"?a.push({id:`deep:${m.id}:${u}`,label:`Open /${y.join("/")} in ${m.label}`,hint:m.id==="firestore"?"Firestore path":"Storage object path",target:{tab:m.id,rest:y}}):m.id==="auth"?a.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):m.id==="traffic"&&a.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 m=d[1].split("/").filter(Boolean);a.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:m}})}else if(n.includes("/")&&!n.includes(" ")){const m=n.split("/").filter(Boolean);m.length&&a.push({id:`deep:firestore:${n}`,label:`Open /${m.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:m}})}return[...s,...a,...i].slice(0,Dy)}function Hr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const Gr={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function $y(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const c=await t(i.shift());for(const l of c.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...c.prefixes)}return s}async function Oy(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],c=[],l=[...e];let u=0;for(;l.length&&a.length<r&&u<s;){const d=l.shift();u++;let m=[];try{m=await t(d)}catch{continue}for(const f of m){if(a.length>=r)break;const p=`${d}/${f}`;a.push(p);try{const y=await n(p,i);for(const b of y.slice(0,i))c.push(b),l.push(b)}catch{}}}return{subcollections:a,documents:c}}const Ty=5;function wn(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,a=-1,c=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),c=u,i++);if(i!==n.length)return 0;const l=c-a+1;return Math.max(1,400-(l-n.length)*10-Math.min(a,50))}const My={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},Uy=["collection","document","subcollection","user","object","rtdb-key"];function By(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 uc(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function Ly(e,t){const{base:n,trailing:r}=uc(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const a=s.length-1;for(let c=0;c<a;c++)if(s[c].toLowerCase()!==i[c].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:wn(s[a],i[a])}function Fy(e,t){const{base:n,trailing:r}=uc(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:wn(n,s)}function Vi(e,t,n,r=Ty){const s=e.trim();if(!s)return[];const i=[],a=Py(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const c of Uy){const l=c==="document"||c==="subcollection",u=c==="collection"||c==="subcollection",d=new Map;for(const f of n)f.kind===c&&d.set(Hr(f),f);const m=[...d.values()].map(f=>({entry:f,score:Math.max(wn(s,f.label),f.alt?wn(s,f.alt):0,l?Ly(s,f.label):0,u?Fy(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);m.length&&i.push({kind:c,title:My[c],results:m.map(({entry:f})=>({id:Hr(f),label:f.label,hint:By(f),target:f.target}))})}return i}function qi(e){return e.flatMap(t=>t.results)}function Vy(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function Wi(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function qy(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 Wy(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 zy(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function Ky(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function Hy(e,t={},n){const r={...Gr,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},a=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(Vy));const m=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const y=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);m.push(...y),i(y.map(Wi))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await Oy(m,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(qy)),i(p.map(Wi))}catch{}})(),c=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(Wy))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(zy))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(Ky))}catch{}})();return await Promise.allSettled([a,c,l,u]),s}const dc=Symbol("pyric/auth/target"),Gy=Symbol("pyric.user.internal");function q(e,t){return new mt(e,`Firebase: ${t} (${e}).`)}const fc={PASSWORD:"password"},dr={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Ln{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"?Jy(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===fc.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new Yy(i,a,s)}return new Ln(r,s)}}function Jy(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class Yy extends Ln{email;secret;constructor(t,n,r=dr.EMAIL_PASSWORD){super(fc.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===dr.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===dr.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Fn extends Ln{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 ks(e,t){return t?new Fn(e,e):null}class it{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=it.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ks(it.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Fn(it.PROVIDER_ID,it.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class at{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=at.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ks(at.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Fn(at.PROVIDER_ID,at.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class ot{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=ot.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ks(ot.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Fn(ot.PROVIDER_ID,ot.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const hc=[it.PROVIDER_ID,"apple.com",at.PROVIDER_ID,ot.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Ss(e,t=!1){const n=e[dc];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class Qy{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 Xy(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Fe(e){if(typeof e!="string"||e.length===0)throw q("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw q("auth/invalid-email","Error")}function kt(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function pc(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1,nextAnonymousId:1}}}const Zy="__pyric_no_password__";class mc{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new Qy;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;constructor(t,n=t,r=pc(),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(a=>{if(this.applyingTransition)return;const c=a===null?null:a.uid,l=this.cachedUser?.uid??null;c!==l&&(this.cachedUser=this.buildUserFromState(a)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}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){return{email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:new Date().toISOString(),lastLoginAt:null,...t}}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}emitAuthEvent(t,n={}){try{Ie(this.sandbox,Cn({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}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw q("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 n of t){const r=this.usersByUid.get(n.uid);r?.email&&r.email.toLowerCase()!==n.email.toLowerCase()&&this.usersByEmail.delete(r.email.toLowerCase());const s=this.makeStored({uid:n.uid,email:n.email,password:n.password,displayName:n.displayName??null,customClaims:n.customClaims??{},providerUserInfo:[{providerId:n.providerId??"password"}]});this.usersByEmail.set(n.email.toLowerCase(),s),this.usersByUid.set(n.uid,s)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){if(n.email===null)continue;const r={uid:n.uid,email:n.email,password:n.password??Zy,providerId:n.providerUserInfo[0]?.providerId??"password"};n.displayName!==null&&(r.displayName=n.displayName),Object.keys(n.customClaims).length>0&&(r.customClaims=n.customClaims),t.push(r)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw q("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){kt(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){Fe(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw q("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){Fe(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,providerUserInfo:[{providerId:"password"}]});return i.emailVerified=!0,this.usersByEmail.set(n,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i),detail:{emailLink:!0}}),{stored:i,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw q("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(a=>a.providerId===n))throw q("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Fe(i);const a=i.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(kt(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==a&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(a,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 q("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw q("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 q("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Fe(t),kt(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw q("auth/email-already-in-use",`An account already exists for ${t}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i)}),i}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 q("auth/login-blocked",s)}}transitionCurrentUser(t,n){return!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}setCurrentUser(t,n){if(t===null){const a=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}a&&(this.tokenCache.delete(a.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:a.uid,auth:{uid:a.uid}}));return}n!==void 0&&this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=t,this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=i}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:t.uid,auth:i,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,s=this.usersByUid.get(t.uid);s||(s=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous}),this.usersByUid.set(t.uid,s),t.email&&this.usersByEmail.set(t.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(i=>i.providerId===n)||(s.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 q("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=t,i=this.usersByEmail.get(s.email.toLowerCase());i?r=i:(r=this.makeStored({uid:s.uid??eb(),email:s.email,displayName:s.displayName??null,customClaims:s.customClaims??{}}),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,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>this.toRecord(t))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const a of t){const c=a?.providerId?.trim();if(!c)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);c==="password"||c==="anonymous"||s.has(c)||(s.add(c),i.push({providerId:c}))}return n&&i.unshift({providerId:"password"}),i}createUser(t){const n=t.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw q("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Fe(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw q("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(kt(t.password),t.email===void 0))throw q("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}),s}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`No user found for uid ${t}.`);const s=this.toRecord(r);if(n.email!==void 0){Fe(n.email);const a=n.email.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c!==r)throw q("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(a,r)}n.password!==void 0&&(kt(n.password),r.password=n.password,r.providerUserInfo.some(a=>a.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}),i}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw q("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.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 q("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:t.photoUrl,emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo})}mintAnonymousUser(){const t=`anonymous-${this.sharedCounters.nextAnonymousId++}`,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){switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password");case"uid":{const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);if(n.disabled)throw q("auth/user-disabled",`mintSession: user ${t.uid} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password";return this.establishDetachedSession(this.buildUserFromStored(n),r)}}}establishDetachedSession(t,n){this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};return this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:i}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{}})}mintToken(t,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),i=this.nextTokenSerial++,a=Xy(t,n,i),c=this.signInProviderByUid.get(t)??null,l={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(r.getTime()/1e3),iat:Math.floor(r.getTime()/1e3),exp:Math.floor(s.getTime()/1e3),...n,firebase:{sign_in_provider:c}},u={token:a,claims:l,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:c};return{token:a,result:u}}getIdTokenFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.token}const s=this.tokenCache.get(t);if(s)return s.token;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.token}getIdTokenResultFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.result}const s=this.tokenCache.get(t);if(s)return s.result;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",a=t.providers??[{providerId:"password"}],c=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),l={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:c,getIdToken:async u=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0),getIdTokenResult:async u=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0)};return Object.defineProperty(l,Gy,{value:{updateProfile:u=>(this.updateProfileFor(l,u),Promise.resolve()),delete:()=>(this.deleteFor(l),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(l,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(l,u),Promise.resolve()),reload:()=>(this.reloadFor(l),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),l}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 q("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}deleteFor(t){this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){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.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw q("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=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}validatePassword(t,n){if(Fe(t),typeof n!="string"||n.length===0)throw q("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw q("auth/user-not-found",`No user found for ${t}.`);if(r.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw q("auth/wrong-password","Invalid password.");return r}}function eb(){return`provider-${globalThis.crypto.randomUUID()}`}const zi=new WeakSet,Jt=new WeakMap;function yc(e,t,n,r="[DEFAULT]"){return tb(e,t),nb(e,t,n,r)}function tb(e,t){zi.has(e)||(zi.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 Ki(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 nb(e,t,n,r){let s=Jt.get(e);s||(s=new Map,Jt.set(e,s));const i=`auth-session:${r}`,a=s.get(i);if(a){const u=++a.generation;return a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.backend=t,a.session=n,a.unregisterService=e.registerPersistableService(i,Ki(a)),()=>{a.generation===u&&(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&&Jt.delete(e))}}const c={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,c),c.unregisterService=e.registerPersistableService(i,Ki(c));const l=c.generation;return()=>{c.generation===l&&(c.unregisterService?.(),c.unregisterService=void 0,c.unsubscribeBackend?.(),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(i)===c&&s.delete(i),s.size===0&&Jt.delete(e))}}async function wk(e){const{backend:t}=Ss(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 rb(e){const t=Ss(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const Hi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap;function bc(e){let t=Gi.get(e);return t||(t=pc(),Gi.set(e,t)),t}function sb(e){let t=Hi.get(e);return t||(t=new mc(e,e,bc(e)),Hi.set(e,t),yc(e,t,e)),t}function ib(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new mc(n,r,bc(n),i=>{t.onDelete(i)});return t.onDelete(yc(n,s,r,e.name)),s})}function gc(e){if(e===void 0)return gc(bu());const t=gu(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:ib(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return Yi(n,e)});if(ab(e)){let n=Ji.get(e);return n||(n=Yi({kind:"sandbox",sandbox:e,backend:sb(e)}),Ji.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 ab(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function Yi(e,t){const n={[dc]:e,...t?{app:t}:{},signOut(){return rb(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return Ss(e)}const fe={setUser(e,t){K(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){K(e).backend.setResolver(t)},setAuthMailResolver(e,t){K(e).backend.setMailResolver(t)},takeAuthMail(e,t){return K(e).backend.takeMail(t)},listAuthMail(e){return K(e).backend.listMail()},mockActionCode(e,t,n){K(e).backend.stageActionCode(t,n)},listIdentities(e){return K(e).backend.listIdentities()},createSignInCredential(e,t){return K(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new cu("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");K(e).backend.setMockResult(n,t)},seedUsers(e,t){K(e).backend.seedUsers(t)},exportUsers(e){return K(e).backend.exportUsers()},restoreSession(e,t){return K(e).backend.restoreSession(t)},mintSession(e,t){return K(e).backend.mintDetachedSession(t)},listUsers(e){return K(e).backend.listUsers()},createUser(e,t){return K(e).backend.createUser(t)},updateUser(e,t,n){return K(e).backend.updateUser(t,n)},updateProfile(e,t,n){return K(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){K(e).backend.deleteUser(t)},clearUsers(e){K(e).backend.clearUsers()},subscribeUsers(e,t){return K(e).backend.subscribeUsers(t)},getAuthProviderConfig(e){return K(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){K(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){K(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){K(e).backend.setProviderEnforcementDelegated(t)},subscribeAuthProviderConfig(e,t){return K(e).backend.subscribeProviderConfig(t)}};function Ot(e,t){return cb(e)?(Ee(e.storage),new Tt(e.storage,ob(e.fullPath,t??""))):(Ee(e),new Tt(e,vc(t??"")))}class Tt{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Ee(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 Tt(this.storage,n)}get root(){return this.fullPath===""?this:new Tt(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function vc(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function ob(e,t){const n=vc(t);return e===""?n:n===""?e:`${e}/${n}`}function cb(e){if(e===null||typeof e!="object"||Tn in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function lb(e,t){return wc(e,"getBlob"),ub(e,t)}async function Es(e,t){wc(e,"deleteObject");const n=Ee(e.storage),r=gt(n,t),s=await Ft(e.storage),i=await s.backend.getMetadata(e.fullPath);Vt(s,{request:{auth:Ye(n),method:"delete",path:e.fullPath},resource:Un(i)},n,r),await s.backend.delete(e.fullPath);try{Ie(n.sandbox,Cn({service:"storage",op:"object_delete",path:e.fullPath,auth:Ye(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function ub(e,t){const n=Ee(e.storage),r=gt(n),s=await Ft(e.storage),i=await s.backend.getMetadata(e.fullPath);Vt(s,{request:{auth:Ye(n),method:"get",path:e.fullPath},resource:Un(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw Ho(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function wc(e,t){if(e.fullPath==="")throw Mn(t)}function db(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 fb{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_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=db(n,i);const c=Jo({ref:t,blob:this._blob,settable:r}),l=xs(c);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(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Dp(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,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&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const g=a,w=this._error;try{g(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}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 c=i.next;try{c(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 c=i.complete;try{c()}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(){if(this._snapshot.state==="running")try{const n=await Go(this._ref,this._blob,this._metadata,this._provenance);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await Es(this._ref,this._provenance)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function hb(e,t,n,r){if(e.fullPath==="")throw Mn("uploadBytesResumable");return new fb(e,t,n,r)}async function Cs(e){const t=e.storage,n=Ee(t),r=gt(n),s=await Ft(t);Vt(s,{request:{auth:Ye(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),c=[],l=new Set,u=[];for(const d of a){if(!d.fullPath.startsWith(i))continue;const m=d.fullPath.slice(i.length);if(m==="")continue;const f=m.indexOf("/");if(f===-1)c.push(Ot(t,d.fullPath));else{const p=m.slice(0,f),y=`${i}${p}`;l.has(y)||(l.add(y),u.push(Ot(t,y)))}}return u.sort((d,m)=>d.fullPath<m.fullPath?-1:d.fullPath>m.fullPath?1:0),{items:c,prefixes:u}}function pb(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return $f(r,e),r}const mb=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function yb(e){return Qa(e.withAuth(null),mb)}const bb="pyric-studio";function xc(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let gb=0;function vb(e){const t=pb(e,{projectId:"pyric-studio"},`pyric-studio-${gb++}`),n=Nn(e),r=yb(e);return{sandbox:e,app:t,firestore:so(e),adminFirestore:io(r),auth:gc(e),storage:fp(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>xc(n,s)}}function wb(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>vu(),[]),c=h.useMemo(()=>{try{return vb(a)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[a]);return h.useEffect(()=>{let u=!1;if(!e){r(!1);return}return a.enablePersistence({key:bb,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[a,e]),s?{status:"error",handles:null,error:s}:c?e!=null&&n||t==="ready"?{status:"ready",handles:c}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function xb(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=Za(e);return t?t.rules.kind==="evaluated":!1}function jb(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function _b(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 kb(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 Sb(e){const t=[];for(const r of e)xb(r)&&t.push(Eb(r));return kb(t,e).sort((r,s)=>s.at-r.at)}function Eb(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:jb(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),"rules"in e&&e.rules&&(i.rules=e.rules);const a=_b(e);return a!==void 0&&(i.resourceData=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const Qi=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function Cb(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function Nb(e){if(e.rules?.reason==="Validation rule evaluated to false")return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function Rb(e){const t=Cb(e),n=e.reasons.filter(s=>Qi.test(s)),r=e.reasons.filter(s=>!Qi.test(s));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 i=e.matchedRule,a=`Rule #${i.ruleIndex} (${i.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"?Ib(e,n,r):t==="storage"?Db(e,n,r):Ab(e,n,r)}function Ab(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 a=e.matchedRule;i=`Rule #${a.ruleIndex} (${a.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function Ib(e,t,n){const r=e.rules,s=Nb(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let c,l;return i?c=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,c=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,c=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:c,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function Db(e,t,n){const r=e.reasons.find(c=>/^match\s/.test(c)),i=e.reasons.some(c=>/^no rule matches/.test(c))||!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 Pb(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function $b(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:Pb(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}function Ob(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}function Tb(e){const t=Nn(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=>xc(t,n)}}function Me(){const e=Te(),t=pe(),n=t.status==="ready"?t.env.persistence:void 0,r=wb(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=Mb(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:Tb(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 a=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:a,adminFirestore:a,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:c=>s.listSubcollections(c),listDocuments:c=>s.listDocuments(c)}}}return r}}},[e,r,s,i])}function Mb(e){const[t,n]=h.useState([]);return h.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(a=>{r&&n(a)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}const xn=500;function fr(e){return e.length>xn?e.slice(-xn):e}function Wt(){const e=Te(),t=pe(),n=t.status==="ready"?t.env.live?.feed:void 0,r=e.status==="ready",[s,i]=h.useState([]);h.useEffect(()=>{if(r||!n){i([]);return}return i(fr(n.history())),n.subscribe(l=>i(u=>fr(bf(u,l))))},[r,n]);const a=h.useMemo(()=>r?fr(e.events):[],[r,e]);return r?a:s}function Ub(e){return lu(e)}function Bb(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function Lb(e){const t=Za(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};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const c=e.error;c!==void 0&&Bb(c.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let a=[];if(e.reasons!==void 0)a=e.reasons;else{const c=e.error;c!==void 0&&c.reasons!==void 0&&(a=c.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:a,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}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}}function Fb(){const e=Wt();return h.useMemo(()=>e.filter(Ub).map(Lb),[e])}function Vb(){const e=Wt();return h.useMemo(()=>Sb(e),[e])}function qb(){const e=Me();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??We,s=e.firestoreApi?.setDoc??ln;let i=0;const a=[];for(const c of t)try{await s(r(n,c.path),c.data),i++}catch(l){a.push(`${c.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:a}},[e])}function Wb(){const e=Me();return h.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??fe.createUser;let s=0;const i=[];for(const a of t)try{await r(n,a.request),s++}catch(c){const l=a.request.uid??a.request.email??"<auto>";i.push(`${l}: ${c instanceof Error?c.message:String(c)}`)}return{created:s,errors:i}},[e])}function zb(){const e=Me(),t=pe(),n=t.status==="ready"?t.env.live:void 0;return h.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 Kb(){const e=zb(),t=qb(),n=Wb(),r=Te();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await No(async()=>{const{applySeed:c,deploySeedRules:l}=await import("./seed.03a08f9t.js");return{applySeed:c,deploySeedRules:l}},__vite__mapDeps([0,1,2,3,4]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([l,u])=>({path:l,data:u})));const c=i?.authUsers;Array.isArray(c)&&await n(c.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function Ns(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState("");return h.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function Hb(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function Gb(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function Jb(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState([]),s=h.useCallback(async()=>{r(t?await t.listBranches():[])},[t]);h.useEffect(()=>{s()},[s]);const i=h.useCallback(async l=>{t&&(await t.saveBranch(l),await s())},[t,s]),a=h.useCallback(async l=>{t&&await t.switchBranch(l)},[t]),c=h.useCallback(async l=>{t&&(await t.deleteBranch(l),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:c}}function Yb(e="firestore"){const t=Te(),n=t.status==="ready",[r,s]=h.useState({});return h.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(a=>a.ok?a.json():null).then(a=>{if(!i||!a||typeof a!="object")return;const l={};typeof a.rules=="string"&&(l.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?l.rtdb=a.databaseRules:l.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(l.storage=a.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const c=r[a];return c!==void 0?c:""}try{if(a==="rtdb"){const u=go(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return Nn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function Qb(e){let t=!0;return n=>{const r=t;t=!1,e(s=>Zb(s,n,r))}}function Xb(e){const t=new Map;for(const n of e)t.set(Hr(n),n);return[...t.values()]}function Zb(e,t,n){return Xb(n?t:[...e??[],...t])}const eg=3e4;function jc(){const e=Me(),t=pe(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),c=h.useRef(e);c.current=e;const l=t.status==="ready"?t.env.live:void 0,u=h.useRef(l);u.current=l;const d=h.useRef(null),m=h.useRef(0),f=h.useRef(null),p=h.useRef(0),y=h.useCallback(v=>{const g=c.current;if(g.status!=="ready")return;const w=++m.current;a.current=!0,i(!0);const x=g.handles,_=x.adminFirestore,j=g.firestoreApi?.collection??Nt,k=g.firestoreApi?.query??yn,N=g.firestoreApi?.getDocs??mn,A=g.firestoreApi?.limit??bn,R=g.storageApi?.ref??Ot,I=g.storageApi?.listAll??Cs,C=g.authApi?.listUsers??fe.listUsers,S={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(D,V)=>(await N(k(j(_,D),A(V)))).docs.slice(0,V).map(P=>`${D}/${P.id}`),listSubcollections:D=>Promise.resolve(x.listSubcollections(D)),listUsers:async D=>(await Promise.resolve(C(x.auth))).slice(0,D).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:D=>$y(R(x.storage,""),I,{maxObjects:D,maxListCalls:Gr.storageListCalls}),listRtdbTopLevelKeys:async()=>{const D=u.current;if(!D)return[];const V=Date.now()-p.current<eg;if(f.current!==null&&V&&!v?.rtdbLikely)return f.current;const G=await D.readRtdbState(),P=G===null||typeof G!="object"||Array.isArray(G)?[]:Object.keys(G);return f.current=P,p.current=Date.now(),P}},E=Qb(D=>r(D));Hy(S,Gr,D=>{w===m.current&&E(D)}).catch(()=>{}).finally(()=>{if(w===m.current&&(a.current=!1,i(!1),r(D=>D??[]),d.current)){const D=d.current;d.current=null,y(D)}})},[]),b=h.useCallback(v=>{if(c.current.status==="ready"){if(a.current){d.current={...d.current,...v};return}y(v)}},[y]);return h.useEffect(()=>{e.status==="ready"&&n===null&&!a.current&&y()},[e,n,y]),{entries:n,building:s,ensure:b}}const tg=150;function ng(e){return e.startsWith("/")||/rtdb/i.test(e)}function _c({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,c]=h.useState(""),[l,u]=h.useState(0),[d,m]=h.useState(!1),f=h.useRef(null),{entries:p,building:y,ensure:b}=jc();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>c(s),tg);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>Vi(a,Qe,p??[]),[a,p]),g=h.useMemo(()=>qi(v),[v]);h.useEffect(()=>{u(j=>g.length===0?0:Math.min(j,g.length-1))},[g.length]);const w=j=>{j&&(i(""),c(""),m(!1),le(j.target),t?.(j.target))},x=()=>{if(s===a){w(g[l]??g[0]);return}const j=qi(Vi(s,Qe,p??[]));w(j[0])};let _=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.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&&g.length>0,"aria-autocomplete":"list",onFocus:()=>{b(),m(!0)},onBlur:()=>m(!1),onChange:j=>{const k=j.target.value;i(k),m(!0),ng(k)&&b({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(k=>Math.min(k+1,Math.max(g.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(k=>Math.max(k-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),c(""),m(!1)}}})}),d&&!v.length&&y&&p===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const k=_;return _+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,A)=>{const R=k+A;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":R===l,className:"studio-home__command-result","data-active":R===l?"true":void 0,onMouseEnter:()=>u(R),onClick:()=>w(N),children:[o.jsx("span",{className:"studio-home__command-label",children:N.label}),o.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},j.kind)})}):null]})}function rg({onClose:e}){const t=h.useRef(null);return h.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),h.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),o.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:o.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:o.jsx(_c,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const sg={status:"loading",payload:null},Yt={status:"absent",payload:null};let jn=sg,Xi=!1;const Jr=new Set;function Qt(e){jn=e;for(const t of Jr)t()}function ig(){if(!Xi){if(Xi=!0,typeof fetch>"u"){jn=Yt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Qt(Yt);const n=await e.json();Qt({status:"ready",payload:n})}).catch(()=>Qt(Yt))}}function ag(e){return Jr.add(e),ig(),()=>Jr.delete(e)}function Vn(){return h.useSyncExternalStore(ag,()=>jn,()=>jn)}function og(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function cg(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 lg(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?cg(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function ug(e=5e3){const[t,n]=h.useState("checking");return h.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=og(await lg(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",c=()=>{s||(s=setInterval(()=>{a()&&i()},e))},l=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&c()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const dg="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 fg(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 hg(e){return e==="studio"?"Studio":"App"}function pg(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:hg(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:fg(a.lastSeen,n)}));s.sort((a,c)=>a.isThisPage!==c.isThisPage?a.isThisPage?-1:1:a.kindLabel!==c.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(c.route));const i=s.filter(a=>!a.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:dg,otherCount:i}}function mg(){const e=pe(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=h.useState(null);return h.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(pg(i,s))})},[t]),n}const yg={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},bg=()=>()=>{},Zi=()=>yg;function gg(){const e=pe(),t=Vn(),n=ug(),r=mg(),[s,i]=h.useState(!1),a=h.useRef(null),c=e.status==="ready"?e.env.live?.runtime:void 0,l=h.useSyncExternalStore(c?.subscribe??bg,c?.getSnapshot??Zi,c?.getSnapshot??Zi),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,m=e.status==="error",f=l.error?"worker update failed":m?"backend error":d?"worker unreachable":null,p=l.error??(m?e.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics."),y=n==="available";return h.useEffect(()=>{if(!s)return;const b=v=>{v.key==="Escape"&&(i(!1),a.current?.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[s]),o.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[l.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:l.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void c?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:ft({tab:"settings"}),title:p,onClick:b=>{b.preventDefault(),le({tab:"settings"})},children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),f]}):null,r&&r.count>0?o.jsxs("span",{className:"studio-presence",children:[o.jsxs("button",{ref:a,type:"button",className:r.prominent?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger","aria-haspopup":"dialog","aria-expanded":s,"aria-controls":"studio-presence-panel",title:r.otherCount>0?`${r.chipLabel}. ${r.otherCount} other page${r.otherCount===1?"":"s"} can keep the worker alive.`:`${r.chipLabel}. Expand for details.`,onClick:()=>i(b=>!b),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>i(!1)}),o.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[o.jsx("p",{className:"studio-presence__lead",children:r.count===1?"This page is the only connection to the shared sandbox worker.":`${r.count} pages share this sandbox worker. Closing this page alone will not restart it.`}),o.jsx("ul",{className:"studio-presence__list",children:r.clients.map(b=>o.jsxs("li",{className:"studio-presence__item",children:[o.jsxs("div",{className:"studio-presence__item-head",children:[o.jsx("span",{className:"studio-presence__kind",children:b.kindLabel}),b.isThisPage?o.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),o.jsx("div",{className:"studio-presence__route",title:b.route,children:b.route}),o.jsxs("div",{className:"studio-presence__meta",children:[b.visibilityLabel," · ",b.freshnessLabel]})]},b.clientId))}),o.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,y?o.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function vg(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 ea(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 wg({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return h.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let a=s+1;for(;a<e.length&&e[a].groupId===i.groupId;)a++;const c=e.slice(s,a),l=i.origin==="transaction"?"transaction":"batch";r.push(ea(l,i.groupId,c)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&vg(e[a],i);)a++;const c=e.slice(s,a);if(c.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(ea("listener-run",`listener-run:${l}:${s}`,c))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const xg={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function jg({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>_g(e,t,n),[e,t.start,t.end,n])}function _g(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return xg;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let c=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let y=Math.floor((p-t.start)/s);y>=n&&(y=n-1),i[y]++,c++,f.result==="deny"&&(a[y]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const y=a[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:y,allows:f-y,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:y/d}}),total:c,denies:l,maxCount:d,outOfWindow:u}}const kg=new Set(["get","list"]),Sg=new Set(["create","update","set"]),Eg=new Set(["delete","remove"]),Cg=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],Ng=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function qn(e){return e.origin==="admin"}function Rg(e,t=qn){return e.result==="allow"||t(e)?kg.has(e.method)?"reads":Sg.has(e.method)?"writes":Eg.has(e.method)?"deletes":null:null}function Ag(e,t=qn){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const Ig=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function kc(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return Ig(r);const a=i/n,c=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 y=s(f);if(y==null)continue;let b=Math.floor((p-t.start)/a);b>=n&&(b=n-1);const v=c.get(y);v[b]++,l.set(y,(l.get(y)??0)+1)}let u=0;for(const f of c.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*a,end:t.start+(f+1)*a};const m=r.map(f=>({key:f.key,label:f.label,values:c.get(f.key),total:l.get(f.key)??0}));return{points:d,series:m,maxValue:u}}function Dg(e,t,n=24,r=qn){return kc(e,t,n,Cg,s=>Rg(s,r))}function Pg(e,t,n=24,r=qn){return kc(e,t,n,Ng,s=>Ag(s,r))}function $g({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Dg(e,t,n,r),[e,t.start,t.end,n,r])}function Og({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Pg(e,t,n,r),[e,t.start,t.end,n,r])}function Yr({children:e,kind:t,className:n,ariaLabel:r}){return o.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?o.jsx("span",{"aria-hidden":"true",children:e}):e})}function Mt(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Sc({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Mt,className:i}){return o.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:[o.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),o.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),o.jsx(Yr,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var Rs=wu();function nt(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var c,l,u;let d;n.key&&((c=n.debug)!=null&&c.call(n))&&(d=Date.now());const m=e();if(!(m.length!==r.length||m.some((y,b)=>r[b]!==y)))return s;r=m;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...m),n.key&&((u=n.debug)!=null&&u.call(n))){const y=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,v=b/16,g=(w,x)=>{for(w=String(w);w.length<x;)w=" "+w;return w};console.info(`%c⏱ ${g(b,5)} /${g(y,5)} ms`,`
109
+ actual: ${t.join(", ")}`)}function qi(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const xe=e=>e,Wi=(...e)=>xe(e.map(t=>`(${t})`).join(" && ")),Am=(...e)=>xe(e.map(t=>`(${t})`).join(" || ")),ac=e=>e,Im=()=>ac("newData.hasChildren()"),Dm=e=>ac(`newData.hasChild("${e}")`);function oc(e,t){const n=e.shape,r=[],s={};for(const[c,l]of Object.entries(n)){const u=l,d=u instanceof ou,m=d?u.unwrap():u;d||r.push(c);const f=cc(m,c),p=t?.[c];if(p&&p.length>0?s[c]={validate:Wi(f,...p)}:s[c]={validate:f},m instanceof ro){const y=oc(m);s[c]={validate:y.validate,children:y.children}}}const i=[Im()];for(const c of r)i.push(Dm(c));return{validate:Wi(...i),children:s}}function cc(e,t){if(e instanceof cu)return xe("newData.isString()");if(e instanceof lu)return xe("newData.isNumber()");if(e instanceof uu)return xe("newData.isBoolean()");if(e instanceof du){const n=e.options;return xe(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof fu){const n=e.value;return xe(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof hu){const n=e._def.options;return Am(...n.map(r=>cc(r,t)))}if(e instanceof ro)return xe("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function Pm(e){let t;if(typeof e=="function"){const s=[];e({path:(i,a)=>s.push([i,a])}),t=s}else t=Object.entries(e);const n=lc(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,c=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-c||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&$m(r,s);for(const[s,i]of n){const a=s==="/"?r:Ns(r,s);a&&Om(r,a,i,s)}return r}function $m(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("/"),a=n.slice(0,s+1).filter(l=>l.startsWith("$"));let c=r.children.find(l=>l.path===i);c||(c={path:i,pathVariables:a,children:[]},r.children.push(c)),r=c}}function Om(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=st(n.read,"read",s)),n.write&&(t.write=st(n.write,"write",s)),n.validate&&(t.validate=st(n.validate,"validate",s)),n.schema){const i=oc(n.schema,n.fieldConstraints);t.validate||(t.validate=st(i.validate,"validate",s));for(const[a,c]of Object.entries(i.children)){const l=`${r}/${a}`;let u=t.children.find(d=>d.path===l);if(u||(u={path:l,pathVariables:s,children:[]},t.children.push(u)),u.validate=st(c.validate,"validate",s),"children"in c&&c.children)for(const[d,m]of Object.entries(c.children)){const f=`${l}/${d}`;let p=u.children.find(y=>y.path===f);p||(p={path:f,pathVariables:s,children:[]},u.children.push(p)),p.validate=st(m.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const c="/"+i.slice(0,-1).join("/"),l=Ns(e,c);l&&(l.indexOn=n.indexOn)}}}function lc(e){const t=[];for(const[n,r]of e){const{children:s,...i}=r;if(t.push([n,i]),s){const a=Object.entries(s).map(([c,l])=>[n+c,l]);t.push(...lc(a))}}return t}function st(e,t,n){return go(String(e),t,n)}function Ns(e,t){if(e.path===t)return e;for(const n of e.children){const r=Ns(n,t);if(r)return r}return null}function Tm(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function Mm(e){return{operation:e.operation,path:e.path,auth:Tm(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function mr(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Yr(e,t){const n=[...mr(e.path,".read",e.read,t),...mr(e.path,".write",e.write,t),...mr(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...Yr(r,t));return n}class Um{definition;constructor(t){this.definition=t}compile(){return Pm(this.definition.paths)}toJSON(){return Ad(this.compile())}check(){try{const t=this.compile(),n=Yr(t,"errors"),r=Yr(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(t){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:t instanceof Error?t.message:String(t)}],warnings:[]}}}simulate(t){return gs(this.compile(),Mm(t))}}function Bm(e){return new Um(e)}function Lm(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function Fm(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class yr{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>qi(n,"error")),...t.warnings.map(n=>qi(n,"warning"))]}runOne(t){const n=this.doc.simulate({operation:t.operation,path:t.path,auth:t.auth??null,...t.data!==void 0?{data:t.data}:{},...t.newData!==void 0?{newData:t.newData}:{}});if(!n.success)return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:t.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,i=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",a=!s&&i===t.expectation;return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:i,passed:a,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(t){const n=t.map(a=>this.runOne(a));let r=0,s=0,i=0;for(const a of n)a.unsupported?i++:a.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n}}explain(t){const n=this.runOne(t);return{decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason}}toJSON(){return this.doc.toJSON()}}function Vm(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class qm{json;compiled;constructor(t){this.json=t,this.compiled=wo(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return gs(this.compiled,{operation:t.operation,path:t.path,auth:Vm(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function Wm(e){return Lm(e)?new yr(e):Fm(e)?new yr(new qm(e)):new yr(Bm(e))}function zm(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function zi(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Km(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Hm(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 uc(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:zi(e)};const i=Object.entries(e).sort(([m],[f])=>m.localeCompare(f)),a={},c=[];for(const[m,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?c.push([m,f]):a[m]=zi(f);const l=n>=r&&c.length>0,u=i.length>s,d=n>=r?[]:c.slice(0,s).map(([m,f])=>uc(f,zm(t,m),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:a}}function Gm(e,t={}){const n=Km(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return uc(Hm(e,n),n,0,r,s)}function dc(e){return e.children.reduce((t,n)=>t+1+dc(n),0)}function Jm(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, or validate operation against the RTDB rules and data currently loaded in the local sandbox. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=ko(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=hi(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},c={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:a,...n.newData!==void 0?{newData:n.newData}:{}},l=Wm(s).simulate([c]).cases[0];return{ok:!l.unsupported,summary:l.unsupported?`Simulation unsupported: ${l.reason}`:`Simulation: ${l.decision.toLowerCase()}`,data:{decision:l.decision,allowed:l.decision==="ALLOW",unsupported:l.unsupported,matchedPath:l.matchedPath,matchedRule:l.matchedRule,reason:l.reason}}}},{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=Gm(hi(r),n);return{ok:!0,summary:`Crawled ${dc(s)} object paths from ${s.path}`,data:s}}}]}const Ym={"firestore-simulator":({env:e})=>rd({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>wf({resolveDb:e}),"firestore-inspect":({sandbox:e})=>xf({resolveSandbox:()=>e}),"rtdb-inspection":({sandbox:e})=>Jm({resolveSandbox:()=>e})};function Qm(e){const t={sandbox:e,env:Dn(e),resolveDb:n=>n&&n!=="admin"?lo(e.withAuth({uid:n.uid,token:n.claims})):uo(e)};return ic("forwarded").flatMap(n=>Ym[n.key](t))}function Xm(e){const t=Qm(e);Rm("sandbox dispatcher tools",t.map(r=>r.name),fc);const n=new Map(t.map(r=>[r.name,r]));return async(r,s)=>{const i=n.get(r);if(!i)throw new ey(r);const a={signal:new AbortController().signal},c=await i.execute(s,a);return{ok:c.ok,summary:c.summary,data:c.data}}}const Ki=new WeakMap;async function Zm(e,t,n){let r=Ki.get(e);return r||(r=Xm(e),Ki.set(e,r)),r(t,n)}const fc=ic("forwarded").flatMap(e=>e.tools);class ey extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const ty=500,ny=3e4,ry=2e3,sy=.5,iy=3;function ay(e,t={}){const n=oy(t.url),r=t.sandboxId??cy(),s=t.dispatcher??Zm,i=t.toolNames??[...fc],a=t.initialReconnectDelayMs??ty,c=t.maxReconnectDelayMs??ny,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??ry,m=t.fetchImpl??(P=>fetch(P)),f=t.workerRelay??null;let p=null,y=!1,b=0,v=null,g=null,w=0,x={kind:"connecting"};const k=new Map;function j(){for(const P of k.values())try{P()}catch{}k.clear()}function _(P){x=P;try{u(P)}catch{}}function N(P){if(p&&p.readyState===WebSocket.OPEN)try{p.send(JSON.stringify(P))}catch{}}function A(){if(y)return;_({kind:"connecting"});let P;try{P=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}p=P,P.onopen=()=>{b=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[gm]}:{}};N(O)},P.onmessage=O=>{let T;try{T=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(vm(T)){if(T.type==="hello-ack"){_({kind:"connected",bridgeVersion:T.bridgeVersion});return}if(T.type==="tool-call"){R(T);return}if(T.type==="worker-op"){I(T);return}if(T.type==="worker-sub"){C(T);return}if(T.type==="worker-unsub"){const $=k.get(T.subId);if($){k.delete(T.subId);try{$()}catch{}}return}if(T.type==="ping"){N({type:"pong",id:T.id});return}}},P.onclose=O=>{const T=O.reason||`closed (code ${O.code})`;if(p=null,j(),O.code===bm){E();return}G(T)},P.onerror=()=>{}}async function R(P){let O;try{const T=await s(e,P.name,P.args??{});O={type:"tool-result",id:P.id,ok:!0,result:T}}catch(T){O={type:"tool-result",id:P.id,ok:!1,error:{code:T instanceof Error?T.name:"Error",message:T instanceof Error?T.message:String(T)}}}N(O)}async function I(P){if(f)try{const O=await f.op(P.op);Vi(`op '${P.op.method}'`,O),N({type:"worker-res",id:P.id,ok:!0,value:O})}catch(O){const T=O.denialContext;N({type:"worker-res",id:P.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...T!==void 0?{denialContext:T}:{}}})}}function C(P){if(f&&!k.has(P.subId))try{const O=f.subscribe(P.sub,T=>{try{Vi(`subscription '${P.subId}'`,T)}catch($){N({type:"worker-snap",subId:P.subId,value:{__error:{code:$.code??"invalid-argument",message:$ instanceof Error?$.message:String($)}}});return}N({type:"worker-snap",subId:P.subId,value:T})});k.set(P.subId,O)}catch(O){const T=O.denialContext;N({type:"worker-snap",subId:P.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...T!==void 0?{denialContext:T}:{}}}})}}function S(){try{const P=new URL(n);P.protocol=P.protocol==="wss:"?"https:":"http:";const O=P.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(l){_({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}b=0,w=0,_({kind:"standby"}),D()}}function D(){if(y)return;const P=d*(1+Math.random()*sy);g=setTimeout(()=>{g=null,V()},P)}async function V(){if(y)return;let P=null;for(const O of S())try{const T=await m(O);if(!T.ok)continue;const $=await T.json();if(typeof $.sandboxConnected=="boolean"){P=!$.sandboxConnected;break}}catch{}if(!y){if(P===!0){A();return}if(P===!1){w=0,D();return}if(w+=1,w>=iy){G("standby health poll unreachable");return}D()}}function G(P){if(y)return;if(l){_({kind:"disconnected",reason:P});return}b+=1;const O=Math.min(a*2**(b-1),c);_({kind:"reconnecting",attempt:b,delayMs:O}),v=setTimeout(()=>{v=null,A()},O)}return A(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),g&&(clearTimeout(g),g=null),p){try{p.close()}catch{}p=null}_({kind:"disconnected",reason:"client closed"})},state(){return x}}}function oy(e){if(e)return e;if(typeof window<"u"){const t=window.__PYRIC_BRIDGE_URL__;if(t)return t;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${Li}${Fi}`}return`ws://localhost:${Li}${Fi}`}function cy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function ly(e,t){try{const n=new URL(e,t.href),r=new URL(t.href),s=t.protocol==="https:"?"wss:":"ws:",i=r.port.length>0,a=n.port.length>0,l=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${l}${n.pathname}`}catch{return e}}function uy(e,t){return{url:t,dispatcher:(n,r,s)=>mh(e,r,s),workerRelay:{op:n=>yh(e,n),subscribe:(n,r)=>bh(e,n,r)}}}async function dy(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 a=t.locationLike??(typeof window<"u"?window.location:null),c=a?ly(i,a):i,l=ay(null,{...uy(e,c),...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",c),l}const fy={};function hy(){return!1}function py(){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 my(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=hy(),s=t.persistence==="memory"||r?pu():Af(n),i=t.disableLive?null:ym(t.workerUrl),a=i?py():null;let c=!1,l=null;return i&&a&&dy(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{c?u?.disconnect():l=u}),{mode:e,projects:r?Pf():Nf(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){c=!0,l?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const hc=h.createContext(null),yy={status:"pending",env:null,error:null};function by(e){try{return{status:"ready",env:my(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function gy({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=by(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:yy;return o.jsx(hc.Provider,{value:s,children:t})}function be(){const e=h.useContext(hc);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const vy="pyric-studio:theme",dn="dark";function wy(){return dn}function xy(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const jy=h.createContext(null);function ky({children:e}){const[t,n]=h.useState(wy);h.useEffect(()=>{xy();try{localStorage.setItem(vy,dn)}catch{}},[t]);const r="dark",s=h.useCallback(c=>n(dn),[]),i=h.useCallback(()=>n(dn),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(jy.Provider,{value:a,children:e})}function Wn(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function _y(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 Rs(e,t="",n=Wn()){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)),[a="",...c]=i;return{tab:a,rest:c,query:_y(t)}}function Sy(e,t=Wn()){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 pc="studio",Ey=[{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 Cy({assuranceEnabled:e=!1}={}){return Ey.filter(t=>t.id!=="assurance"||e)}const et=Cy({assuranceEnabled:!1}),Ny=et.map(e=>e.id);function Ry(e){return et.find(t=>t.id===e)??et[0]}const Qr="pyric:studio:navigated",Ay={tab:"",rest:[],query:{}};function mc(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Iy(e){return e===""||e===pc?"home":e}function we(){if(typeof window>"u")return Ay;const e=Rs(window.location.pathname,window.location.search);return{...e,tab:Iy(e.tab)}}function Dy(e){return e.tab==="home"?{...e,tab:pc}:e}function mt(e){return Sy(Dy(e))}function yc(){typeof window<"u"&&window.dispatchEvent(new Event(Qr))}function de(e){if(typeof window>"u")return;const t=mt(e);mc()!==t&&(window.history.pushState(null,"",t),yc())}function kn(e){typeof window>"u"||(window.history.replaceState(null,"",mt(e)),yc())}function Kt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Qr,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Qr,e)})}function Py(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(Kt,()=>n(we().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const c=i.slice(1),l=c.indexOf("?"),u=Rs(`/${l===-1?c:c.slice(0,l)}`,l===-1?"":c.slice(l),"/");if(e.includes(u.tab)){kn(u);return}}const a=we();e.includes(a.tab)||kn({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&de({tab:a})},[n,r]);return[r,s]}let Xr=null;function $y(e){Xr=e}function Oy(){return Xr?(Xr(),!0):!1}function Ty(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function My(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 Uy=7;function By(e,t){const n=e.trim();if(!n)return[];const r=t.filter(m=>m.id!=="settings"),s=[],i=[],a=[],[c="",...l]=n.split(/\s+/),u=l.join(" ");for(const m of r){const f={id:`tab:${m.id}`,label:`Go to ${m.label}`,hint:m.description,target:{tab:m.id}},p=m.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):My(n,m.label)&&i.push(f),u&&(p===c.toLowerCase()||p.startsWith(c.toLowerCase()))){const y=u.split("/").filter(Boolean);m.id==="firestore"||m.id==="storage"?a.push({id:`deep:${m.id}:${u}`,label:`Open /${y.join("/")} in ${m.label}`,hint:m.id==="firestore"?"Firestore path":"Storage object path",target:{tab:m.id,rest:y}}):m.id==="auth"?a.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):m.id==="traffic"&&a.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 m=d[1].split("/").filter(Boolean);a.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:m}})}else if(n.includes("/")&&!n.includes(" ")){const m=n.split("/").filter(Boolean);m.length&&a.push({id:`deep:firestore:${n}`,label:`Open /${m.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:m}})}return[...s,...a,...i].slice(0,Uy)}function Zr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const es={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function Ly(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const c=await t(i.shift());for(const l of c.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...c.prefixes)}return s}async function Fy(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],c=[],l=[...e];let u=0;for(;l.length&&a.length<r&&u<s;){const d=l.shift();u++;let m=[];try{m=await t(d)}catch{continue}for(const f of m){if(a.length>=r)break;const p=`${d}/${f}`;a.push(p);try{const y=await n(p,i);for(const b of y.slice(0,i))c.push(b),l.push(b)}catch{}}}return{subcollections:a,documents:c}}const Vy=5;function _n(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,a=-1,c=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),c=u,i++);if(i!==n.length)return 0;const l=c-a+1;return Math.max(1,400-(l-n.length)*10-Math.min(a,50))}const qy={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},Wy=["collection","document","subcollection","user","object","rtdb-key"];function zy(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 bc(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function Ky(e,t){const{base:n,trailing:r}=bc(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const a=s.length-1;for(let c=0;c<a;c++)if(s[c].toLowerCase()!==i[c].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:_n(s[a],i[a])}function Hy(e,t){const{base:n,trailing:r}=bc(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:_n(n,s)}function Hi(e,t,n,r=Vy){const s=e.trim();if(!s)return[];const i=[],a=By(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const c of Wy){const l=c==="document"||c==="subcollection",u=c==="collection"||c==="subcollection",d=new Map;for(const f of n)f.kind===c&&d.set(Zr(f),f);const m=[...d.values()].map(f=>({entry:f,score:Math.max(_n(s,f.label),f.alt?_n(s,f.alt):0,l?Ky(s,f.label):0,u?Hy(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);m.length&&i.push({kind:c,title:qy[c],results:m.map(({entry:f})=>({id:Zr(f),label:f.label,hint:zy(f),target:f.target}))})}return i}function Gi(e){return e.flatMap(t=>t.results)}function Gy(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function Ji(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function Jy(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 Yy(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 Qy(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function Xy(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function Zy(e,t={},n){const r={...es,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},a=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(Gy));const m=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const y=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);m.push(...y),i(y.map(Ji))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await Fy(m,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(Jy)),i(p.map(Ji))}catch{}})(),c=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(Yy))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(Qy))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(Xy))}catch{}})();return await Promise.allSettled([a,c,l,u]),s}const gc=Symbol("pyric/auth/target"),eb=Symbol("pyric.user.internal");function q(e,t){return new gt(e,`Firebase: ${t} (${e}).`)}const vc={PASSWORD:"password"},br={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class zn{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"?tb(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===vc.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new nb(i,a,s)}return new zn(r,s)}}function tb(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class nb extends zn{email;secret;constructor(t,n,r=br.EMAIL_PASSWORD){super(vc.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===br.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===br.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Kn extends zn{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 As(e,t){return t?new Kn(e,e):null}class ct{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=ct.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return As(ct.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Kn(ct.PROVIDER_ID,ct.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class lt{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=lt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return As(lt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Kn(lt.PROVIDER_ID,lt.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class ut{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=ut.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return As(ut.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Kn(ut.PROVIDER_ID,ut.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const wc=[ct.PROVIDER_ID,"apple.com",lt.PROVIDER_ID,ut.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Is(e,t=!1){const n=e[gc];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class rb{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 sb(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function We(e){if(typeof e!="string"||e.length===0)throw q("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw q("auth/invalid-email","Error")}function Ct(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function xc(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1,nextAnonymousId:1}}}const ib="__pyric_no_password__";class jc{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new rb;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;constructor(t,n=t,r=xc(),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(a=>{if(this.applyingTransition)return;const c=a===null?null:a.uid,l=this.cachedUser?.uid??null;c!==l&&(this.cachedUser=this.buildUserFromState(a)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}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){return{email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:new Date().toISOString(),lastLoginAt:null,...t}}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}emitAuthEvent(t,n={}){try{Pe(this.sandbox,In({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}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw q("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 n of t){const r=this.usersByUid.get(n.uid);r?.email&&r.email.toLowerCase()!==n.email.toLowerCase()&&this.usersByEmail.delete(r.email.toLowerCase());const s=this.makeStored({uid:n.uid,email:n.email,password:n.password,displayName:n.displayName??null,customClaims:n.customClaims??{},providerUserInfo:[{providerId:n.providerId??"password"}]});this.usersByEmail.set(n.email.toLowerCase(),s),this.usersByUid.set(n.uid,s)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){if(n.email===null)continue;const r={uid:n.uid,email:n.email,password:n.password??ib,providerId:n.providerUserInfo[0]?.providerId??"password"};n.displayName!==null&&(r.displayName=n.displayName),Object.keys(n.customClaims).length>0&&(r.customClaims=n.customClaims),t.push(r)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw q("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){Ct(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){We(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw q("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){We(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,providerUserInfo:[{providerId:"password"}]});return i.emailVerified=!0,this.usersByEmail.set(n,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i),detail:{emailLink:!0}}),{stored:i,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw q("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(a=>a.providerId===n))throw q("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){We(i);const a=i.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(Ct(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==a&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(a,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 q("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw q("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 q("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){We(t),Ct(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw q("auth/email-already-in-use",`An account already exists for ${t}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i)}),i}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 q("auth/login-blocked",s)}}transitionCurrentUser(t,n){return!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}setCurrentUser(t,n){if(t===null){const a=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}a&&(this.tokenCache.delete(a.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:a.uid,auth:{uid:a.uid}}));return}n!==void 0&&this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=t,this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=i}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:t.uid,auth:i,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,s=this.usersByUid.get(t.uid);s||(s=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous}),this.usersByUid.set(t.uid,s),t.email&&this.usersByEmail.set(t.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(i=>i.providerId===n)||(s.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 q("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=t,i=this.usersByEmail.get(s.email.toLowerCase());i?r=i:(r=this.makeStored({uid:s.uid??ab(),email:s.email,displayName:s.displayName??null,customClaims:s.customClaims??{}}),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,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>this.toRecord(t))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const a of t){const c=a?.providerId?.trim();if(!c)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);c==="password"||c==="anonymous"||s.has(c)||(s.add(c),i.push({providerId:c}))}return n&&i.unshift({providerId:"password"}),i}createUser(t){const n=t.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw q("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(We(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw q("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(Ct(t.password),t.email===void 0))throw q("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}),s}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`No user found for uid ${t}.`);const s=this.toRecord(r);if(n.email!==void 0){We(n.email);const a=n.email.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c!==r)throw q("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(a,r)}n.password!==void 0&&(Ct(n.password),r.password=n.password,r.providerUserInfo.some(a=>a.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}),i}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw q("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.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 q("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:t.photoUrl,emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo})}mintAnonymousUser(){const t=`anonymous-${this.sharedCounters.nextAnonymousId++}`,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){switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password");case"uid":{const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);if(n.disabled)throw q("auth/user-disabled",`mintSession: user ${t.uid} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password";return this.establishDetachedSession(this.buildUserFromStored(n),r)}}}establishDetachedSession(t,n){this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};return this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:i}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{}})}mintToken(t,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),i=this.nextTokenSerial++,a=sb(t,n,i),c=this.signInProviderByUid.get(t)??null,l={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(r.getTime()/1e3),iat:Math.floor(r.getTime()/1e3),exp:Math.floor(s.getTime()/1e3),...n,firebase:{sign_in_provider:c}},u={token:a,claims:l,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:c};return{token:a,result:u}}getIdTokenFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.token}const s=this.tokenCache.get(t);if(s)return s.token;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.token}getIdTokenResultFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.result}const s=this.tokenCache.get(t);if(s)return s.result;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",a=t.providers??[{providerId:"password"}],c=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),l={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:c,getIdToken:async u=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0),getIdTokenResult:async u=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0)};return Object.defineProperty(l,eb,{value:{updateProfile:u=>(this.updateProfileFor(l,u),Promise.resolve()),delete:()=>(this.deleteFor(l),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(l,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(l,u),Promise.resolve()),reload:()=>(this.reloadFor(l),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),l}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 q("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}deleteFor(t){this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){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.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw q("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=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}validatePassword(t,n){if(We(t),typeof n!="string"||n.length===0)throw q("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw q("auth/user-not-found",`No user found for ${t}.`);if(r.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw q("auth/wrong-password","Invalid password.");return r}}function ab(){return`provider-${globalThis.crypto.randomUUID()}`}const Yi=new WeakSet,Xt=new WeakMap;function kc(e,t,n,r="[DEFAULT]"){return ob(e,t),cb(e,t,n,r)}function ob(e,t){Yi.has(e)||(Yi.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 Qi(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 cb(e,t,n,r){let s=Xt.get(e);s||(s=new Map,Xt.set(e,s));const i=`auth-session:${r}`,a=s.get(i);if(a){const u=++a.generation;return a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.backend=t,a.session=n,a.unregisterService=e.registerPersistableService(i,Qi(a)),()=>{a.generation===u&&(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&&Xt.delete(e))}}const c={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,c),c.unregisterService=e.registerPersistableService(i,Qi(c));const l=c.generation;return()=>{c.generation===l&&(c.unregisterService?.(),c.unregisterService=void 0,c.unsubscribeBackend?.(),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(i)===c&&s.delete(i),s.size===0&&Xt.delete(e))}}async function E_(e){const{backend:t}=Is(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 lb(e){const t=Is(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const Xi=new WeakMap,Zi=new WeakMap,ea=new WeakMap;function _c(e){let t=Zi.get(e);return t||(t=xc(),Zi.set(e,t)),t}function ub(e){let t=Xi.get(e);return t||(t=new jc(e,e,_c(e)),Xi.set(e,t),kc(e,t,e)),t}function db(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new jc(n,r,_c(n),i=>{t.onDelete(i)});return t.onDelete(kc(n,s,r,e.name)),s})}function Sc(e){if(e===void 0)return Sc(_u());const t=Su(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:db(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return ta(n,e)});if(fb(e)){let n=ea.get(e);return n||(n=ta({kind:"sandbox",sandbox:e,backend:ub(e)}),ea.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 fb(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function ta(e,t){const n={[gc]:e,...t?{app:t}:{},signOut(){return lb(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return Is(e)}const me={setUser(e,t){K(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){K(e).backend.setResolver(t)},setAuthMailResolver(e,t){K(e).backend.setMailResolver(t)},takeAuthMail(e,t){return K(e).backend.takeMail(t)},listAuthMail(e){return K(e).backend.listMail()},mockActionCode(e,t,n){K(e).backend.stageActionCode(t,n)},listIdentities(e){return K(e).backend.listIdentities()},createSignInCredential(e,t){return K(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new mu("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");K(e).backend.setMockResult(n,t)},seedUsers(e,t){K(e).backend.seedUsers(t)},exportUsers(e){return K(e).backend.exportUsers()},restoreSession(e,t){return K(e).backend.restoreSession(t)},mintSession(e,t){return K(e).backend.mintDetachedSession(t)},listUsers(e){return K(e).backend.listUsers()},createUser(e,t){return K(e).backend.createUser(t)},updateUser(e,t,n){return K(e).backend.updateUser(t,n)},updateProfile(e,t,n){return K(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){K(e).backend.deleteUser(t)},clearUsers(e){K(e).backend.clearUsers()},subscribeUsers(e,t){return K(e).backend.subscribeUsers(t)},getAuthProviderConfig(e){return K(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){K(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){K(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){K(e).backend.setProviderEnforcementDelegated(t)},subscribeAuthProviderConfig(e,t){return K(e).backend.subscribeProviderConfig(t)}};function Ut(e,t){return pb(e)?(Ne(e.storage),new Bt(e.storage,hb(e.fullPath,t??""))):(Ne(e),new Bt(e,Ec(t??"")))}class Bt{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Ne(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 Bt(this.storage,n)}get root(){return this.fullPath===""?this:new Bt(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Ec(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function hb(e,t){const n=Ec(t);return e===""?n:n===""?e:`${e}/${n}`}function pb(e){if(e===null||typeof e!="object"||Fn in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function mb(e,t){return Cc(e,"getBlob"),yb(e,t)}async function Ds(e,t){Cc(e,"deleteObject");const n=Ne(e.storage),r=xt(n,t),s=await Wt(e.storage),i=await s.backend.getMetadata(e.fullPath);zt(s,{request:{auth:Ze(n),method:"delete",path:e.fullPath},resource:qn(i)},n,r),await s.backend.delete(e.fullPath);try{Pe(n.sandbox,In({service:"storage",op:"object_delete",path:e.fullPath,auth:Ze(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function yb(e,t){const n=Ne(e.storage),r=xt(n),s=await Wt(e.storage),i=await s.backend.getMetadata(e.fullPath);zt(s,{request:{auth:Ze(n),method:"get",path:e.fullPath},resource:qn(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw ec(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function Cc(e,t){if(e.fullPath==="")throw Vn(t)}function bb(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 gb{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_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=bb(n,i);const c=nc({ref:t,blob:this._blob,settable:r}),l=Cs(c);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(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Up(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,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&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const g=a,w=this._error;try{g(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}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 c=i.next;try{c(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 c=i.complete;try{c()}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(){if(this._snapshot.state==="running")try{const n=await tc(this._ref,this._blob,this._metadata,this._provenance);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await Ds(this._ref,this._provenance)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function vb(e,t,n,r){if(e.fullPath==="")throw Vn("uploadBytesResumable");return new gb(e,t,n,r)}async function Ps(e){const t=e.storage,n=Ne(t),r=xt(n),s=await Wt(t);zt(s,{request:{auth:Ze(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),c=[],l=new Set,u=[];for(const d of a){if(!d.fullPath.startsWith(i))continue;const m=d.fullPath.slice(i.length);if(m==="")continue;const f=m.indexOf("/");if(f===-1)c.push(Ut(t,d.fullPath));else{const p=m.slice(0,f),y=`${i}${p}`;l.has(y)||(l.add(y),u.push(Ut(t,y)))}}return u.sort((d,m)=>d.fullPath<m.fullPath?-1:d.fullPath>m.fullPath?1:0),{items:c,prefixes:u}}function wb(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return Ff(r,e),r}const xb=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function jb(e){return no(e.withAuth(null),xb)}const kb="pyric-studio";function Nc(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let _b=0;function Sb(e){const t=wb(e,{projectId:"pyric-studio"},`pyric-studio-${_b++}`),n=Dn(e),r=jb(e);return{sandbox:e,app:t,firestore:lo(e),adminFirestore:uo(r),auth:Sc(e),storage:gp(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>Nc(n,s)}}function Eb(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>Eu(),[]),c=h.useMemo(()=>{try{return Sb(a)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[a]);return h.useEffect(()=>{let u=!1;if(!e){r(!1);return}return a.enablePersistence({key:kb,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[a,e]),s?{status:"error",handles:null,error:s}:c?e!=null&&n||t==="ready"?{status:"ready",handles:c}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function Cb(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=so(e);return t?t.rules.kind==="evaluated":!1}function Nb(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function Rb(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 Ab(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 Ib(e){const t=[];for(const r of e)Cb(r)&&t.push(Db(r));return Ab(t,e).sort((r,s)=>s.at-r.at)}function Db(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:Nb(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),"rules"in e&&e.rules&&(i.rules=e.rules);const a=Rb(e);return a!==void 0&&(i.resourceData=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const na=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function Pb(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function $b(e){if(e.rules?.reason==="Validation rule evaluated to false")return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function Ob(e){const t=Pb(e),n=e.reasons.filter(s=>na.test(s)),r=e.reasons.filter(s=>!na.test(s));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 i=e.matchedRule,a=`Rule #${i.ruleIndex} (${i.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"?Mb(e,n,r):t==="storage"?Ub(e,n,r):Tb(e,n,r)}function Tb(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 a=e.matchedRule;i=`Rule #${a.ruleIndex} (${a.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function Mb(e,t,n){const r=e.rules,s=$b(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let c,l;return i?c=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,c=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,c=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:c,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function Ub(e,t,n){const r=e.reasons.find(c=>/^match\s/.test(c)),i=e.reasons.some(c=>/^no rule matches/.test(c))||!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 Bb(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function Lb(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:Bb(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}function Fb(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}function Vb(e){const t=Dn(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=>Nc(t,n)}}function Be(){const e=Ue(),t=be(),n=t.status==="ready"?t.env.persistence:void 0,r=Eb(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=qb(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:Vb(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 a=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:a,adminFirestore:a,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:c=>s.listSubcollections(c),listDocuments:c=>s.listDocuments(c)}}}return r}}},[e,r,s,i])}function qb(e){const[t,n]=h.useState([]);return h.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(a=>{r&&n(a)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}const Sn=500;function gr(e){return e.length>Sn?e.slice(-Sn):e}function Ht(){const e=Ue(),t=be(),n=t.status==="ready"?t.env.live?.feed:void 0,r=e.status==="ready",[s,i]=h.useState([]);h.useEffect(()=>{if(r||!n){i([]);return}return i(gr(n.history())),n.subscribe(l=>i(u=>gr(_f(u,l))))},[r,n]);const a=h.useMemo(()=>r?gr(e.events):[],[r,e]);return r?a:s}function Wb(e){return yu(e)}function zb(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function Kb(e){const t=so(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};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const c=e.error;c!==void 0&&zb(c.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let a=[];if(e.reasons!==void 0)a=e.reasons;else{const c=e.error;c!==void 0&&c.reasons!==void 0&&(a=c.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:a,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}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}}function Hb(){const e=Ht();return h.useMemo(()=>e.filter(Wb).map(Kb),[e])}function Gb(){const e=Ht();return h.useMemo(()=>Ib(e),[e])}function Jb(){const e=Be();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??He,s=e.firestoreApi?.setDoc??fn;let i=0;const a=[];for(const c of t)try{await s(r(n,c.path),c.data),i++}catch(l){a.push(`${c.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:a}},[e])}function Yb(){const e=Be();return h.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??me.createUser;let s=0;const i=[];for(const a of t)try{await r(n,a.request),s++}catch(c){const l=a.request.uid??a.request.email??"<auto>";i.push(`${l}: ${c instanceof Error?c.message:String(c)}`)}return{created:s,errors:i}},[e])}function Qb(){const e=Be(),t=be(),n=t.status==="ready"?t.env.live:void 0;return h.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 Xb(){const e=Qb(),t=Jb(),n=Yb(),r=Ue();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await Po(async()=>{const{applySeed:c,deploySeedRules:l}=await import("./seed.lywYbXZ0.js");return{applySeed:c,deploySeedRules:l}},__vite__mapDeps([0,1,2,3,4]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([l,u])=>({path:l,data:u})));const c=i?.authUsers;Array.isArray(c)&&await n(c.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function $s(){const e=be(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState("");return h.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function Zb(){const e=be(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function eg(){const e=be(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function tg(){const e=be(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState([]),s=h.useCallback(async()=>{r(t?await t.listBranches():[])},[t]);h.useEffect(()=>{s()},[s]);const i=h.useCallback(async l=>{t&&(await t.saveBranch(l),await s())},[t,s]),a=h.useCallback(async l=>{t&&await t.switchBranch(l)},[t]),c=h.useCallback(async l=>{t&&(await t.deleteBranch(l),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:c}}function ng(e="firestore"){const t=Ue(),n=t.status==="ready",[r,s]=h.useState({});return h.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(a=>a.ok?a.json():null).then(a=>{if(!i||!a||typeof a!="object")return;const l={};typeof a.rules=="string"&&(l.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?l.rtdb=a.databaseRules:l.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(l.storage=a.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const c=r[a];return c!==void 0?c:""}try{if(a==="rtdb"){const u=ko(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return Dn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function rg(e){let t=!0;return n=>{const r=t;t=!1,e(s=>ig(s,n,r))}}function sg(e){const t=new Map;for(const n of e)t.set(Zr(n),n);return[...t.values()]}function ig(e,t,n){return sg(n?t:[...e??[],...t])}const ag=3e4;function Rc(){const e=Be(),t=be(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),c=h.useRef(e);c.current=e;const l=t.status==="ready"?t.env.live:void 0,u=h.useRef(l);u.current=l;const d=h.useRef(null),m=h.useRef(0),f=h.useRef(null),p=h.useRef(0),y=h.useCallback(v=>{const g=c.current;if(g.status!=="ready")return;const w=++m.current;a.current=!0,i(!0);const x=g.handles,k=x.adminFirestore,j=g.firestoreApi?.collection??It,_=g.firestoreApi?.query??vn,N=g.firestoreApi?.getDocs??gn,A=g.firestoreApi?.limit??wn,R=g.storageApi?.ref??Ut,I=g.storageApi?.listAll??Ps,C=g.authApi?.listUsers??me.listUsers,S={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(D,V)=>(await N(_(j(k,D),A(V)))).docs.slice(0,V).map(P=>`${D}/${P.id}`),listSubcollections:D=>Promise.resolve(x.listSubcollections(D)),listUsers:async D=>(await Promise.resolve(C(x.auth))).slice(0,D).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:D=>Ly(R(x.storage,""),I,{maxObjects:D,maxListCalls:es.storageListCalls}),listRtdbTopLevelKeys:async()=>{const D=u.current;if(!D)return[];const V=Date.now()-p.current<ag;if(f.current!==null&&V&&!v?.rtdbLikely)return f.current;const G=await D.readRtdbState(),P=G===null||typeof G!="object"||Array.isArray(G)?[]:Object.keys(G);return f.current=P,p.current=Date.now(),P}},E=rg(D=>r(D));Zy(S,es,D=>{w===m.current&&E(D)}).catch(()=>{}).finally(()=>{if(w===m.current&&(a.current=!1,i(!1),r(D=>D??[]),d.current)){const D=d.current;d.current=null,y(D)}})},[]),b=h.useCallback(v=>{if(c.current.status==="ready"){if(a.current){d.current={...d.current,...v};return}y(v)}},[y]);return h.useEffect(()=>{e.status==="ready"&&n===null&&!a.current&&y()},[e,n,y]),{entries:n,building:s,ensure:b}}const og=150;function cg(e){return e.startsWith("/")||/rtdb/i.test(e)}function Ac({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,c]=h.useState(""),[l,u]=h.useState(0),[d,m]=h.useState(!1),f=h.useRef(null),{entries:p,building:y,ensure:b}=Rc();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>c(s),og);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>Hi(a,et,p??[]),[a,p]),g=h.useMemo(()=>Gi(v),[v]);h.useEffect(()=>{u(j=>g.length===0?0:Math.min(j,g.length-1))},[g.length]);const w=j=>{j&&(i(""),c(""),m(!1),de(j.target),t?.(j.target))},x=()=>{if(s===a){w(g[l]??g[0]);return}const j=Gi(Hi(s,et,p??[]));w(j[0])};let k=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.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&&g.length>0,"aria-autocomplete":"list",onFocus:()=>{b(),m(!0)},onBlur:()=>m(!1),onChange:j=>{const _=j.target.value;i(_),m(!0),cg(_)&&b({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(_=>Math.min(_+1,Math.max(g.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(_=>Math.max(_-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),c(""),m(!1)}}})}),d&&!v.length&&y&&p===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const _=k;return k+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,A)=>{const R=_+A;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":R===l,className:"studio-home__command-result","data-active":R===l?"true":void 0,onMouseEnter:()=>u(R),onClick:()=>w(N),children:[o.jsx("span",{className:"studio-home__command-label",children:N.label}),o.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},j.kind)})}):null]})}function lg({onClose:e}){const t=h.useRef(null);return h.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),h.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),o.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:o.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:o.jsx(Ac,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const ug={status:"loading",payload:null},Zt={status:"absent",payload:null};let En=ug,ra=!1;const ts=new Set;function en(e){En=e;for(const t of ts)t()}function dg(){if(!ra){if(ra=!0,typeof fetch>"u"){En=Zt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return en(Zt);const n=await e.json();en({status:"ready",payload:n})}).catch(()=>en(Zt))}}function fg(e){return ts.add(e),dg(),()=>ts.delete(e)}function Hn(){return h.useSyncExternalStore(fg,()=>En,()=>En)}function hg(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function pg(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 mg(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?pg(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function yg(e=5e3){const[t,n]=h.useState("checking");return h.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=hg(await mg(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",c=()=>{s||(s=setInterval(()=>{a()&&i()},e))},l=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&c()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const bg="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 gg(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 vg(e){return e==="studio"?"Studio":"App"}function wg(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:vg(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:gg(a.lastSeen,n)}));s.sort((a,c)=>a.isThisPage!==c.isThisPage?a.isThisPage?-1:1:a.kindLabel!==c.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(c.route));const i=s.filter(a=>!a.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:bg,otherCount:i}}function xg(){const e=be(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=h.useState(null);return h.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(wg(i,s))})},[t]),n}const jg={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},kg=()=>()=>{},sa=()=>jg;function _g(){const e=be(),t=Hn(),n=yg(),r=xg(),[s,i]=h.useState(!1),a=h.useRef(null),c=e.status==="ready"?e.env.live?.runtime:void 0,l=h.useSyncExternalStore(c?.subscribe??kg,c?.getSnapshot??sa,c?.getSnapshot??sa),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,m=e.status==="error",f=l.error?"worker update failed":m?"backend error":d?"worker unreachable":null,p=l.error??(m?e.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics."),y=n==="available";return h.useEffect(()=>{if(!s)return;const b=v=>{v.key==="Escape"&&(i(!1),a.current?.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[s]),o.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[l.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:l.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void c?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:mt({tab:"settings"}),title:p,onClick:b=>{b.preventDefault(),de({tab:"settings"})},children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),f]}):null,r&&r.count>0?o.jsxs("span",{className:"studio-presence",children:[o.jsxs("button",{ref:a,type:"button",className:r.prominent?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger","aria-haspopup":"dialog","aria-expanded":s,"aria-controls":"studio-presence-panel",title:r.otherCount>0?`${r.chipLabel}. ${r.otherCount} other page${r.otherCount===1?"":"s"} can keep the worker alive.`:`${r.chipLabel}. Expand for details.`,onClick:()=>i(b=>!b),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>i(!1)}),o.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[o.jsx("p",{className:"studio-presence__lead",children:r.count===1?"This page is the only connection to the shared sandbox worker.":`${r.count} pages share this sandbox worker. Closing this page alone will not restart it.`}),o.jsx("ul",{className:"studio-presence__list",children:r.clients.map(b=>o.jsxs("li",{className:"studio-presence__item",children:[o.jsxs("div",{className:"studio-presence__item-head",children:[o.jsx("span",{className:"studio-presence__kind",children:b.kindLabel}),b.isThisPage?o.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),o.jsx("div",{className:"studio-presence__route",title:b.route,children:b.route}),o.jsxs("div",{className:"studio-presence__meta",children:[b.visibilityLabel," · ",b.freshnessLabel]})]},b.clientId))}),o.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,y?o.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function Sg(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 ia(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 Eg({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return h.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let a=s+1;for(;a<e.length&&e[a].groupId===i.groupId;)a++;const c=e.slice(s,a),l=i.origin==="transaction"?"transaction":"batch";r.push(ia(l,i.groupId,c)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&Sg(e[a],i);)a++;const c=e.slice(s,a);if(c.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(ia("listener-run",`listener-run:${l}:${s}`,c))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const Cg={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function Ng({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>Rg(e,t,n),[e,t.start,t.end,n])}function Rg(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return Cg;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let c=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let y=Math.floor((p-t.start)/s);y>=n&&(y=n-1),i[y]++,c++,f.result==="deny"&&(a[y]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const y=a[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:y,allows:f-y,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:y/d}}),total:c,denies:l,maxCount:d,outOfWindow:u}}const Ag=new Set(["get","list"]),Ig=new Set(["create","update","set"]),Dg=new Set(["delete","remove"]),Pg=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],$g=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Gn(e){return e.origin==="admin"}function Og(e,t=Gn){return e.result==="allow"||t(e)?Ag.has(e.method)?"reads":Ig.has(e.method)?"writes":Dg.has(e.method)?"deletes":null:null}function Tg(e,t=Gn){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const Mg=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Ic(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return Mg(r);const a=i/n,c=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 y=s(f);if(y==null)continue;let b=Math.floor((p-t.start)/a);b>=n&&(b=n-1);const v=c.get(y);v[b]++,l.set(y,(l.get(y)??0)+1)}let u=0;for(const f of c.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*a,end:t.start+(f+1)*a};const m=r.map(f=>({key:f.key,label:f.label,values:c.get(f.key),total:l.get(f.key)??0}));return{points:d,series:m,maxValue:u}}function Ug(e,t,n=24,r=Gn){return Ic(e,t,n,Pg,s=>Og(s,r))}function Bg(e,t,n=24,r=Gn){return Ic(e,t,n,$g,s=>Tg(s,r))}function Lg({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Ug(e,t,n,r),[e,t.start,t.end,n,r])}function Fg({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Bg(e,t,n,r),[e,t.start,t.end,n,r])}function ns({children:e,kind:t,className:n,ariaLabel:r}){return o.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?o.jsx("span",{"aria-hidden":"true",children:e}):e})}function Lt(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Dc({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Lt,className:i}){return o.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:[o.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),o.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),o.jsx(ns,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var Os=Cu();function it(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var c,l,u;let d;n.key&&((c=n.debug)!=null&&c.call(n))&&(d=Date.now());const m=e();if(!(m.length!==r.length||m.some((y,b)=>r[b]!==y)))return s;r=m;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...m),n.key&&((u=n.debug)!=null&&u.call(n))){const y=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,v=b/16,g=(w,x)=>{for(w=String(w);w.length<x;)w=" "+w;return w};console.info(`%c⏱ ${g(b,5)} /${g(y,5)} ms`,`
110
110
  font-size: .6rem;
111
111
  font-weight: bold;
112
- color: hsl(${Math.max(0,Math.min(120-120*v,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return a.updateDeps=c=>{r=c},a}function ta(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Tg=(e,t)=>Math.abs(e-t)<1.01,Mg=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},na=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Ug=e=>e,Bg=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},Lg=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:c,height:l}=a;t({width:Math.round(c),height:Math.round(l)})};if(s(na(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const c=()=>{const l=a[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(na(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},ra={passive:!0},sa=typeof window>"u"?!0:"onscrollend"in window,Fg=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&sa?()=>{}:Mg(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:m,isRtl:f}=e.options;s=m?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},c=a(!0),l=a(!1);n.addEventListener("scroll",c,ra);const u=e.options.useScrollendEvent&&sa;return u&&n.addEventListener("scrollend",l,ra),()=>{n.removeEventListener("scroll",c),u&&n.removeEventListener("scrollend",l)}},Vg=(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"]},qg=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const a=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class Wg{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 a=()=>{const c=i.target,l=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(c,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));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:Ug,rangeExtractor:Bg,onChange:()=>{},measureElement:Vg,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=nt(()=>(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 a=r-1;a>=0;a--){const c=n[a];if(s.has(c.lane))continue;const l=i.get(c.lane);if(l==null||c.end>l.end?i.set(c.lane,c):c.end<l.end&&s.set(c.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,c)=>a.end===c.end?a.index-c.index:a.end-c.end)[0]:void 0},this.getMeasurementOptions=nt(()=>[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,a,c,l)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=nt(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l},u)=>{if(!a)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 m=this.measurementsCache.slice(0,d),f=new Array(c).fill(void 0);for(let p=0;p<d;p++){const y=m[p];y&&(f[y.lane]=p)}for(let p=d;p<n;p++){const y=i(p),b=this.laneAssignments.get(p);let v,g;const w=l==="estimate"||u.has(y);if(b!==void 0&&this.options.lanes>1){v=b;const k=f[v],N=k!==void 0?m[k]:void 0;g=N?N.end+this.options.gap:r+s}else{const k=this.options.lanes===1?m[p-1]:this.getFurthestMeasurement(m,p);g=k?k.end+this.options.gap:r+s,v=k?k.lane:p%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(p,v)}const x=u.get(y),_=typeof x=="number"?x:this.options.estimateSize(p),j=g+_;m[p]={index:p,start:g,size:_,end:j,key:y,lane:v},f[v]=p}return this.measurementsCache=m,m},{key:!1,debug:()=>this.options.debug}),this.calculateRange=nt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?zg({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=nt(()=>{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,a)=>i===null||a===null?[]:n({startIndex:i,endIndex:a,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)),a=Math.max(0,s-i),c=Math.min(this.options.count-1,s+i);return n>=a&&n<=c}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,c)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(c))});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 a=this.itemSizeCache.get(i.key)??i.size,c=r-a;c!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,c,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=c,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=nt(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const c=n[i],l=r[c];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return ta(r[Ec(0,r.length-1,s=>ta(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(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,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(),a=this.measurementsCache[n];if(!a)return;if(r==="auto")if(a.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(a.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const c=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,r,a.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),a=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:a,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[a,c]=i,l=this.now();this.scrollState={index:n,align:c,behavior:s,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{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 a=r.length-1;for(;a>=0&&i.some(c=>c===null);){const c=r[a];i[c.lane]===null&&(i[c.lane]=c.end),a--}s=Math.max(...i.filter(c=>c!==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,a=s!==this.scrollState.lastTargetOffset;if(!a&&Tg(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Ec=(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 zg({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 a=Ec(0,s,i,n),c=a;if(r===1)for(;c<s&&e[c].end<n+t;)c++;else if(r>1){const l=Array(r).fill(0);for(;c<s&&l.some(d=>d<n+t);){const d=e[c];l[d.lane]=d.end,c++}const u=Array(r).fill(n+t);for(;a>=0&&u.some(d=>d>=n);){const d=e[a];u[d.lane]=d.start,a--}a=Math.max(0,a-a%r),c=Math.min(s,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const ia=typeof document<"u"?h.useLayoutEffect:h.useEffect;function Kg({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var c;e&&a?Rs.flushSync(n):n(),(c=t.onChange)==null||c.call(t,i,a)}},[s]=h.useState(()=>new Wg(r));return s.setOptions(r),ia(()=>s._didMount(),[]),ia(()=>s._willUpdate()),s}function Hg(e){return Kg({observeElementRect:Lg,observeElementOffset:Fg,scrollToFn:qg,...e})}function As({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const c=h.useRef(null),l=typeof t=="function"?t:()=>t,u=Hg({count:e.length,getScrollElement:()=>c.current,estimateSize:l,overscan:r});return o.jsx("div",{ref:c,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:o.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const m=e[d.index],f=a?a(m,d.index):d.key;return o.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(m,d.index)},f)})})})}const Gg={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function Jg({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[c,l]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":c?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":c,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:Gg[e.kind]}),o.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?o.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),c?o.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>o.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:o.jsx(Sc,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function Yg(e){return e<0?0:e>1?1:e}function hr(e,t){const n=t.end-t.start;return n<=0?0:Yg((e-t.start)/n)}function Qg({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:c,header:l,axis:u,emptyState:d,className:m}){const f=h.useId(),[p,y]=h.useState(null),[b,v]=h.useState(null),g=jg({events:e??[],window:n,bucketCount:r}),w=t??g,{buckets:x,total:_}=w,j=p??b,k=j===null?null:x.find(S=>S.index===j)??null,N=k!==null&&s?.start===k.start&&s.end===k.end;if(x.length===0)return o.jsx("div",{className:m,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const A=_===0,R=c===void 0?n.end:c,I=R==null?null:hr(R,n),C=typeof u=="function"?u(n):u;return o.jsxs("div",{className:m,"data-pyric-ui":"traffic-timeline","data-pyric-empty":A?"":void 0,children:[l!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:l}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(S=>o.jsx(Xg,{bucket:S,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&k?.index===S.index?f:void 0,selected:s?.start===S.start&&s.end===S.end},S.index))}),k&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(k.index+.5)/Math.max(x.length,1)},children:a(k)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":hr(s.start,n),"--pyric-brush-right":1-hr(s.end,n)}}),I!=null&&o.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":I}})]}),C!=null&&o.jsx("div",{"data-pyric-timeline-axis":"",children:C})]})}function Xg({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const c=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return o.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":a?"":void 0,disabled:!c,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":c?a: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:c?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[o.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const Zg=e=>String(e);function ev({series:e,visible:t,onToggle:n,formatValue:r=Zg,className:s}){const i=t!==void 0&&n!==void 0;return o.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((a,c)=>{const l=t?t.has(a.key):!0,u=o.jsxs(o.Fragment,{children:[o.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-metric-label":"",children:a.label}),o.jsx("span",{"data-pyric-metric-value":"",children:r(a.total)})]});return i?o.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,"data-pyric-metric-hidden":l?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(a.key),"data-pyric-metric-checkbox":""}),u]},a.key):o.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,children:u},a.key)})})}const tv=e=>String(e),nv=e=>new Date(e).toLocaleTimeString();function rv({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=tv,formatTime:i=nv,emptyState:a,className:c}){const[l,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:a});const d=t.filter(g=>(!n||n.has(g.key))&&(!r||g.total>0));let m=0;for(const g of d)for(const w of g.values)w>m&&(m=w);const f=m===0?1:m,p=e.length,y=g=>p===1?50:g/(p-1)*100,b=g=>100-g/f*100,v=l!=null?e[l]:null;return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(g=>{const w=t.indexOf(g);if(!((!n||n.has(g.key))&&(!r||g.total>0)))return null;const _=g.values.map((j,k)=>`${k===0?"M":"L"}${y(k)},${b(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":g.key,"data-pyric-series-index":w,d:_,fill:"none",vectorEffect:"non-scaling-stroke"},g.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((g,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(g.start)} to ${i(g.end)}`},g.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(g=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":g.key,"data-pyric-series-index":t.indexOf(g),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:g.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(g.values[v.index])})]},g.key))]})]})})}const sv={listUsers:fe.listUsers,subscribeUsers:fe.subscribeUsers,createUser:fe.createUser,updateUser:fe.updateUser,deleteUser:fe.deleteUser,clearUsers:fe.clearUsers,getAuthProviderConfig:fe.getAuthProviderConfig,setAuthProviderConfig:fe.setAuthProviderConfig,subscribeAuthProviderConfig:fe.subscribeAuthProviderConfig},Cc=h.createContext(sv);function iv(){return h.useContext(Cc)}function Nc({value:e,children:t}){return h.createElement(Cc.Provider,{value:e},t)}function av(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Is(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=iv(),[c,l]=h.useState([]),[u,d]=h.useState(!0),[m,f]=h.useState(void 0),[p,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const k=I=>{j||(l(I),d(!1))},N=I=>{j||(l([]),f(I instanceof Error?I:new Error(String(I))),d(!1))},A=()=>{try{const I=t(e);I&&typeof I.then=="function"?I.then(k).catch(N):k(I)}catch(I){N(I)}};let R;try{A(),R=n(e,A)}catch(I){N(I)}return()=>{j=!0,R?.()}},[e,t,n]);const b=h.useMemo(()=>{const j=p.trim().toLowerCase();return j?c.filter(k=>av(k,j)):c},[c,p]),v=h.useCallback(j=>r(e,j),[e,r]),g=h.useCallback((j,k)=>s(e,j,k),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),_=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(k=>l(k)).catch(()=>{}):l(j)},[e,t]);return{users:b,totalCount:c.length,isLoading:u,error:m,filter:p,setFilter:y,createUser:v,updateUser:g,deleteUser:w,clearUsers:x,refresh:_}}const ov=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],cv=1e3;function Rc(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>cv)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 ov)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const lv={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},uv=new Set(["password","anonymous","phone"]),dv=/^[^@]+@[^@]+\.[^@]+$/,aa=6;function fv(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=>!uv.has(t))}:{...lv}}function hv(e){const t=fv(e);return{fields:t,initial:{...t}}}function pv(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function mv(e){const t={},n=e.email.trim(),r=e.password;n&&!dv.test(n)&&(t.email="Invalid email"),r&&r.length<aa&&(t.password=`Password should be at least ${aa} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Rc(e.claimsText);return s.ok||(t.claims=s.message),t}function yv(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Ac(t.providerIds,n.providerIds):t[r]!==n[r])}function Ac(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function Ic(e){const t=Rc(e.claimsText);return t.ok?t.claims:void 0}function bv(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=Ic(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function gv(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=Ic(t)??{}),Ac(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Dc(e={}){const[t,n]=h.useReducer(pv,e.initial,hv),r=h.useMemo(()=>mv(t.fields),[t.fields]),s=h.useMemo(()=>yv(t),[t]),i=h.useCallback((c,l)=>n({type:"setField",field:c,value:l}),[]),a=h.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:a,toCreateRequest:()=>bv(t),toUpdateRequest:()=>gv(t),dispatch:n}}const vv={"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 _n(e){return vv[e]??e}function oa(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function wv(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:_n("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:_n(t.providerId)},t.providerId))}function ca(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Pc({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:c,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:m=ca,formatLastLoginAt:f=ca,emptyState:p,noResultsState:y,className:b,virtualizeThreshold:v=100,rowHeight:g=44,virtualizedHeight:w="60vh"}){if(n)return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const j=!!r?.trim();return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":j?"":void 0,children:j?y??"No results":p??"No users for this project yet"})}const x=e.length>v,_=j=>o.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":j.uid,"data-pyric-user-disabled":j.disabled?"":void 0,children:[c?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:c(j)}):null,o.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?o.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(j),children:i?i(j):oa(j)}):(i??oa)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??wv)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:m(j.createdAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(j.lastLoginAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:j.uid}),u?o.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(j)}):null]},j.uid);return o.jsxs("div",{className:b,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":x?"":void 0,"data-pyric-selection":c?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[c?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,o.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),x?o.jsx(As,{items:e,estimateSize:g,height:w,getItemKey:j=>j.uid,renderItem:_}):o.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(_)})]})}function xv({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return o.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[o.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:a=>t(a.target.value)}),n!=null&&o.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&o.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function jv({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:hc.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:_n(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function $c({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:c}){const l=Dc({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),m=(y,b,v,g,w=null)=>({name:y,label:b,input:g,error:w,kind:v,defaultRender:()=>v==="checkbox"?o.jsxs("label",{"data-pyric-field-label":y,children:[g,o.jsx("span",{"data-pyric-label-text":!0,children:b})]},y):v==="group"?o.jsxs("fieldset",{"data-pyric-field-label":y,children:[o.jsx("legend",{"data-pyric-label-text":!0,children:b}),g]},y):o.jsxs("label",{"data-pyric-field-label":y,children:[o.jsx("span",{"data-pyric-label-text":!0,children:b}),g,w!=null&&o.jsx("p",{role:"alert","data-pyric-field-error":y,children:w})]},y)}),f=[m("email","Email","text",o.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:y=>l.setField("email",y.target.value)}),l.errors.email??null),m("password","Password","text",o.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:y=>l.setField("password",y.target.value)}),l.errors.password??null),m("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:y=>l.setField("displayName",y.target.value)})),m("phone-number","Phone number","text",o.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:y=>l.setField("phoneNumber",y.target.value)})),m("photo-url","Photo URL","text",o.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:y=>l.setField("photoUrl",y.target.value)})),...u==="create"?[m("providers","Sign-in providers","group",o.jsx(jv,{selected:l.fields.providerIds,onChange:y=>l.setField("providerIds",y)}))]:[],m("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:y=>l.setField("emailVerified",y.target.checked)})),m("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:y=>l.setField("disabled",y.target.checked)}))],p=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return o.jsxs("form",{className:a,"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(y=>c?o.jsx(h.Fragment,{children:c(y)},y.name):y.defaultRender()),o.jsx(xv,{value:l.fields.claimsText,onChange:y=>l.setField("claimsText",y),error:l.errors.claims}),i,o.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?o.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,o.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}function _v({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:c,className:l}){const u=h.useRef(null),d=h.useRef(null);return h.useEffect(()=>{if(!e)return;const m=f=>{f.key==="Escape"&&(f.stopPropagation(),t(!1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,t]),h.useEffect(()=>{if(e)return d.current=document.activeElement,u.current?.focus(),()=>{d.current?.focus?.()}},[e]),!e||typeof document>"u"?null:Rs.createPortal(o.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:m=>{m.target===m.currentTarget&&t(!1)},children:[o.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),o.jsxs("div",{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:[o.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?o.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,o.jsxs("div",{"data-pyric-confirm-actions":!0,children:[o.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:a}),o.jsx("button",{ref:u,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:c,children:i})]})]})]}),document.body)}const Oc=h.createContext(null);function wt(){const e=h.useContext(Oc);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function Ds({children:e,dialogClassName:t}){const[n,r]=h.useState(null),s=h.useRef(!1),i=h.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),a=h.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),c=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=h.useMemo(()=>i,[i]);return o.jsxs(Oc.Provider,{value:l,children:[e,n?o.jsx(_v,{open:!0,onOpenChange:c,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:a,className:t}):null]})}function kv(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Sv({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const c=wt(),l=async()=>{await c({title:n,body:r??`This will permanently delete ${kv(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:l})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function Ev(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 Cv={addDoc:ro,collection:Nt,deleteDoc:jr,doc:We,getDoc:xo,getDocs:mn,limit:bn,onSnapshot:af,query:yn,setDoc:ln,startAfter:sf},Tc=h.createContext(Cv);function Ps(){return h.useContext(Tc)}function Nv({value:e,children:t}){return h.createElement(Tc.Provider,{value:e},t)}function Rv(e){const{onSnapshot:t}=Ps(),[n,r]=h.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return h.useEffect(()=>{if(!e){r({data:void 0,error:void 0,isLoading:!1});return}return r(i=>({data:i.data,error:void 0,isLoading:!0})),t(e,i=>r({data:i,error:void 0,isLoading:!1}),i=>r({data:void 0,error:Ev(i),isLoading:!1}))},[t,e]),n}function Wn(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&Ze(e)!==null?"vector":Array.isArray(e)?"array":e instanceof pt?"timestamp":e instanceof lt?"geopoint":e instanceof In?"bytes":typeof e=="object"&&Mc(e)?"timestamp":typeof e=="object"&&Uc(e)?"geopoint":typeof e=="object"&&Av(e)?"reference":typeof e=="object"?"map":"null"}function Mc(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 Uc(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function Av(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 Ze(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Xt(t.value)||t.__type__==="__vector__"&&Xt(t.value))return Zt(t.value);if(Xt(t._values))return Zt(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Xt(n))return Zt(n)}catch{}return null}function Xt(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Zt(e){const t=e.slice();return{values:t,dimension:t.length}}const la=4;function Bc(e){const t=e.values.slice(0,la).join(", "),n=e.values.length>la?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function kn(e){const t=Ze(e);if(t)return Bc(t);if(Array.isArray(e))return e.map(kn);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]=kn(i);return r}}return e}function Lc(){return crypto.randomUUID()}function Iv(e){const t=Lc(),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))Qr(n,t,r,s);return n}function Qr(e,t,n,r){const s=Wn(r),i=Lc(),a={id:i,parentId:t,key:n,type:s,value:Dv(s)?void 0:r};if(e.nodes[i]=a,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[c,l]of Object.entries(r))Qr(e,i,c,l);else if(s==="array"&&Array.isArray(r))for(const c of r)Qr(e,i,null,c);return i}function Dv(e){return e==="map"||e==="array"}function Fc(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return Xr(e,e.rootId)}function Xr(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]=Xr(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(Xr(e,s));return r}default:return n.value}}function Zr(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 Vc(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 qc(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 pt?void 0:"Expected a Timestamp";case"geopoint":return t instanceof lt?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 In?void 0:"Expected a Bytes value";case"vector":return Ze(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Wc(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=qc(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]??[],a=new Map;for(const c of i){const l=t[c];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[c].error=t[c].error??"Field name is required");const d=a.get(u)??[];d.push(c),a.set(u,d)}for(const[c,l]of a)if(c&&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 $s(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return pt.now();case"geopoint":return new lt(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return In.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function es(e){if(e===null||typeof e!="object"||Ze(e)!==null)return e;if(Mc(e)){const n=e;return new pt(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Uc(e)){const n=e;return new lt(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(es);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=es(s);return n}return e}function zc(e){const t=Iv(es(e)),{tree:n,errorCount:r}=Wc(t);return{tree:n,initial:n,errorCount:r}}function Pv(e,t){switch(t.type){case"setValue":return rt(e,n=>Ov(n,t.nodeId,t.value));case"setType":return rt(e,n=>Tv(n,t.nodeId,t.newType));case"setKey":return rt(e,n=>Mv(n,t.nodeId,t.key));case"addMapEntry":return rt(e,n=>Uv(n,t.parentId,t.key,t.childType));case"addArrayEntry":return rt(e,n=>Bv(n,t.parentId,t.childType));case"remove":return rt(e,n=>Lv(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:$v(e.initial)};case"replaceData":return zc(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Zr(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Zr(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function rt(e,t){const n=t(Zr(e.tree)),{tree:r,errorCount:s}=Wc(n);return{...e,tree:r,errorCount:s}}function $v(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function Ov(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function Tv(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 a of i)for(const c of Vc(e,a))delete e.nodes[c],delete e.childIds[c];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:$s(n);return e.nodes[t]={...r,type:n,value:s},e}function Mv(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 Uv(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),a=r==="map"||r==="array"?void 0:$s(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:a},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function Bv(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:$s(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 Lv(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Vc(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 Kc(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=zc(t));const[r,s]=h.useReducer(Pv,n.current),i=h.useCallback((w,x)=>s({type:"setValue",nodeId:w,value:x}),[]),a=h.useCallback((w,x)=>s({type:"setType",nodeId:w,newType:x}),[]),c=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),l=h.useCallback((w,x,_)=>s({type:"addMapEntry",parentId:w,key:x,childType:_}),[]),u=h.useCallback((w,x)=>s({type:"addArrayEntry",parentId:w,childType:x}),[]),d=h.useCallback(w=>s({type:"remove",nodeId:w}),[]),m=h.useCallback(()=>s({type:"reset"}),[]),f=h.useCallback(w=>s({type:"replaceData",data:w}),[]),p=h.useCallback(w=>s({type:"touch",nodeId:w}),[]),y=h.useCallback(()=>s({type:"touchAll"}),[]),b=h.useCallback(()=>Fc(r.tree),[r.tree]),v=r.tree!==r.initial,g=r.errorCount===0;return h.useMemo(()=>({...r,isDirty:v,isValid:g,dispatch:s,setValue:i,setType:a,setKey:c,addMapEntry:l,addArrayEntry:u,remove:d,reset:m,replaceData:f,touch:p,touchAll:y,toData:b}),[r,v,g,i,a,c,l,u,d,m,f,p,y,b])}function Fv({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,c]=h.useState(!0),[l,u]=h.useState(void 0),[d,m]=h.useState(!1),[f,p]=h.useState(0),[y,b]=h.useState(n),v=h.useRef(0),[g,w]=h.useState(0),{addDoc:x,deleteDoc:_,doc:j,getDoc:k,getDocs:N,limit:A,onSnapshot:R,query:I,setDoc:C,startAfter:S}=Ps();h.useEffect(()=>{b(n)},[e,r,n,t]),h.useEffect(()=>{let P=!1;r==="paged"&&i([]),m(!1),c(!0),u(void 0);const O=t??e,T=r==="live"?y:n,$=I(O,A(T)),Y=ne=>{P||(i([...ne.docs]),m(ne.docs.length===T),c(!1))},ie=ne=>{P||(u(ne instanceof Error?ne:new Error(String(ne))),c(!1))};if(r==="live"){const ne=++v.current,Ul=R($,Bl=>{w(ne),Y(Bl)},ie);return()=>{P=!0,Ul()}}return N($).then(ne=>{Y(ne)}).catch(ie),()=>{P=!0}},[e,N,A,r,R,n,t,I,y,f]);const E=h.useCallback(()=>{if(!d||a)return;if(r==="live"){c(!0),b($=>$+n);return}const P=s[s.length-1];if(!P)return;c(!0);const T=I(t??e,S(P),A(n));N(T).then($=>{i(Y=>[...Y,...$.docs]),m($.docs.length===n),c(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),c(!1)})},[e,s,N,d,a,A,r,n,t,I,S]),D=h.useCallback(async(P,O,T)=>{if(P==null){const Y=await x(e,O);return r==="paged"&&p(ie=>ie+1),Y}const $=j(e,P);if(T?.onExisting==="fail"){const Y=await k($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const ne=new Error(`Document "${P}" already exists.`);throw ne.code="already-exists",ne}}return await C($,O),r==="paged"&&p(Y=>Y+1),$},[x,e,j,k,r,C]),V=h.useCallback(async P=>{await _(P),r==="paged"&&p(O=>O+1)},[_,r]),G=h.useCallback(()=>p(P=>P+1),[]);return{documents:s,isLoading:a,error:l,subscriptionGeneration:g,hasMore:d,loadMore:E,createDocument:D,deleteDocument:V,refresh:G}}function Vv({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=h.useState([]),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),l(void 0);return}let m=!1;return a(!0),l(void 0),u.current(e,t).then(f=>{m||(s(f),a(!1))}).catch(f=>{m||(l(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{m=!0}},[e,d]),{subcollections:r,isLoading:i,error:c}}function ua(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function da(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Sn(e,t){if(Object.is(e,t))return!0;if(ua(e))return e.isEqual(t);if(ua(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)=>Sn(s,t[i]));if(!da(e)||!da(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&Sn(e[s],t[s]))}function qv({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function Wv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const zv={type:"string",Display:qv,Edit:Wv};function Kv({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function Hv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,a=i===""?Number.NaN:parseFloat(i);t(a)},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Gv={type:"number",Display:Kv,Edit:Hv};function Jv({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function Yv({value:e,onChange:t,path:n}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:o.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]})})}const Qv={type:"boolean",Display:Jv,Edit:Yv};function Xv({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function Zv({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const ew={type:"null",Display:Xv,Edit:Zv};function Hc(e){if(e instanceof pt)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 tw({value:e,path:t}){const n=Hc(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return o.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function nw({value:e,onChange:t,error:n,path:r}){const s=Hc(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),a=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,16);return o.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"datetime-local",value:a,onChange:c=>{const l=c.target.value;if(!l)return;const u=new Date(l);t(pt.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const rw={type:"timestamp",Display:tw,Edit:nw};function sw({value:e,path:t}){return o.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 iw({value:e,onChange:t,error:n,path:r}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new lt(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new lt(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const aw={type:"geopoint",Display:sw,Edit:iw},Gc=h.createContext({});Gc.Provider;function ow(){return h.useContext(Gc)}function cw({value:e,path:t}){const{onReferenceClick:n}=ow();return n?o.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}):o.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function lw({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,a=i.split("/").filter(Boolean),c=a[a.length-1]??"",l=e.firestore??{};t({path:i,id:c,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const uw={type:"reference",Display:cw,Edit:lw};function dw({value:e,path:t}){const n=e.toBase64();return o.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(e.toUint8Array().byteLength),children:n})}function fw({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("textarea",{value:e.toBase64(),onChange:s=>{try{t(In.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const hw={type:"bytes",Display:dw,Edit:fw};function ts({value:e,path:t,fieldEditors:n}){const r=Wn(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function Jc({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Wn(t),a=i==="map"||i==="array",[c,l]=h.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 a?o.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[o.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":c,onClick:()=>l(m=>!m),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),c?o.jsx(ts,{value:t,path:n,fieldEditors:r}):null]}):o.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),o.jsx("span",{...u,children:e}),o.jsx(ts,{value:t,path:n,fieldEditors:r})]})}function pw({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return o.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>o.jsx(Jc,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const mw={type:"map",Display:pw};function yw({value:e,path:t,fieldEditors:n}){return o.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>o.jsx(Jc,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const bw={type:"array",Display:yw},fa=4;function gw(e){return e.length<=fa?`[${e.join(", ")}]`:`[${e.slice(0,fa).join(", ")}, …]`}function vw({value:e,path:t}){const n=Ze(e);return n?o.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),o.jsx("span",{"data-pyric-vector-preview":!0,children:gw(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function ww(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 xw({value:e,onChange:t,error:n,path:r}){const s=Ze(e),i=s?JSON.stringify(s.values):"[]",[a,c]=h.useState(i),[l,u]=h.useState(void 0),d=p=>{c(p);const y=ww(p);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},m=s?s.dimension:0,f=l??n;return o.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(m),"data-pyric-error":f?"":void 0,children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${m}`}),o.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),o.jsx("textarea",{"data-pyric-vector-raw":!0,value:a,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?o.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const jw={type:"vector",Display:vw,Edit:xw},ha={string:zv,number:Gv,boolean:Qv,null:ew,timestamp:rw,geopoint:aw,reference:uw,bytes:hw,map:mw,array:bw,vector:jw};function Yc(e){return e?{...ha,...e}:ha}function zn(e={}){const t=h.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=h.useState("wide");return h.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=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 c.observe(a),()=>c.disconnect()},[n,r]),{ref:t,size:s}}const Qc=h.createContext(null);function Ue(){const e=h.useContext(Qc);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function _w({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Kc({initial:e}),a=Yc(t),c=h.useRef(n);c.current=n,h.useEffect(()=>{c.current?.(i)},[i]);const{ref:l,size:u}=zn();return o.jsx(Qc.Provider,{value:{editor:i,fieldEditors:a},children:o.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 kw(){const{editor:e}=Ue(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(Os,{nodeId:n,path:Sw(e,n)},n)),o.jsx(Xc,{parentId:e.tree.rootId})]})}function Sw(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 Os({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Ue(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx(Nw,{node:s,path:t});if(s.type==="array")return o.jsx(Rw,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const c=s.touched?s.error:void 0;return o.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":c?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(Ts,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:c,onChange:l=>n.setValue(s.id,l)})]})}function Ts({node:e,path:t}){const{editor:n}=Ue(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:o.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?o.jsx("input",{type:"text",value:e.key??"",onChange:a=>n.setKey(e.id,a.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,o.jsx(Cw,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const Ew=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function Cw({node:e}){const{editor:t}=Ue(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=Ew.filter(s=>!(n?.type==="array"&&s==="array"));return o.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=>o.jsx("option",{value:s,children:s},s))})}function Nw({node:e,path:t}){const{editor:n}=Ue(),r=n.tree.childIds[e.id]??[];return o.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?o.jsx(Ts,{node:e,path:t}):null,o.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const a=t?`${t}.${i.key??""}`:i.key??"";return o.jsx(Os,{nodeId:s,path:a},s)})}),o.jsx(Xc,{parentId:e.id})]})}function Rw({node:e,path:t}){const{editor:n}=Ue(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[o.jsx(Ts,{node:e,path:t}),o.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const a=t?`${t}[${i}]`:`[${i}]`;return o.jsx("li",{"data-field-index":String(i),children:o.jsx(Os,{nodeId:s,path:a})},s)})}),o.jsx(Aw,{parentId:e.id})]})}function Xc({parentId:e}){const{editor:t}=Ue();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function Aw({parentId:e}){const{editor:t}=Ue();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const pa={Root:_w,Fields:kw};function Iw({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):o.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(a=>o.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":a.id,children:o.jsx("button",{type:"button",onClick:()=>r?.(a),"data-pyric-collection-select":!0,children:a.id})},a.path))})}const St=new Map;function Ms({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),c=h.useRef(new Map),[l,u]=h.useState(St);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(St)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(St);return}const m=new Map;for(const[f,p]of t){const y=d.entries.has(f),b=d.entries.get(f);if(y&&n(b,p))continue;const v=a.current.get(f)===0?1:0;a.current.set(f,v),m.set(f,{kind:y?"modified":"added",cycle:v})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let y=m.size>0;for(const b of f.keys())t.has(b)||(p.delete(b),y=!0);for(const[b,v]of m)p.set(b,v);return y?p.size===0?St:p:f});for(const[f,p]of m){const y=c.current.get(f);y&&clearTimeout(y);const b=setTimeout(()=>{c.current.delete(f),u(v=>{if(v.get(f)?.cycle!==p.cycle)return v;const g=new Map(v);return g.delete(f),g.size===0?St:g})},r);c.current.set(f,b)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of c.current.values())clearTimeout(d);c.current.clear()},[]),l}function Et(e){return e.ref}function Dw({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:c,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:m=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const y=h.useMemo(()=>new Map(e.map(g=>[Et(g).path,g.data()])),[e]),b=Ms({scope:d,entries:y,equals:Sn,ready:!t});if(n)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const v=e.length>m;return o.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":v?"":void 0,children:[v?o.jsx(As,{items:e,estimateSize:f,height:p,getItemKey:g=>Et(g).path,renderItem:g=>{const w=b.get(Et(g).path);return o.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":g.id,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(Et(g)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(g):g.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(g)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(g=>{const w=Et(g),x=b.get(w.path);return o.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":g.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(w),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:a?a(g):g.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(g)}):null]},w.path)})}),r&&i?o.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const Pw=/^__.*__$/;function Zc(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(Pw.test(e))return"Cannot match __.*__ (reserved)";if(Ow(e)>1500)return"Cannot exceed 1500 bytes"}function $w(e){return Zc(e)}function Ow(e){return new TextEncoder().encode(e).length}function Tw(e){return Zc(e)}const ma="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Mw(){let e="";for(let t=0;t<20;t++)e+=ma.charAt(Math.floor(Math.random()*ma.length));return e}const Uw={ref:Ot,listAll:Cs,getMetadata:Up,getBlob:lb,uploadBytes:Go,uploadBytesResumable:hb,deleteObject:Es},el=h.createContext(Uw);function Kn(){return h.useContext(el)}function Bw({value:e,children:t}){return h.createElement(el.Provider,{value:e},t)}function pr(e){return e.replace(/^\/+|\/+$/g,"")}function ns(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function mr(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(ns)}function Lw(e,t){const{listAll:n,ref:r}=Kn(),s=pr(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[c,l]=h.useState(0),u=h.useRef(new Map);h.useEffect(()=>{if(u.current.clear(),e==null){a({status:"idle",items:[],prefixes:[],error:void 0});return}let y=!1;return a({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(b=>{y||a({status:"success",items:[...b.items].sort(ns),prefixes:[...b.prefixes].sort(ns),error:void 0})}).catch(b=>{y||a({status:"error",items:[],prefixes:[],error:b instanceof Error?b:new Error(String(b))})}),()=>{y=!0}},[e,s,c]);const d=h.useCallback(()=>l(y=>y+1),[]),m=h.useCallback(y=>{if(e==null)return;const b=y.endsWith("/"),v=pr(y),g=s===""?"":`${s}/`;if(!v.startsWith(g)||v===s)return;const w=v.slice(g.length),x=w.indexOf("/");a(_=>{if(_.status==="idle")return _;if(x===-1)return b?(u.current.set(v,_.prefixes.some(k=>k.fullPath===v)?null:v),{..._,prefixes:mr(_.prefixes,r(e,v))}):(u.current.set(v,_.items.some(k=>k.fullPath===v)?null:v),{..._,items:mr(_.items,r(e,v))});const j=`${g}${w.slice(0,x)}`;return u.current.set(v,_.prefixes.some(k=>k.fullPath===j)?null:j),{..._,prefixes:mr(_.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const b=pr(y),v=u.current.get(b);if(u.current.delete(b),v===null)return;const g=v??b;a(w=>({...w,items:w.items.filter(x=>x.fullPath!==g),prefixes:w.prefixes.filter(x=>x.fullPath!==g)}))},[]),p=h.useMemo(()=>[...i.prefixes.map(y=>({kind:"folder",name:y.name,fullPath:y.fullPath,ref:y})),...i.items.map(y=>({kind:"object",name:y.name,fullPath:y.fullPath,ref:y}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:m,removeItem:f}}function Q(e){return e.split("/").filter(Boolean).join("/")}function Fw(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>Q(r)),c=s?Q(t):i,l=h.useCallback(p=>{const y=Q(p);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>c===""?[]:c.split("/"),[c]),d=h.useCallback(p=>{const y=Q(p);l(y.includes("/")||c===""?y:`${c}/${y}`)},[c,l]),m=h.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=h.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:c,segments:u,setPath:l,enter:d,up:m,navigateToIndex:f}}const ya={status:"idle",blob:void 0,url:void 0,error:void 0};function Vw(e,t){const{getBlob:n,getMetadata:r,ref:s}=Kn(),i=t==null?null:Q(t),a=e!=null&&i!=null&&i!=="",[c,l]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(ya),[m,f]=h.useState(0),p=h.useRef(0);h.useEffect(()=>{if(p.current++,d(ya),!a){l({status:"idle",metadata:void 0,error:void 0});return}let g=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{g||l({status:"success",metadata:w,error:void 0})}).catch(w=>{g||l({status:"error",metadata:void 0,error:w instanceof Error?w:new Error(String(w))})}),()=>{g=!0}},[e,i,m]);const y=u.url;h.useEffect(()=>{if(y!==void 0)return()=>{URL.revokeObjectURL(y)}},[y]);const b=h.useCallback(()=>f(g=>g+1),[]),v=h.useCallback(()=>{if(e==null||i==null||i==="")return;const g=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(w=>{g===p.current&&d({status:"success",blob:w,url:URL.createObjectURL(w),error:void 0})}).catch(w=>{g===p.current&&d({status:"error",blob:void 0,url:void 0,error:w instanceof Error?w:new Error(String(w))})})},[e,i]);return{status:c.status,metadata:c.metadata,error:c.error,refresh:b,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function qw(){const[e,t]=h.useState(()=>new Map),n=h.useCallback(u=>e.has(u),[e]),r=h.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const m=new Map(d);return m.set(u.fullPath,u),m})},[]),s=h.useCallback(u=>{t(d=>{if(!d.has(u))return d;const m=new Map(d);return m.delete(u),m})},[]),i=h.useCallback(u=>{t(d=>{const m=new Map(d);return m.has(u.fullPath)?m.delete(u.fullPath):m.set(u.fullPath,u),m})},[]),a=h.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),c=h.useCallback(()=>t(new Map),[]);return{selected:h.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:a,clear:c}}function Ww(e,t){const n=Ot(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function zw(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function Kw(e){return{async*start(t){const n=e??{listAll:Cs,deleteObject:Es};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const c=await n.listAll(a);s.push(...c.prefixes);for(const l of c.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(zw(a))}catch{}yield{deletedCount:r,done:!0}}}}function Hw(e,t={}){const n=Kn(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(0),d=h.useRef(t);return d.current=t,{deleteEntries:h.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const b=d.current.impl??Kw(n);let v=0;try{for(const g of f){d.current.list?.removeItem(g.fullPath);try{if(g.kind==="object")await n.deleteObject(n.ref(e,g.fullPath)),v++;else for await(const w of b.start(n.ref(e,g.fullPath))){if(p!==u.current)return y;if(s(v+w.deletedCount),w.done){v+=w.deletedCount;break}}y.deleted.push(g.fullPath),p===u.current&&s(v)}catch(w){const x=w instanceof Error?w:new Error(String(w));y.failed.push({fullPath:g.fullPath,error:x}),d.current.list?.insertItem(g.kind==="folder"?`${g.fullPath}/`:g.fullPath),p===u.current&&y.failed.length===1&&l(x)}}return y}finally{p===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:c}}const Gw=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),Jw=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 Yw(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[Tn],[c,l]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?Vr(r):r;l({status:"ready",rules:w,source:"option",error:void 0})}catch(w){l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let g=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{g||l({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{g||l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}),()=>{g=!0}},[a,r]);const u=s!==void 0?s:a?.context.auth??null,{rules:d,status:m}=c,f=i?.size,p=i?.contentType,y=h.useCallback(g=>{if(d==null)return m==="ready"?Jw:Gw;const w=Q(g),x=a?.bucket??"pyric-default",_=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=I=>zo(d,{request:{auth:u,method:I,path:_,...I==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),k=j("read"),N=j("create"),A=j("delete"),R=N;return{read:k.allowed,write:R.allowed,delete:A.allowed,upload:N.allowed,reasons:{read:k.allowed?[]:k.reasons,write:R.allowed?[]:R.reasons}}},[d,m,a?.bucket,u,f,p]),b=typeof n=="string"?n:(n??[]).join(`
113
- `),v=h.useMemo(()=>{const g=typeof n=="string"?[n]:n??[],w={};for(const x of g)w[Q(x)]=y(x);return w},[b,y]);return{status:m,source:c.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:c.error}}function ba(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Qw(e){return e instanceof Blob?e.size:e.byteLength}function Xw(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function Zw(e,t={}){const{ref:n,uploadBytes:r}=Kn(),s=Q(t.path??""),[i,a]=h.useState([]),c=h.useRef(t);c.current=t;const l=h.useCallback(f=>{a(p=>p.map(y=>y.id===f.id?f:y))},[]),u=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const y=(Array.isArray(f)?f:[f]).map(b=>{const v=Xw(b);return{task:{id:crypto.randomUUID(),fullPath:ba(s,Q(v.path)),status:"running",bytesTransferred:0,totalBytes:Qw(v.data)},entry:v}});a(b=>[...b,...y.map(v=>v.task)]);for(const{task:b}of y)c.current.list?.insertItem(b.fullPath),c.current.onProgress?.(b);return Promise.all(y.map(async({task:b,entry:v})=>{try{const g=await r(n(e,b.fullPath),v.data,v.metadata),w={...b,status:"success",bytesTransferred:b.totalBytes,metadata:g.metadata};return l(w),c.current.onProgress?.(w),c.current.onComplete?.(w),w}catch(g){const w={...b,status:"error",error:g instanceof Error?g:new Error(String(g))};return c.current.list?.removeItem(b.fullPath),l(w),c.current.onError?.(w),w}}))},[e,s,l,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=ba(s,Q(f));if(p==="")throw new Error("createFolder: folder name is empty");c.current.list?.insertItem(`${p}/`);try{await r(Ww(e,p),new Blob([]),{contentType:"text/plain"})}catch(y){throw c.current.list?.removeItem(p),y}},[e,s,r]),m=h.useCallback(()=>{a(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:m}}function ex({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=Q(e),a=i===""?[]:i.split("/");return o.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:o.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[o.jsx("li",{"data-pyric-breadcrumb-item":!0,children:o.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":a.length===0?"":void 0,"aria-current":a.length===0?"page":void 0,children:n})}),a.map((c,l)=>{const u=l===a.length-1,d=a.slice(0,l+1).join("/");return o.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),o.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:c})]},d)})]})})}function tx({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:c,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:m=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:y,size:b}=zn();if(n)return o.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 o.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 o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const v=x=>{if(!a)return{denied:!1};const _=a.verdictFor(x.fullPath);return _.read?{denied:!1}:{denied:!0,reason:_.reasons.read.join("; ")}},g=x=>{const _=x.kind==="object"&&x.fullPath===i;return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>x.kind==="folder"?r?.(x.fullPath):s?.(x.ref),"data-pyric-entry-select":!0,"data-pyric-selected":_?"":void 0,"aria-selected":_||void 0,children:c?c(x):x.name}),l?o.jsx("span",{"data-pyric-storage-action":!0,children:l(x)}):null]})},w=e.length>m;return o.jsx("div",{ref:y,className:d,"data-pyric-ui":"object-browser","data-size":b,"data-pyric-virtualized":w?"":void 0,children:w?o.jsx(As,{items:e,estimateSize:f,height:p,getItemKey:x=>`${x.kind}:${x.fullPath}`,renderItem:x=>{const _=v(x);return o.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:g(x)})}}):o.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(x=>{const _=v(x);return o.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:g(x)},`${x.kind}:${x.fullPath}`)})})})}async function tl(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,a)=>e.file(i,a));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((a,c)=>s.readEntries(a,c));if(i.length===0)break;for(const a of i)await tl(a,r,n)}}}async function nx(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 tl(i,"",t);else{const a=r.getAsFile?.();a&&t.push({file:a,relativePath:a.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function rx({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),c=h.useRef(0),l=h.useCallback(f=>{f.preventDefault(),!n&&(c.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(c.current=Math.max(0,c.current-1),c.current===0&&a(!1))},[n]),m=h.useCallback(f=>{if(f.preventDefault(),c.current=0,a(!1),n)return;const p=f.dataTransfer;p&&nx(p).then(y=>{y.length>0&&e(y)})},[n,e]);return o.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:m,children:t})}function sx(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 ix(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 ga(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=sx(e),{base:s,counter:i}=ix(n);let a=i===null?1:i+1;for(;;){const c=`${s} (${a})${r}`;if(!t.has(c))return c;a+=1}}function ax(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=ga(s,n);return n.add(l),l}const a=s.slice(0,i);let c=r.get(a);return c===void 0&&(c=ga(a,n),n.add(c),r.set(a,c)),`${c}${s.slice(i)}`})}function va(e){const t=Q(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const nl=[];function ox(e,t){switch(t.type){case"create":{const n=va(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(va(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=Q(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:nl}}function cx(e,t){const n=Q(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 wa(e,t){return e.includes(Q(t))}function lx(e){const t=Q(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const ux=256*1024;function rs(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const dx={id:"image",match:e=>rs(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?o.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function fx({blob:e,isJson:t}){const[n,r]=h.useState(void 0);return h.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:o.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const hx={id:"text",match:e=>{const t=rs(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:ux,render:({metadata:e,blob:t})=>t?o.jsx(fx,{blob:t,isJson:rs(e)==="application/json"}):null},px=[dx,hx];function mx(e,t){for(const n of[...t??[],...px])if(n.match(e))return n}const yx=[{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 bx({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[yx.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":t,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[o.jsx("dt",{children:t}),o.jsx("dd",{children:n})]},`custom:${t}`))]})}function gx({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:c}=zn(),l=Vw(e,t),{metadata:u,blobStatus:d,loadBlob:m}=l,f=u?mx(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,y=f?.needsBlob===!0&&!p;if(h.useEffect(()=>{y&&d==="idle"&&m()},[y,d,m]),l.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let b,v={};return f===void 0?v={"data-pyric-preview-none":""}:p?v={"data-pyric-preview-too-large":""}:y&&d==="loading"?v={"data-pyric-preview-loading":""}:y&&d==="error"?(v={"data-pyric-preview-error":""},b=l.blobError?.message):(!y||d==="success")&&(b=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":c,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(bx,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:b}),s]})}const rl=h.createContext(null);function vx(){const e=h.useContext(rl);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function wx({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=h.useState([]),a=h.useCallback(u=>{i(d=>d.filter(m=>m.id!==u))},[]),c=h.useCallback(u=>{const d=crypto.randomUUID(),m=u.duration??t;return i(f=>[...f,{id:d,...u}]),m>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},m),d},[t]),l=h.useMemo(()=>({toast:c,dismiss:a,toasts:s}),[c,a,s]);return o.jsxs(rl.Provider,{value:l,children:[e,o.jsx(xx,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function xx({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:Rs.createPortal(o.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(a=>o.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":a.kind??"info",role:a.kind==="error"?"alert":"status",children:[o.jsx("div",{"data-pyric-toast-title":!0,children:a.title}),a.body?o.jsx("div",{"data-pyric-toast-body":!0,children:a.body}):null,o.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(a.id),children:"×"})]},a.id))}),document.body)}function jx({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:c="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:m}){const f=wt(),{toast:p}=vx(),{deleteEntries:y,isRunning:b,progress:v}=Hw(e,{impl:n,list:r}),g=s?t.map(j=>({entry:j,verdict:s.verdictFor(j.fullPath)})).filter(j=>!j.verdict.delete):[],w=g.length===0?void 0:`Delete denied for ${g[0].entry.fullPath}${g.length>1?` (+${g.length-1} more)`:""}: ${g[0].verdict.reasons.write.join("; ")}`,x=b||t.length===0||e==null||g.length>0,_=async()=>{if(x||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:a??o.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>o.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:c}))return;const k=await y(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:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:k.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(k))};return d?o.jsx(o.Fragment,{children:d({onClick:_,isRunning:b,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:_,className:m,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":b?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:b?`Deleting… (${v})`:c})}function En(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 sl(e){const t=e.indexOf("?");return _s(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function _x(e){const{tab:t,rest:n,query:r}=sl(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:En(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 kx(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 il(e){const{tab:t,query:n}=sl(e),r=_x(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let xa=null,ss=il("");function Sx(){const e=cc();return e!==xa&&(xa=e,ss=il(e)),ss}function Ex(){return ss}function en(e){le(kx(e))}function Cx(e){le({tab:"traffic",query:{inspect:e}})}function Hn(){const e=h.useSyncExternalStore(qt,Sx,Ex),t=h.useCallback(s=>en(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":en({view:"auth",uid:s.uid});break;case"storage":en({view:"storage",kind:"object",path:s.objectPath});break;case"document":en({view:"firestore",path:En(s.path)});break}},[]),r=h.useCallback(s=>Cx(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const Nx={narrowBreakpoint:640,mediumBreakpoint:920};function Rx(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function Ax(e,t){const n=Rx(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 yr({label:e,error:t,hint:n,children:r}){return o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:e}),r,t?o.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?o.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function al({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,c]=h.useState(()=>Mw()),[l,u]=h.useState(null),[d,m]=h.useState(null),[f,p]=h.useState(!1),y=h.useRef(null),b=e==="collection"&&s?$w(s):void 0,v=a?Tw(a):void 0,w=!(e==="collection"&&(!s||b))&&!!a&&!v&&!f;h.useEffect(()=>{const j=k=>{k.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!l)){if(!l.isValid){l.touchAll();return}p(!0),m(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:Fc(l.tree)}),r()}catch(j){m(j instanceof Error?j:new Error(String(j))),p(!1)}}},_=e==="collection"?"Start a collection":"Add a document";return o.jsx("div",{className:"fs-modal-backdrop",onMouseDown:j=>{j.target===j.currentTarget&&!f&&r()},children:o.jsxs("div",{ref:y,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":_,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[o.jsx("h2",{className:"fs-modal__title",children:_}),o.jsx(yr,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(yr,{label:"Collection ID",error:b,children:o.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:j=>i(j.target.value),"data-pyric-field":"collection-id","aria-invalid":b?"true":void 0})}):null,o.jsx(yr,{label:"Document ID",error:a?v:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:o.jsx("input",{autoFocus:e==="document",type:"text",value:a,onChange:j=>c(j.target.value),"data-pyric-field":"doc-id","aria-invalid":v||!a?"true":void 0})}),o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:"Fields"}),o.jsx("div",{className:"fs-modal__fields",children:o.jsx(pa.Root,{initial:{},onChange:u,children:o.jsx(pa.Fields,{})})})]}),d?o.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,o.jsxs("div",{className:"fs-modal__actions",children:[o.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),o.jsx("button",{type:"button",className:"fs-editor__save",disabled:!w,onClick:()=>void x(),children:f?"Saving…":"Save"})]})]})})}function ol({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),c=()=>{if(!n){const l=a.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return h.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),o.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[o.jsx("button",{ref:a,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:c,children:o.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),o.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>o.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 cl(e){return JSON.stringify(e)}function Ix(e,t){const n=new Map,r=(s,i)=>{const a=t(s),c=cl(i);if(a==="map"){const l=s,u=Object.keys(l).sort();n.set(c,[a,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(a==="array"){const l=s;n.set(c,[a,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(c,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function ll(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 cl(n)}function Dx(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 Px(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 ja(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 $x=42;function Ox(e,t,n,r=$x){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(l=>ja(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${ja(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function Tx(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function Mx(e){return e.shiftKey===!0}const ul=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],Ux=[...ul,"map","array"];function Bx({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:c,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const m=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>m,[]),p=Kc({initial:f}),y=p.replaceData,b=h.useMemo(()=>Yc(i),[i]),v=wt(),[g,w]=h.useState(()=>new Set),[x,_]=h.useState(null),j=h.useRef(e),k=h.useRef(new Set),N=h.useRef(!1),[A,R]=h.useState(null),I=h.useMemo(()=>Ix(m,Wn),[m]),C=Ms({scope:t.path,entries:I,equals:Sn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,R(null),n(p.toData()).catch($=>{R($ instanceof Error?$:new Error(String($)))}))},[p.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,k.current.clear(),y(e.data()??{}))},[x,y,e]);const S=h.useCallback($=>{w(Y=>{const ie=new Set(Y);return ie.has($)?ie.delete($):ie.add($),ie})},[]),[E,D]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?p.addMapEntry($,"","string"):p.addArrayEntry($,"string"),$!==p.tree.rootId){const ie=ll(p.tree,$);w(ne=>new Set(ne).add(ie))}D($)},[p]);h.useEffect(()=>{if(!E)return;const $=p.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(k.current.add(Y),_(Y),D(null))},[p.tree,E]);const G=h.useCallback($=>{p.remove($),k.current.delete($),N.current=!0,x===$&&_(null)},[p,x]),P=h.useCallback(async($,Y,ie)=>{if(Mx(ie)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,T=p.tree.childIds[p.tree.rootId]??[];return o.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[o.jsxs("div",{className:"fs-doctree__head",children:[o.jsx("span",{className:"fs-doctree__docid",children:O}),o.jsx(ol,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await v({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}]})]}),A?o.jsx("p",{className:"fs-doctree__err",children:A.message}):null,o.jsxs("ul",{className:"fs-doctree__rows",children:[c?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:c,children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>V(p.tree.rootId,"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),T.map($=>o.jsx(dl,{nodeId:$,depth:0,editor:p,registry:b,expanded:g,onToggle:S,editingId:x,setEditingId:_,newIdsRef:k,onAdd:V,onDelete:P,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),l&&u?o.jsx(fl,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function dl({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:m,onReferenceClick:f,updates:p}){const{tree:y}=n,b=y.nodes[e];if(!b)return null;const{label:v,isArrayChild:g}=Px(y,e),w=b.type==="map"||b.type==="array",x=Dx(y,e),_=ll(y,e),j=p.get(_),k=s.has(_),N=a===e,A=l.current.has(e);return N?o.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:o.jsx(Lx,{node:b,isNew:A,isArrayChild:g,tree:y,editor:n,registry:r,path:x,onCommitNeeded:m,onDone:()=>{l.current.delete(e),c(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),c(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":k,onClick:()=>i(_),children:o.jsx("span",{"aria-hidden":"true",children:k?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),g?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?k?null:o.jsx("span",{className:"fs-doctree__preview",children:Ox(y,e,{asVectorView:Ze,vectorPreview:Bc})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(ts,{value:b.value,path:x,fieldEditors:r})}),o.jsxs("span",{className:"fs-doctree__hover",children:[o.jsxs("span",{className:"fs-doctree__typenote",children:["(",b.type,")"]}),w?o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${v||"document"}`,onClick:()=>u(e,b.type==="array"?"array":"map"),children:"+"}):o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${v}`,onClick:()=>c(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:R=>void d(b,v,{shiftKey:R.shiftKey}),children:"🗑"})]})]}),w&&k?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(R=>o.jsx(dl,{nodeId:R,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:m,onReferenceClick:f,updates:p},R)),o.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,b.type==="array"?"array":"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," ",b.type==="array"?"Add item":"Add field"]})})]}):null]})}function Lx({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:c,onDone:l,onCancelNew:u}){const[d,m]=h.useState(e.key??""),[f,p]=h.useState(e.type),[y,b]=h.useState(e.value),[v,g]=h.useState(!1),w=n?void 0:d===""?"Field name is required":Tx(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:qc(f,y),_=!w&&!x,j=()=>{if(!_){g(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,y),c(),l()},k=()=>{t?u():l()},A=i[f]?.Edit,R=f!=="map"&&f!=="array"&&A?o.jsx(A,{value:y,path:a,error:v?x:void 0,onChange:S=>b(S)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,I=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:k,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:S=>{const E=S.target.value;p(E),E!=="map"&&E!=="array"&&E!==f&&b(Fx(E))},"aria-label":"Field type",children:(t?Ux:ul).map(S=>o.jsx("option",{value:S,children:S},S))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:S=>{S.key==="Enter"&&!S.target.matches("textarea")?(S.preventDefault(),j()):S.key==="Escape"&&(S.preventDefault(),k())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:S=>m(S.target.value),onBlur:()=>g(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,R,I]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function Fx(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function fl({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=Vv({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:o.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[o.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),o.jsx("ul",{className:"fs-doctree__sublist",children:s.map(a=>o.jsx("li",{children:r?o.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(a),"aria-label":`Open subcollection ${a.id}`,children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),o.jsx("span",{"aria-hidden":"true",children:"›"})]}):o.jsxs("div",{className:"fs-doctree__subrow",children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},a.path))})]})}function Vx(e){return e.split("/").filter(Boolean).length%2===0}function hl(e,t){async function*n(s,i,a=!1){const c=await t.listSubcollections(s.path);for(const l of c)yield*r(e.collection(s,l),i);a||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const a=await t.listDocuments(s.path);for(const c of a){const l=c.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,c.phantom===!0))}}return{async*start(s){const i={n:0};Vx(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function pl(e,t){for await(const n of e.start(t))if(n.done)return}async function ml({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:o.jsxs("label",{className:"fs-delete-recursive",children:[o.jsx("input",{type:"checkbox",onChange:a=>{s=a.currentTarget.checked}}),o.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await pl(r,t):await n.deleteDoc(t),!0):!1}function qx(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function Wx(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 zx(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function _a(e){return e.__pyricPhantom===!0}function Kx(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 Hx({handles:e}){const{target:t,navigate:n}=Hn(),r=e.adminFirestore,s=Ps(),i=h.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),a=h.useCallback(_=>{const j=typeof _=="function"?_(i):_;n({view:"firestore",path:j})},[n,i]),c=(_,j)=>a(k=>[...k.slice(0,_+1),j]),[l,u]=h.useState(null),d=h.useCallback(async({collectionId:_,docId:j,data:k})=>{if(!l||!_)return;const N=l.parentDocPath,A=N?s.collection(s.doc(r,N),_):s.collection(r,_);await Wx(s,A,j,k);const R=N?`${N}/${_}`:_;n({view:"firestore",path:En(`${R}/${j}`)})},[s,r,l,n]),m=[o.jsx(Yx,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:_=>a([{kind:"collection",id:_,path:_}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((_,j)=>_.kind==="collection"?o.jsx(Qx,{api:s,firestore:r,handles:e,collectionPath:_.path,selectedId:i[j+1]?.id??null,onSelect:k=>c(j,{kind:"document",id:k.id,path:k.path}),onCollectionDeleted:()=>a(k=>k.slice(0,j))},_.path):o.jsx(Xx,{api:s,firestore:r,handles:e,docPath:_.path,onOpenSubcollection:k=>c(j,{kind:"collection",id:k.id,path:k.path}),onReferenceClick:k=>n({view:"firestore",path:En(k.path)}),onStartCollection:()=>u({parentDocPath:_.path}),onDeleted:()=>a(k=>k.slice(0,j))},_.path))],{ref:f,size:p}=zn(Nx),{startIndex:y,visibleCount:b,emptySlots:v}=Ax(m.length,p),g=m.slice(y,y+b),w=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,x=[...g,...Array.from({length:v},(_,j)=>o.jsx(Jx,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(p==="wide")return;const _=f.current;if(!_)return;const j=document.activeElement;if(j&&j!==document.body&&_.contains(j))return;const k=_.querySelector(".fs-columns > .fs-col:last-child");k&&(k.tabIndex=-1,k.focus({preventScroll:!0}))},[i.length,p]),o.jsx(Ds,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[o.jsx(Gx,{path:i,onHome:()=>a([]),onJump:_=>a(j=>j.slice(0,_+1))}),o.jsx("div",{className:"fs-columns",children:x}),l?o.jsx(al,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function Gx({path:e,onHome:t,onJump:n}){return o.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[o.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>o.jsxs(h.Fragment,{children:[o.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?o.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):o.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function Jx({hint:e}){return o.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?o.jsx("p",{className:"fs-empty",children:e}):null})}function Yx({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=h.useMemo(()=>n.map(a=>e.collection(t,a)),[e,t,n]);return o.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:"Collections"}),o.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),o.jsx(Iw,{collections:i,onSelect:a=>r(a.id),emptyState:o.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function Qx({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const c=h.useMemo(()=>Kx(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:m,hasMore:f,loadMore:p,createDocument:y}=Fv({collection:c,mode:"live"}),[b,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(S=>{C||v(S.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,l]);const g=h.useMemo(()=>{const C=new Set(l.map(S=>S.id));return[...l,...b.filter(S=>S.length>0&&!C.has(S)).map(S=>zx(e.doc(t,`${r}/${S}`)))]},[l,b,e,t,r]),w=r.split("/").pop()??r,[x,_]=h.useState(null),[j,k]=h.useState(!1),N=wt(),A=h.useMemo(()=>hl(e,n),[e,n]),R=h.useCallback(async C=>{_(null);try{await ml({confirm:N,ref:C,api:e,recursiveImpl:A})}catch(S){_(S instanceof Error?S:new Error(String(S)))}},[e,N,A]),I=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){_(null);try{await pl(A,c),a()}catch(S){_(S instanceof Error?S:new Error(String(S)))}}},[N,A,c,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>k(!0),children:"+ New"})}),o.jsx(ol,{items:[{label:"Delete collection",onSelect:()=>void I(),destructive:!0}]})]}),j?o.jsx(al,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:S})=>{const E=await y(C,S,{onExisting:"fail"});i(E)},onClose:()=>k(!1)}):null,o.jsx(Dw,{documents:g,isLoading:u,error:d,updateScope:`${r}:${m}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:C=>{const S=C.ref;return o.jsx("span",{"data-pyric-selected":s===S.id?"":void 0,style:{display:"contents"},children:_a(C)?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"fs-doc-phantom",children:C.id}),o.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):C.id})},renderRowAction:C=>{if(_a(C))return null;const S=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${S.id}`,onClick:E=>{E.stopPropagation(),R(S)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function Xx({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:c}){const l=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:m}=Rv(l),f=h.useCallback(async(_,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),p=wt(),y=h.useMemo(()=>hl(e,n),[e,n]),[b,v]=h.useState(null),g=h.useCallback(async()=>{v(null);try{await ml({confirm:p,ref:l,api:e,recursiveImpl:y})&&c()}catch(_){v(_ instanceof Error?_:new Error(String(_)))}},[e,p,y,l,c]),w=h.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),x=u!=null&&qx(u);return o.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[x?null:o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:l.id}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:a,children:"+ Collection"})})]}),u&&x?o.jsx(Bx,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void g(),onDeleteDocumentFields:w,onCommit:async _=>{await e.setDoc(l,_)}},r):d?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):m?o.jsx("p",{className:"fs-empty",children:"Loading document…"}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"fs-empty",children:"This document does not exist."}),o.jsx(fl,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),b?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:b.message}):null]})}const Zx="block w-full text-sm text-soft-white";function ej({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:c,updateUser:l}=Is(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),c(t))},[t,c]);const m=n.find(f=>f.uid===u)??null;return o.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[o.jsxs("section",{className:"min-w-0",children:[o.jsx("input",{value:a,onChange:f=>c(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"}),o.jsx(Pc,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:Zx,emptyState:o.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:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),o.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),o.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:m?o.jsx(tj,{user:m,onSave:f=>l(m.uid,f)},m.uid):o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function tj({user:e,onSave:t}){const n=Dc({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),c=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return o.jsxs("div",{"data-pyric-ui":"auth-editor",children:[o.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",o.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"})]}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",o.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?o.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),o.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[o.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?o.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?o.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:c,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"}),o.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 ka(e){const t=Q(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Sa(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Ea(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const nj=[{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 rj(e){const t=Object.entries(e.customMetadata??{});return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[o.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),nj.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":n,children:[o.jsx("dt",{children:r}),o.jsx("dd",{children:i})]},n)}),t.length>0?o.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:r})]},`custom:${n}`))]})}function sj(){return o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:o.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 ij(){return o.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[o.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),o.jsx("path",{d:"M9.25 1.75v3h3"})]})}function aj(e){const t=e.kind==="folder";return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"storage__cell-name",children:[o.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?o.jsx(sj,{}):o.jsx(ij,{})}),o.jsx("span",{className:"storage__nm",children:e.name}),t?o.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),o.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),o.jsx("span",{className:"storage__cell-size"}),o.jsx("span",{className:"storage__cell-updated"})]})}function oj({storage:e,focusTarget:t}){const n=Hn(),r=t.kind==="object"?Q(t.path):null,s=t.kind==="prefix"?Q(t.path):r?ka(r):"",i=h.useCallback(C=>{const S=Q(C);n.navigate(S?{view:"storage",kind:"prefix",path:S}:{view:"storage",kind:"root"})},[n.navigate]),a=Fw({path:s,onPathChange:i}),c=C=>{n.navigate({view:"storage",kind:"object",path:Q(C)})},l=Lw(e,a.path),u=qw(),d=Yw(e),[m,f]=h.useReducer(ox,nl),p=Zw(e,{path:a.path,list:l,onComplete:C=>f({type:"materialize",path:ka(C.fullPath)})});h.useEffect(()=>{if(l.status==="success")for(const C of l.entries)C.kind==="folder"&&wa(m,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[l.status,l.entries,m]);const[y,b]=h.useState(!1),[v,g]=h.useState(""),[w,x]=h.useState(null),_=h.useRef(null),j=h.useMemo(()=>{const C=cx(m,a.path).filter(D=>!l.entries.some(V=>V.kind==="folder"&&V.name===D));if(C.length===0)return l.entries;const S=C.map(D=>{const V=Sa(a.path,D);return{kind:"folder",name:D,fullPath:V,ref:{fullPath:V,name:D}}});return[...[...l.entries.filter(D=>D.kind==="folder"),...S].sort((D,V)=>D.name<V.name?-1:D.name>V.name?1:0),...l.entries.filter(D=>D.kind==="object")]},[l.entries,m,a.path]),k=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const S=new Set(j.map(D=>D.name)),E=ax(C.map(D=>D.relativePath),S);p.upload(C.map((D,V)=>({path:E[V],data:D.file})))},A=C=>{C.preventDefault();const S=lx(v);if(S){x(S);return}const E=Sa(a.path,Q(v));f({type:"create",path:E}),a.setPath(E),g(""),x(null),b(!1)};h.useEffect(()=>u.clear(),[a.path,u.clear]);const R=p.tasks.filter(C=>C.status==="error"),I=d.verdictFor(a.path);return o.jsx(wx,{children:o.jsx(Ds,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(ex,{path:a.path,rootLabel:"files",onNavigate:a.setPath}),o.jsx("div",{className:"storage__actions",children:u.size>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),o.jsx(jx,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const S of u.selected)S.kind==="folder"&&C.deleted.includes(S.fullPath)&&f({type:"discard",path:S.fullPath});r&&u.selected.some(S=>S.kind==="object"?S.fullPath===r:r.startsWith(`${S.fullPath}/`))&&a.setPath(a.path),u.clear(),l.refresh()},onFailed:C=>{const S=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>S.has(E.fullPath))),l.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{b(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>_.current?.click(),children:"Upload files"}),o.jsx("input",{ref:_,type:"file",multiple:!0,hidden:!0,onChange:C=>{const S=Array.from(C.currentTarget.files??[]);S.length>0&&N(S.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:A,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{g(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&b(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.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,R.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[R.length===1?`Upload failed: ${Ea(R[0].fullPath)} — ${R[0].error?.message??"error"}`:`${R.length} uploads failed: ${R.map(C=>Ea(C.fullPath)).join(", ")}`,o.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,o.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[o.jsxs(rx,{className:"storage__browser",onFiles:N,disabled:!I.upload,disabledReason:I.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:k,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(tx,{entries:j,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:aj,renderRowAction:C=>o.jsx("label",{className:"storage__select-row",title:`Select ${C.name}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${C.name}`,checked:u.isSelected(C.fullPath),onChange:()=>u.toggle(C)})}),onNavigate:a.enter,onSelect:C=>c(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:wa(m,a.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."})}),o.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",a.path||""]})]}),o.jsx("div",{className:"storage__inspector",children:r?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__back",onClick:()=>a.setPath(a.path),"aria-label":"Back to files",children:"‹ Files"}),o.jsx(gx,{storage:e,path:r,renderMetadata:rj})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function cj({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return o.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[o.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),o.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 yl({view:e}){const{target:t}=Hn(),n=Me(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(cj,{view:e}):n.authApi?o.jsx(Nc,{value:n.authApi,children:o.jsx(Ca,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(Ca,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function Ca({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=Is(n),c=h.useMemo(()=>new Set(a.map(l=>l.uid)),[a]);switch(e){case"firestore":{const l=o.jsx(Hx,{handles:t,knownUids:c});return s?o.jsx(Nv,{value:s,children:l}):l}case"auth":return o.jsx(ej,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=o.jsx(oj,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(Bw,{value:i,children:l}):l}}}function lj(){return o.jsx(yl,{view:"firestore"})}function uj(){return o.jsx(yl,{view:"storage"})}function dj(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function fj(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function hj(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=dj(s,e);return i.size===s.size&&[...i].every(a=>s.has(a))?s:i})},[e]);const r=h.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 a=new Set(i);return a.has(s)?a.delete(s):a.add(s),a})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function pj({users:e,filter:t,onDelete:n,onComplete:r}){const s=wt(),[i,a]=h.useState(!1),[c,l]=h.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;a(!0),l(null);const f=await fj(e,n);a(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),c?o.jsx("span",{className:"auth-sub__error",children:c}):null]})}function bl(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 gl(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 mj(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return o.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[o.jsx("span",{className:"auth-ident__primary",title:n,children:n}),o.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function yj({auth:e}={}){const t=Te(),n=Me(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return o.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:o.jsx(xj,{status:t.status})});const i=o.jsx(Ds,{children:o.jsx(bj,{auth:r})});return s?o.jsx(Nc,{value:s,children:i}):i}function bj({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:c,updateUser:l,deleteUser:u}=Is(e),d=Hn(),m=d.target?.view==="auth"?d.target.uid:null,f=g=>d.navigate({view:"auth",uid:g}),p=h.useMemo(()=>t.find(g=>g.uid===m)??null,[t,m]),[y,b]=h.useState(!1),v=hj(t);return o.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[o.jsxs("div",{className:"auth-sub",children:[o.jsxs("span",{className:"auth-sub__h",children:["users ",o.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),o.jsx("input",{className:"auth-sub__filter",value:i,onChange:g=>a(g.target.value),placeholder:"filter users…","aria-label":"Filter users"}),o.jsx("div",{className:"auth-sub__right",children:v.selectedUsers.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[v.selectedUsers.length," selected"]}),o.jsx(pj,{users:v.selectedUsers,filter:i,onDelete:g=>Promise.resolve(u(g)),onComplete:g=>{v.replace(g),m&&!g.includes(m)&&f(null)}}),o.jsx("button",{type:"button",className:"auth-sub__clear",onClick:v.clear,children:"Clear selection"})]}):o.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{b(!0),f(null)},children:"Add user"})})]}),o.jsxs("div",{className:"auth-body","data-auth-level":p||y?"detail":"list",children:[o.jsx("div",{className:"auth-list",children:o.jsx(Pc,{users:t,isLoading:r,error:s,filter:i,onSelect:g=>{b(!1),f(g.uid)},renderIdentifier:mj,formatCreatedAt:gl,formatLastLoginAt:bl,renderSelectionHeader:o.jsx("label",{className:"auth-select",title:"Select all shown users",children:o.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:v.allVisibleSelected,onChange:g=>v.selectAll(g.currentTarget.checked)})}),renderSelection:g=>o.jsx("label",{className:"auth-select",title:`Select ${g.uid}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${g.uid}`,checked:v.isSelected(g.uid),onChange:()=>v.toggle(g.uid)})}),emptyState:o.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:o.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),o.jsx("div",{className:"auth-detail",children:y?o.jsx(gj,{onCancel:()=>b(!1),onCreate:async g=>{const w=await Promise.resolve(c(g));b(!1),f(w.uid)}}):p?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),o.jsx(wj,{user:p,onSave:g=>{g.mode==="edit"&&l(g.uid,g.request)},onProvidersChange:async g=>{await Promise.resolve(l(p.uid,{providerUserInfo:g}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):o.jsx("div",{className:"auth-detail__empty",children:o.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function gj({onCreate:e,onCancel:t}){const[n,r]=h.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(a=>{r(a instanceof Error?a:new Error(String(a)))}))};return o.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsx("div",{className:"auth-editor__who",children:"New user"}),o.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),o.jsx($c,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const Na=[...hc];function vj({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(p=>p.providerId),c=a.includes("password"),l=a.filter(p=>p!=="password"),u=l.filter(p=>!Na.includes(p)),d=p=>{r(null),t(p.map(y=>({providerId:y}))).catch(y=>{r(y instanceof Error?y:new Error(String(y)))})},m=(p,y)=>{d(y?[...l,p]:l.filter(b=>b!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return o.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[o.jsx("div",{className:"auth-group",children:"Sign-in providers"}),o.jsx("div",{className:"auth-providers-editor__list",children:[...Na,...u].map(p=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[o.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:y=>m(p,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:_n(p)}),o.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),c||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:c?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,o.jsx("div",{className:"auth-provider-custom",children:o.jsxs("label",{className:"auth-provider-custom__field",children:[o.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),o.jsxs("span",{className:"auth-provider-custom__row",children:[o.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),o.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function wj({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,c]=h.useState(!1),l=m=>{i(null),c(!1);try{t(m),c(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=gl(e.createdAt),d=bl(e.lastLoginAt);return o.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?o.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),o.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),o.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),o.jsx(vj,{user:e,onChange:n}),o.jsxs($c,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,a?o.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),o.jsx("div",{className:"auth-editor__foot",children:o.jsx(Sv,{user:e,onDelete:r,className:"auth-del"})})]})}function xj({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 o.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:o.jsx("p",{className:"auth-zero",children:t})})}function jj(e){return e.operationContext.source.kind==="studio"}function _j(e,t){return t?e.filter(n=>!jj(n)):[...e]}const kj=["all","allow","deny","bypassed"];function Gn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function Sj(e,t){return t==="all"?[...e]:e.filter(n=>Gn(n)===t)}function br(e){return e.rulesDisposition.kind==="evaluated"}function Ra(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}}const is="inspect";function vl(e){const t=e[is];return t||null}function wl(e,t){const{[is]:n,...r}=e;return t?{...r,[is]:t}:r}function Ej(e,t){return wl(e,vl(e)===t?null:t)}const Cj=h.lazy(()=>No(()=>import("./RulesCodeEditor.DsTAsKIa.js"),__vite__mapDeps([5,1,3])));function xl(e){return o.jsx(h.Suspense,{fallback:o.jsx(Nj,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(Cj,{...e})})}function Nj({value:e,minHeightRem:t=14}){return o.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 jl({denial:e,rulesSource:t}){const n=Rb(e);return o.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:[o.jsxs("section",{children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?o.jsx(Yr,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(Yr,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:e.unsupported?"unsupported":"denied"}),o.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),o.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?o.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."}):o.jsxs(o.Fragment,{children:[o.jsx(Rj,{denial:e,exp:n,rulesSource:t}),o.jsx($j,{denial:e})]}),o.jsx(Tj,{denial:e})]})}function Rj({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(Bj,{denial:e,exp:t,rulesSource:n}):s?o.jsx(Lj,{exp:t}):o.jsx(Pj,{denial:e,exp:t,rulesSource:n})}function Aj(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 a=JSON.parse(i);return Array.isArray(a)?a:null}catch{return null}}function Ij(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function Dj(e,t){if(e===void 0||t===void 0)return t;const s=Aj(e);if(s!==null){const a=s.find(l=>l.authoredLine===t);if(a!==void 0)return a.generatedLine}return t}function Pj({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=Dj(n,r),i=n!==void 0?Ij(n):void 0,a=e.result==="allow",c=!!(i&&i.trim().length>0);return o.jsx(De,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:c?o.jsx(xl,{value:i,readOnly:!0,markLine:s,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):o.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:[...t.ruleLines,...t.otherLines].join(`
114
- `)||"(no trace)"})})}function $j({denial:e}){const t=$b(e);return t.length===0?null:o.jsx(De,{label:"show the work — how the condition evaluated",children:o.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)=>o.jsx(_l,{step:n},r))})})}const Oj={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function _l({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:`→ ${kl(e.value)}`;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[o.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:Oj[e.outcome]}),o.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),o.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?o.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>o.jsx(_l,{step:r},s))]})}function kl(e){if(e===void 0)return"undefined";try{return JSON.stringify(kn(e))}catch{return String(e)}}function Tj({denial:e}){const t=Ob(e);return o.jsx(De,{label:"what the rule saw (request / resource)",children:o.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=>o.jsx(Mj,{variable:n},n.name))})})}function Mj({variable:e}){return o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?o.jsx(Sl,{value:e.value}):o.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Sl({value:e,depth:t=0}){const[n,r]=h.useState(t<2),s=kn(e);if(s===null||typeof s!="object")return o.jsx("span",{className:"font-mono text-xs text-soft-white",children:kl(s)});const i=Array.isArray(s)?s.map((a,c)=>[String(c),a]):Object.entries(s);return i.length===0?o.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):o.jsxs("div",{className:"flex flex-col",children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),o.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?o.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([a,c])=>o.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[o.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[a,":"]}),o.jsx(Sl,{value:c,depth:t+1})]},a))}):null]})}function Uj(e,t,n,r){if(!e||!n)return;const i=e.split(/\r?\n/),a=t!==void 0&&t.length>0;let c;a?c=`".${t}"`:c=null;const l=[];for(let p=0;p<i.length;p++){const y=i[p];!y.includes(n)||!(c===null||y.includes(c))||l.push(p+1)}if(l.length===1)return l[0];if(l.length===0)return;const d=(r??"").split("/").filter(Boolean);if(d.length===0)return l[0];let m=l[0],f=-1;for(const p of l){let y=0;const b=p-2,v=Math.max(0,b-30);for(let g=b;g>=v;g--){const w=i[g];for(const x of d)w.includes(`"${x}"`)&&y++}y>f&&(f=y,m=p)}return m}function Bj({denial:e,exp:t,rulesSource:n}){const r=Uj(n,t.phase,t.ruleExpression,e.rules?.matchedPath),s=e.result==="allow",i=n!==void 0&&n.trim().length>0;let a;t.implicitDeny||!t.ruleNode?a="rule node":r!==void 0?a=`rule node — ${t.ruleNode} · line ${r}`:a=`rule node — ${t.ruleNode}`;let c;return s?c="Deployed database.rules.json — the allowing rule is marked":c="Deployed database.rules.json — the denying rule is marked",o.jsxs(o.Fragment,{children:[o.jsx(De,{label:a,children:i?o.jsx(xl,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:c}):o.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}`:""]})}),!i&&t.ruleExpression?o.jsx(De,{label:"rule expression",children:o.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?o.jsx(De,{label:"$variable bindings",children:o.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([l,u])=>`${l.startsWith("$")?l:`$${l}`} → ${u}`).join(", ")})}):null,e.rules?.reason?o.jsx(De,{label:"simulator reason",children:o.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}function Lj({exp:e}){return o.jsxs(De,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?o.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,o.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(`
115
- `)||"(no trace)"})]})}function De({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function Aa({eventId:e,onClose:t}){const r=Vb().find(a=>a.id===e),s=r?.service??"firestore",i=Yb(s);return r?o.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[o.jsxs("div",{className:"traffic__inspector-bar",children:[o.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),o.jsx(jl,{denial:r,rulesSource:i})]}):o.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[o.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."}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const Fj=new Intl.NumberFormat,Vj={reads:"read operations",writes:"writes",deletes:"deletes"},qj={allows:"allowed requests",denies:"denied requests"};function Ia(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 Da(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function El(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=`${Fj.format(n)} observed ${n===1?t.singular:t.plural}`,a=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(a);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${Ia(u)}.`:`${Da(Ia(u))} tied for the largest share of ${t.subject} in this window.`}}const c=s[0],l=Math.round(c.total/n*100);return{total:n,headline:i,finding:`${Da(a(c))} accounted for ${l}% of ${t.subject} in this window.`}}function Wj(e){return El(e,{labels:Vj,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 zj(e){return El(e,{labels:qj,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 Kj=new Intl.NumberFormat,Hj=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Pa(e){return Kj.format(e)}function Ct(e){return Hj.format(e)}function Gj(e){return Gn(e)==="bypassed"}function Jj(e){return e.every(t=>t.total===0)}function Cl({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:c,methodology:l}){const[u,d]=h.useState(()=>new Set(n.map(f=>f.key))),m=h.useCallback(f=>{d(p=>{const y=new Set(p);return y.has(f)?y.delete(f):y.add(f),y})},[]);return o.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[o.jsxs("header",{className:"traffic__metric-story",children:[o.jsx("p",{className:"traffic__metric-eyebrow",children:e}),o.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),o.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),o.jsx(ev,{series:n,visible:u,onToggle:m,formatValue:Pa,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),Jj(n)?o.jsx("p",{className:"traffic__empty",children:i}):o.jsxs("div",{className:"traffic__metric-evidence",children:[o.jsxs("div",{className:"traffic__metric-evidence-header",children:[o.jsx("h4",{children:a}),o.jsxs("span",{children:[Ct(s.start),"–",Ct(s.end)]})]}),o.jsx(rv,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:Pa,formatTime:Ct,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:Ct(s.start)}),o.jsx("span",{children:Ct(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:c}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:l})]})]})]})}function Yj({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=$g({events:n,window:t,isAdmin:Gj}),s=h.useMemo(()=>Wj(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx(Cl,{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:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts successful Firestore sandbox ",o.jsx("code",{children:"get"}),"/",o.jsx("code",{children:"list"}),","," ",o.jsx("code",{children:"create"}),"/",o.jsx("code",{children:"update"}),"/",o.jsx("code",{children:"set"}),", and"," ",o.jsx("code",{children:"delete"}),"/",o.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",o.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 Qj({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=Og({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>zj(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx(Cl,{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:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",o.jsx("code",{children:"evaluated"}),", grouped by its ",o.jsx("code",{children:"allow"})," or ",o.jsx("code",{children:"deny"})," ","verdict."]}),o.jsxs("p",{children:[o.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."]})]})})})}const Xj=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function Zj(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function e_(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 t_(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:e_(n.length,r)}}function n_(e,t){return e?.start===t.start&&e.end===t.end?null:t}function r_(){const{tab:e,query:t}=ge();return e!=="traffic"?"timeline":Zj(t.view)}function s_(){const e=h.useSyncExternalStore(qt,r_,()=>"timeline"),t=h.useCallback(n=>{const r={...ge().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,le({tab:"traffic",query:r})},[]);return[e,t]}function i_(){const e=h.useSyncExternalStore(qt,()=>ge().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...ge().query};n.hide==="studio"?delete n.hide:n.hide="studio",le({tab:"traffic",query:n})},[]);return[e,t]}function a_(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 $a(e){return`${Mt(e.start)}–${Mt(e.end)}`}function o_({event:e}){const t=Gn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function c_(){return h.useSyncExternalStore(qt,()=>vl(ge().query),()=>null)}const gr=100;function l_(){const e=Fb(),[t,n]=s_(),[r,s]=i_(),i=h.useMemo(()=>_j(e,r),[e,r]),a=e.length-i.length,[c,l]=h.useState("all"),[u,d]=h.useState(null),m=c_(),[f,p]=h.useState(gr),y=E=>{le({tab:"traffic",query:Ej(ge().query,E)})},b=()=>{le({tab:"traffic",query:wl(ge().query,null)})};h.useEffect(()=>{if(!m)return;const E=D=>{D.key==="Escape"&&b()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[m]);const v=h.useMemo(()=>{const E=Date.now();if(i.length===0)return{start:E-15*6e4,end:E};let D=1/0;for(const V of i)V.at<D&&(D=V.at);return{start:Math.min(D,E-6e4),end:E+1e3}},[i]),g=v.end,w=h.useMemo(()=>u?t_(i,u):null,[i,u]),x=w?.events??i,_=h.useMemo(()=>Sj(x,c).sort((E,D)=>D.at-E.at),[x,c]),{items:j}=wg({events:_}),k=j.slice(0,f),N=j.length-k.length,A=i.length>=xn,R=i.filter(E=>E.result==="deny").length,I=E=>o.jsx(o_,{event:E}),C=E=>{if(br(E)){y(E.id);return}const D=Ra(E);D&&le(D)},S=m!=null&&k.some(E=>E.type!=="group"&&E.event.id===m);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[Xj.map(E=>o.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===E.id,onClick:()=>n(E.id),children:E.label},E.id)),o.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":r,onClick:s,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",r&&a>0?` (${a} hidden)`:""]})]}),t==="billable"?o.jsx(Yj,{events:i,window:v}):t==="rules"?o.jsx(Qj,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(Qg,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(D=>n_(D,E)),m&&b()},liveAt:v.end,bucketCount:36,className:"traffic__timeline",header:o.jsxs("div",{className:"traffic__tl-header",children:[o.jsxs("span",{className:"traffic__tl-count",children:[i.length," requests",A?` (showing latest ${xn})`:""]}),R>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":c==="deny",onClick:()=>l(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[R," denied"]}):null,o.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>o.jsxs("div",{className:"traffic__tl-axis",children:[o.jsx("span",{children:a_(E.start,g)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:$a(E)}),o.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),o.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:o.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),w?o.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[o.jsxs("div",{className:"traffic__time-focus-story",children:[o.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),o.jsx("h3",{children:$a(w.window)}),o.jsx("p",{children:w.finding})]}),o.jsx("button",{type:"button",onClick:()=>d(null),children:"Show all traffic"})]}):null,o.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[o.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),kj.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":c===E,onClick:()=>l(E),children:E},E))]}),m&&!S?o.jsx(Aa,{eventId:m,onClose:b},m):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?c==="all"?"No requests occurred in the selected interval.":`No ${c} traffic occurred in the selected interval.`:c==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${c} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:k.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx(Jg,{group:E,onSelect:D=>{const V=D;if(br(V)){y(V.id);return}const G=Ra(V);G&&le(G)},renderClassification:D=>I(D),formatTime:Mt})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Gn(E.event)??void 0,children:[o.jsx(Sc,{event:E.event,selected:E.event.id===m,onSelect:D=>C(D),renderClassification:D=>I(D),formatTime:Mt}),E.event.id===m&&br(E.event)?o.jsx(Aa,{eventId:m,onClose:b},m):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>p(E=>E+gr),children:["Show ",Math.min(N,gr)," more (",N," hidden)"]}):null]})]})]})}const Oa=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],Ta=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function Us(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`${Oa[t%Oa.length]}-${Ta[(t>>>4)%Ta.length]}`}function u_(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 d_(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function f_(e){const{provenance:t,identity:n}=u_(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:d_(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 h_(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=f_(e[r]);s&&n.push(s)}return n}const p_=20;function m_(e){le(e)}function ht({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:ft(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),m_(e))},children:n})}function y_(){const e=Te(),t=Vn(),n=Ns();if(t.status==="loading"||e.status==="pending")return o.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(o.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(o.jsxs(ht,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(o.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(o.jsxs(ht,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),Us(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function b_(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function g_(){const e=Wt(),t=h.useMemo(()=>h_(e,p_),[e]);return o.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[o.jsxs("header",{className:"studio-home__feed-head",children:[o.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),o.jsx(ht,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?o.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):o.jsx("div",{className:"studio-home__feed-scroll",children:o.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[o.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),o.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),o.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:b_(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(ht,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const v_=["firestore","auth","rtdb","storage","traffic"];function w_(){const e=Me(),t=Wt(),n=h.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 o.jsx("div",{className:"studio-home__tiles",children:v_.map(r=>{const s=Qe.find(i=>i.id===r);return s?o.jsxs(ht,{className:"studio-card studio-home__tile",target:{tab:r},children:[o.jsxs("span",{className:"studio-home__tile-top",children:[o.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?o.jsx("span",{className:"studio-badge",children:n[r]}):null]}),o.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function x_(){const e=Vn(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),o.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."}),o.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),o.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),o.jsx(ht,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?o.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."]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),o.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function j_(){const e=Me(),t=Wt(),n=Te(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return o.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[o.jsxs("div",{className:"studio-home__hero",children:[o.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),o.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),o.jsx(_c,{exposeFocus:Ny}),o.jsx(y_,{}),o.jsx("div",{className:"studio-home__body",children:r?o.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"})]}):s?o.jsx(x_,{}):o.jsxs(o.Fragment,{children:[o.jsx(g_,{}),o.jsx(w_,{})]})})]})}function te(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Xe(e){return te(e).split("/").filter(Boolean)}function as(e,t){return te([...Xe(e),...t.split("/").filter(Boolean)].join("/"))}function Nl(e,t){const n=Xe(e),r=Xe(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 Rl(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 a=Rl(i);if(a===null){n=!0;continue}a!==i&&(n=!0),r[s]=a}return Object.keys(r).length===0?null:n?r:e}function __(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 Bs(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Al(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Il(e,t){let n=e??null;for(const r of Xe(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function k_(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function os(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((a,c)=>os(a,t[c]));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(a=>a in r&&os(n[a],r[a]))}function S_(e,t){const n=new Map,r=(s,i)=>{if(!Bs(s)){n.set(i,["leaf",s??null]);return}const a=Al(s);n.set(i,["parent",a.map(([c])=>c)]);for(const[c,l]of a)r(l,as(i,c))};return r(e,te(t)),n}function E_(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(/[?#].*$/,""),te(t)}function C_(e){const t=Xe(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const N_=["string","number","boolean","json"];function Ma(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function R_(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function A_(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function I_(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 Dl(e){return{path:te(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Pl(e,t){const n=Nl(e.path,t);return n===null?null:Il(e.value,n)}function D_(e,t){const n=te(t);return n===e.path||e.expanded[n]===!0}function P_(e,t,n){const r=Al(Pl(e,t)),s=Math.min(r.length,e.pages[te(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function Ua(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=Nl(t.path,s);a!==null&&Bs(Il(t.value,a))?n[s]=i:r=!0}return r?n:e}function $l(e,t){switch(t.type){case"navigate":{const n=te(t.path);return n===e.path?e:Dl(n)}case"value":{if(te(t.path)!==e.path)return e;const n={...e,status:"live",value:Rl(t.value),error:null};return n.expanded=Ua(e.expanded,n),n.pages=Ua(e.pages,n),n}case"error":return te(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=te(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=te(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=te(t.path);return $l(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=te(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const $_=50;function O_(e,t,n={}){const r=n.pageSize??$_,s=te(t),[i,a]=h.useReducer($l,s,Dl),c=h.useMemo(()=>S_(i.value,i.path),[i.path,i.value]),l=Ms({scope:i.path,entries:c,equals:os,ready:i.status==="live"});i.path!==s&&a({type:"navigate",path:s}),h.useEffect(()=>{let b=!1;const v=e.subscribeValue(s,g=>{b||a({type:"value",path:s,value:g})},g=>{b||a({type:"error",path:s,message:g instanceof Error?g.message:String(g)})});return()=>{b=!0,v()}},[e,s]);const u=h.useCallback(b=>Pl(i,b),[i]),d=h.useCallback(b=>D_(i,b),[i]),m=h.useCallback(b=>P_(i,b,r),[i,r]),f=h.useCallback(b=>a({type:"toggle",path:b}),[]),p=h.useCallback(b=>a({type:"show-more",path:b,pageSize:r}),[r]),y=h.useCallback(b=>l.get(te(b)),[l]);return h.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:m,toggle:f,showMore:p,updateAt:y}),[i,r,u,d,m,f,p,y])}function T_({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=te(e),[a,c]=h.useState(!1),l=h.useRef(null);h.useEffect(()=>{a&&l.current?.select()},[a]);const u=f=>{f.preventDefault(),t(E_(l.current?.value??"")),c(!1)},d=()=>c(!1),m=C_(i);return o.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":a?"":void 0,"aria-label":"Database path",children:a?o.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?o.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,o.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})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[o.jsx("li",{"data-rtdb-crumb-item":!0,children:o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":m.length===0?"":void 0,"aria-current":m.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),m.map((f,p)=>{const y=p===m.length-1;return o.jsxs("li",{"data-rtdb-crumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":y?"":void 0,"aria-current":y?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),o.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>c(!0),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:o.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 M_({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=Xe(i.path),c=a.length===0?r:a[a.length-1];return o.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?o.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):o.jsx(Ol,{tree:e,api:t,onNavigate:n,path:i.path,label:c,isViewRoot:!0})})}function Ol({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),c=Bs(a),l=e.isExpanded(r),u=e.updateAt(r),[d,m]=h.useState(!1),[f,p]=h.useState(!1),[y,b]=h.useState(!1),[v,g]=h.useState(null),w=async(j,k)=>{try{await j(),g(null),k()}catch(N){g(N instanceof Error?N.message:String(N))}},x=()=>{m(!0),b(!1),c&&!l&&e.toggle(r)},_=c&&l?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":c?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":c&&l?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[c&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:o.jsx("path",{d:"M1 0l6 4-6 4z"})})}):o.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),o.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),c?null:o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),o.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":k_(a),title:"Edit value",onClick:()=>{p(!0),b(!1)},children:__(a)})]}),o.jsx("span",{"data-rtdb-actions":!0,children:y?o.jsxs("span",{"data-rtdb-confirm":!0,children:[o.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",c?" subtree":"","?"]}),o.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void w(()=>t.remove(r),()=>b(!1)),children:"Delete"}),o.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>b(!1),children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${Ba(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Ba(r)}`,title:"Delete",onClick:()=>b(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(La,{initialType:Ma(a),initialText:R_(a,Ma(a)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:j=>w(()=>t.set(r,j),()=>p(!1))}):null,d?o.jsx(La,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>m(!1),onSubmit:(j,k)=>w(()=>t.set(as(r,k),j),()=>m(!1))}):null,_?o.jsxs("ul",{"data-rtdb-children":!0,children:[_.entries.map(([j])=>o.jsx("li",{children:o.jsx(Ol,{tree:e,api:t,onNavigate:n,path:as(r,j),label:j})},j)),_.hiddenCount>0?o.jsx("li",{"data-rtdb-show-more-item":!0,children:o.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",_.hiddenCount," hidden)"]})}):null]}):null]})}function Ba(e){const t=Xe(e);return t.length===0?"root":t[t.length-1]}function La({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),c=h.useRef(null),[l,u]=h.useState(t),[d,m]=h.useState(null),f=y=>{y.preventDefault();const b=a.current?.value??"";if(e){const g=A_(b);if(g){m(g);return}}const v=I_(l,c.current?.value??"");if(!v.ok){m(v.error);return}m(null),s(v.value,e?b.trim():void 0)},p=y=>{y.key==="Escape"&&i()};return o.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?o.jsx("input",{ref:a,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,o.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:y=>u(y.currentTarget.value),onKeyDown:p,children:N_.map(y=>o.jsx("option",{value:y,children:y},y))}),l==="boolean"?o.jsxs("select",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]}):o.jsx("input",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),o.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),o.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?o.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}function U_(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return o.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),o.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),o.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?o.jsx(L_,{live:t}):o.jsx(B_,{})]})}function B_(){return o.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[o.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),o.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 L_({live:e}){const[t,n]=h.useState("/"),r=Us(Ns()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(c,l)=>e.setRtdbValue(c,l),remove:c=>e.deleteRtdbValue(c),subscribeValue:(c,l,u)=>e.subscribeRtdbValue(c,l,u)}),[e]),a=O_(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(T_,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(M_,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function F_(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 tn(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function V_(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(tn(e.collections,"collection")),e.users&&t.push(tn(e.users,"user")),e.objects&&t.push(tn(e.objects,"file")),e.rtdbKeys&&t.push(tn(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Jn(){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 q_(){return o.jsxs("svg",{...Jn(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function W_(){return o.jsxs("svg",{...Jn(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function z_(){return o.jsxs("svg",{...Jn(),children:[o.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),o.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),o.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),o.jsx("path",{d:"M7 8.4v7.2"}),o.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function K_(){return o.jsxs("svg",{...Jn(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function nn({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return o.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[o.jsxs("span",{className:"studio-sandbox__action-top",children:[e,o.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),o.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function H_(){const e=Kb(),t=Hb(),n=Gb(),r=Jb(),s=Vn(),i=h.useRef(null),a=Us(Ns()),[c,l]=h.useState(!1),[u,d]=h.useState(!1),[m,f]=h.useState(!1),[p,y]=h.useState(!1),[b,v]=h.useState(""),g=jc(),{ensure:w}=g;h.useEffect(()=>w(),[w]);const x=F_(g.entries),_=V_(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",k=async()=>{const S=await t();if(!S||typeof document>"u")return;const E=URL.createObjectURL(new Blob([S],{type:"application/json"})),D=document.createElement("a");D.href=E,D.download=`pyric-sandbox-${a||"export"}.json`,D.click(),URL.revokeObjectURL(E)},N=async S=>{const E=S.target.files?.[0];if(S.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},A=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},R=async()=>{const S=b.trim();S&&(await r.save(S),v(""),y(!1))},I=async S=>{typeof window<"u"&&!window.confirm(`Switch to branch "${S}"? This replaces the current sandbox state.`)||await r.switchTo(S)},C=async S=>{typeof window<"u"&&!window.confirm(`Delete branch "${S}"?`)||await r.remove(S)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:_}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(nn,{glyph:o.jsx(q_,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void k()}),o.jsx(nn,{glyph:o.jsx(W_,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(nn,{glyph:o.jsx(z_,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(S=>!S)}),o.jsx(nn,{glyph:o.jsx(K_,{}),name:c?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:c,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),p?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:S=>{S.preventDefault(),R()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:b,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:S=>v(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!b.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,m?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&_!=="empty — no data yet"?`This erases ${_}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void A(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(S=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:S}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void I(S),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(S),children:"Delete"})]})]},S))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function rn(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 G_(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(a=>JSON.stringify(n[a])!==JSON.stringify(r[a]));if(i.length>0&&i.length<=3)return i.map(a=>`${a}: ${rn(n[a])} -> ${rn(r[a])}`).join(", ")}return`${rn(t.before)} -> ${rn(t.after)}`}function J_(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:G_(t),supported:t.qualification.supported}))}function Y_(e){const t=e.mutation.events.find(a=>a.result==="allow"||a.result==="deny"||a.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.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 Q_="pyric:assurance-campaign",X_="pyric-assurance-v1",cs=new Set;let Fa=!1,Va;function qa(e){for(const t of cs)t(e)}function Wa(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function Z_(){if(!(Fa||typeof document>"u")){Fa=!0,globalThis.addEventListener(Q_,e=>{const t=e.detail;Wa(t)&&qa(t)});try{Va=new BroadcastChannel(X_),Va.onmessage=e=>{Wa(e.data)&&qa(e.data)}}catch{}}}function ek(e){return Z_(),cs.add(e),()=>cs.delete(e)}function vr(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 tk=[vr({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"}}),vr({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"}),vr({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"}}})],xk=tk.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const ls="pyric:assurance:campaigns",Tl="pyric:assurance:campaign:";function nk(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function rk(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(ls)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${Tl}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(nk);return t.length,t}catch{return[]}}function sk(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(ls)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(ls,JSON.stringify(n)),sessionStorage.setItem(`${Tl}${e.campaignId}`,JSON.stringify(e))}catch{}}function ik(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 ak(){const[e,t]=h.useState(rk);return h.useEffect(()=>{const r=ek(s=>{sk(s),t(i=>ik(i,s))});return()=>{r()}},[]),e}function ok(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function ck(e){return e.replaceAll("-"," ")}function za({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function lk(){return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),o.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function Ka({attachment:e}){return e?o.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[o.jsxs("span",{children:[o.jsx("strong",{children:e.source.origin}),"read-only clone"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function uk({campaigns:e}){const t=ak(),n=e??t,r=ge().query,[s,i]=h.useState(r.campaign??n.find(x=>x.report)?.campaignId??n[0]?.campaignId??""),a=n.find(x=>x.campaignId===s)??n[0],c=h.useMemo(()=>a?.report?J_(a.report):[],[a]),[l,u]=h.useState(r.probe??c[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{c.some(x=>x.id===l)||u(c[0]?.id??"")},[c,l]),!a)return o.jsx(lk,{});const d=a.context?.attachment,m=a.report;if(!m)return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:a.campaignId}),o.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),o.jsxs("p",{children:[a.observations.length," known-good operation(s) and"," ",a.probes.length," probe(s) are available."]}),o.jsx(Ka,{attachment:d}),d?.coverageGaps.length?o.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.service}),x.reason]},x.code))}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=c.find(x=>x.id===l)??c[0],p=m.results.find(x=>x.probeId===f?.id),y=p?Y_(p):null,b=a.verifications?.at(-1),v=b!==void 0&&b.summary.controlsPassed===b.summary.probes&&b.summary.noCounterexamples===b.summary.probes&&b.summary.localCounterexamples===0&&b.summary.engineGaps===0&&b.summary.invalidProbes===0;function g(x){i(x);const j=n.find(k=>k.campaignId===x)?.report?.results[0]?.probeId??"";u(j),vn({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),vn({tab:"assurance",query:{campaign:a.campaignId,probe:x.id}})}return o.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[o.jsxs("header",{className:"assurance-surface__header",children:[o.jsxs("div",{children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-title",children:a.campaignId})]}),o.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?o.jsxs("label",{children:[o.jsx("span",{children:"Campaign"}),o.jsx("select",{value:a.campaignId,onChange:x=>g(x.target.value),children:n.map(x=>o.jsx("option",{value:x.campaignId,children:x.campaignId},x.campaignId))})]}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),o.jsx(Ka,{attachment:d}),o.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Controls"}),o.jsxs("strong",{children:[m.summary.controlsPassed,"/",m.summary.probes]})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Counterexamples"}),o.jsx("strong",{children:m.summary.localCounterexamples})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Candidate signals"}),o.jsx("strong",{children:m.summary.candidateSignals})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Engine gaps"}),o.jsx("strong",{children:m.summary.engineGaps})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Coverage gaps"}),o.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),b?o.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${v?"passed":"failed"}`,role:"status",children:[o.jsx("strong",{children:v?"Candidate rules verified":"Candidate rules need review"}),o.jsxs("span",{children:[b.summary.controlsPassed,"/",b.summary.probes," ","controls preserved"," | ",b.summary.noCounterexamples,"/",b.summary.probes," negative cases denied"]}),o.jsx("code",{children:b.campaignId})]}):null,d?.coverageGaps.length?o.jsxs("div",{className:"assurance-coverage-band",children:[o.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),o.jsx("span",{children:d.coverageGaps.map(x=>`${x.service}: ${x.reason}`).join(" ")})]}):null,o.jsxs("div",{className:"assurance-workspace",children:[o.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),o.jsx("span",{children:m.targetHash})]}),o.jsxs("div",{className:"assurance-table",role:"table",children:[o.jsxs("div",{className:"assurance-table__header",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Operation"}),o.jsx("span",{role:"columnheader",children:"Actor"}),o.jsx("span",{role:"columnheader",children:"Expected"}),o.jsx("span",{role:"columnheader",children:"Observed"}),o.jsx("span",{role:"columnheader",children:"Impact"})]}),c.map(x=>o.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":x.id===f?.id,onClick:()=>w(x),role:"row",children:[o.jsxs("span",{role:"cell",children:[o.jsx("small",{children:x.service}),x.operation]}),o.jsx("span",{role:"cell",children:x.actor}),o.jsx("span",{role:"cell",className:`assurance-verdict ${x.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:x.expected}),o.jsx("span",{role:"cell",className:`assurance-verdict ${ok(x.expected,x.observed)}`,children:x.observed}),o.jsx("span",{role:"cell",children:x.impact})]},x.id))]})]}),p?o.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:ck(p.classification)}),o.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),o.jsx("span",{children:p.actorEvidence.reachability})]}),o.jsxs("dl",{className:"assurance-facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Invariant"}),o.jsx("dd",{children:p.invariant.statement})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Mutation"}),o.jsx("dd",{children:p.mutationSpec.description})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Actor"}),o.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Fidelity"}),o.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(x=>!x.supported)?o.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(x=>!x.supported).map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.id}),x.reason]},x.id))}):null,p.stateDiff?o.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[o.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),o.jsxs("div",{className:"assurance-evidence__diff",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Before"}),o.jsx(za,{value:p.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(za,{value:p.stateDiff.after})]})]})]}):null,y?o.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[o.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),o.jsx(jl,{denial:y})]}):o.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function Ha(){return Bn()}function Ml(){return`${Bn()}docs`}function Ga(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function dk(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${Ml()}/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 fk({id:e}){const t=_y(e),n=Te(),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"),o.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[o.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),o.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),o.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),o.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>o.jsx("span",{children:s},s))})]})}function hk({id:e}){switch(e){case"home":return o.jsx(j_,{});case"firestore":return o.jsx(lj,{});case"auth":return o.jsx(yj,{});case"storage":return o.jsx(uj,{});case"rtdb":return o.jsx(U_,{});case"traffic":return o.jsx(l_,{});case"assurance":return o.jsx(uk,{});case"settings":return o.jsx(H_,{});default:return o.jsx(fk,{id:e})}}function pk(){const[e,t]=Cy(jy,"home"),n=l=>t(l),[r,s]=h.useState(!1),i=dk(),a=e==="home";h.useEffect(()=>{const l=u=>{if(Ay(u)){if(r){u.preventDefault(),s(!1);return}if(a){Ry()&&u.preventDefault();return}u.preventDefault(),s(!0)}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const c=Qe.filter(l=>l.id!=="home");return o.jsxs("div",{className:"studio","data-surface":e,children:[o.jsxs("header",{className:"studio__chrome",children:[o.jsx("div",{className:"studio__bar",children:o.jsxs("div",{className:"studio__chrome-inner",children:[o.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[o.jsx("a",{className:"studio__brand",href:Ha(),"aria-label":"Pyric",children:"pyric"}),o.jsx("a",{className:"studio__nav-tab",href:Ha(),children:"Home"}),i?o.jsx("a",{className:"studio__nav-tab",href:Ml(),children:"Docs"}):null,o.jsx("a",{className:"studio__nav-tab",href:ft({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:Ga(()=>n("home")),children:"Studio"})]}),o.jsx(gg,{})]})}),o.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:o.jsx("div",{className:"studio__chrome-inner",children:o.jsx("div",{className:"studio__nav",children:c.map(l=>o.jsx("a",{className:"studio__nav-tab",href:ft({tab:l.id}),"aria-current":l.id===e?"page":void 0,onClick:Ga(()=>n(l.id)),children:l.label},l.id))})})})]}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx(hk,{id:e})})}),r?o.jsx(rg,{onClose:()=>s(!1)}):null]})}function mk(){return o.jsx(by,{children:o.jsx(gf,{children:o.jsx(fy,{mode:"local",children:o.jsx(pk,{})})})})}function jk(){return o.jsx(h.StrictMode,{children:o.jsx(mk,{})})}export{jk as S,wk as a,rb as b,Ot as r,fe as s,Go as u};
112
+ color: hsl(${Math.max(0,Math.min(120-120*v,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return a.updateDeps=c=>{r=c},a}function aa(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Vg=(e,t)=>Math.abs(e-t)<1.01,qg=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},oa=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Wg=e=>e,zg=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},Kg=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:c,height:l}=a;t({width:Math.round(c),height:Math.round(l)})};if(s(oa(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const c=()=>{const l=a[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(oa(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},ca={passive:!0},la=typeof window>"u"?!0:"onscrollend"in window,Hg=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&la?()=>{}:qg(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:m,isRtl:f}=e.options;s=m?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},c=a(!0),l=a(!1);n.addEventListener("scroll",c,ca);const u=e.options.useScrollendEvent&&la;return u&&n.addEventListener("scrollend",l,ca),()=>{n.removeEventListener("scroll",c),u&&n.removeEventListener("scrollend",l)}},Gg=(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"]},Jg=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const a=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class Yg{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 a=()=>{const c=i.target,l=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(c,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));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:Wg,rangeExtractor:zg,onChange:()=>{},measureElement:Gg,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=it(()=>(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 a=r-1;a>=0;a--){const c=n[a];if(s.has(c.lane))continue;const l=i.get(c.lane);if(l==null||c.end>l.end?i.set(c.lane,c):c.end<l.end&&s.set(c.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,c)=>a.end===c.end?a.index-c.index:a.end-c.end)[0]:void 0},this.getMeasurementOptions=it(()=>[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,a,c,l)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=it(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l},u)=>{if(!a)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 m=this.measurementsCache.slice(0,d),f=new Array(c).fill(void 0);for(let p=0;p<d;p++){const y=m[p];y&&(f[y.lane]=p)}for(let p=d;p<n;p++){const y=i(p),b=this.laneAssignments.get(p);let v,g;const w=l==="estimate"||u.has(y);if(b!==void 0&&this.options.lanes>1){v=b;const _=f[v],N=_!==void 0?m[_]:void 0;g=N?N.end+this.options.gap:r+s}else{const _=this.options.lanes===1?m[p-1]:this.getFurthestMeasurement(m,p);g=_?_.end+this.options.gap:r+s,v=_?_.lane:p%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(p,v)}const x=u.get(y),k=typeof x=="number"?x:this.options.estimateSize(p),j=g+k;m[p]={index:p,start:g,size:k,end:j,key:y,lane:v},f[v]=p}return this.measurementsCache=m,m},{key:!1,debug:()=>this.options.debug}),this.calculateRange=it(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?Qg({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=it(()=>{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,a)=>i===null||a===null?[]:n({startIndex:i,endIndex:a,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)),a=Math.max(0,s-i),c=Math.min(this.options.count-1,s+i);return n>=a&&n<=c}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,c)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(c))});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 a=this.itemSizeCache.get(i.key)??i.size,c=r-a;c!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,c,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=c,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=it(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const c=n[i],l=r[c];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return aa(r[Pc(0,r.length-1,s=>aa(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(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,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(),a=this.measurementsCache[n];if(!a)return;if(r==="auto")if(a.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(a.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const c=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,r,a.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),a=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:a,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[a,c]=i,l=this.now();this.scrollState={index:n,align:c,behavior:s,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{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 a=r.length-1;for(;a>=0&&i.some(c=>c===null);){const c=r[a];i[c.lane]===null&&(i[c.lane]=c.end),a--}s=Math.max(...i.filter(c=>c!==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,a=s!==this.scrollState.lastTargetOffset;if(!a&&Vg(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Pc=(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 Qg({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 a=Pc(0,s,i,n),c=a;if(r===1)for(;c<s&&e[c].end<n+t;)c++;else if(r>1){const l=Array(r).fill(0);for(;c<s&&l.some(d=>d<n+t);){const d=e[c];l[d.lane]=d.end,c++}const u=Array(r).fill(n+t);for(;a>=0&&u.some(d=>d>=n);){const d=e[a];u[d.lane]=d.start,a--}a=Math.max(0,a-a%r),c=Math.min(s,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const ua=typeof document<"u"?h.useLayoutEffect:h.useEffect;function Xg({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var c;e&&a?Os.flushSync(n):n(),(c=t.onChange)==null||c.call(t,i,a)}},[s]=h.useState(()=>new Yg(r));return s.setOptions(r),ua(()=>s._didMount(),[]),ua(()=>s._willUpdate()),s}function Zg(e){return Xg({observeElementRect:Kg,observeElementOffset:Hg,scrollToFn:Jg,...e})}function Ts({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const c=h.useRef(null),l=typeof t=="function"?t:()=>t,u=Zg({count:e.length,getScrollElement:()=>c.current,estimateSize:l,overscan:r});return o.jsx("div",{ref:c,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:o.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const m=e[d.index],f=a?a(m,d.index):d.key;return o.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(m,d.index)},f)})})})}const ev={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function tv({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[c,l]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":c?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":c,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:ev[e.kind]}),o.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?o.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),c?o.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>o.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:o.jsx(Dc,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function nv(e){return e<0?0:e>1?1:e}function vr(e,t){const n=t.end-t.start;return n<=0?0:nv((e-t.start)/n)}function rv({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:c,header:l,axis:u,emptyState:d,className:m}){const f=h.useId(),[p,y]=h.useState(null),[b,v]=h.useState(null),g=Ng({events:e??[],window:n,bucketCount:r}),w=t??g,{buckets:x,total:k}=w,j=p??b,_=j===null?null:x.find(S=>S.index===j)??null,N=_!==null&&s?.start===_.start&&s.end===_.end;if(x.length===0)return o.jsx("div",{className:m,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const A=k===0,R=c===void 0?n.end:c,I=R==null?null:vr(R,n),C=typeof u=="function"?u(n):u;return o.jsxs("div",{className:m,"data-pyric-ui":"traffic-timeline","data-pyric-empty":A?"":void 0,children:[l!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:l}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(S=>o.jsx(sv,{bucket:S,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&_?.index===S.index?f:void 0,selected:s?.start===S.start&&s.end===S.end},S.index))}),_&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(_.index+.5)/Math.max(x.length,1)},children:a(_)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":vr(s.start,n),"--pyric-brush-right":1-vr(s.end,n)}}),I!=null&&o.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":I}})]}),C!=null&&o.jsx("div",{"data-pyric-timeline-axis":"",children:C})]})}function sv({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const c=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return o.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":a?"":void 0,disabled:!c,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":c?a: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:c?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[o.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const iv=e=>String(e);function av({series:e,visible:t,onToggle:n,formatValue:r=iv,className:s}){const i=t!==void 0&&n!==void 0;return o.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((a,c)=>{const l=t?t.has(a.key):!0,u=o.jsxs(o.Fragment,{children:[o.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-metric-label":"",children:a.label}),o.jsx("span",{"data-pyric-metric-value":"",children:r(a.total)})]});return i?o.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,"data-pyric-metric-hidden":l?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(a.key),"data-pyric-metric-checkbox":""}),u]},a.key):o.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,children:u},a.key)})})}const ov=e=>String(e),cv=e=>new Date(e).toLocaleTimeString();function lv({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=ov,formatTime:i=cv,emptyState:a,className:c}){const[l,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:a});const d=t.filter(g=>(!n||n.has(g.key))&&(!r||g.total>0));let m=0;for(const g of d)for(const w of g.values)w>m&&(m=w);const f=m===0?1:m,p=e.length,y=g=>p===1?50:g/(p-1)*100,b=g=>100-g/f*100,v=l!=null?e[l]:null;return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(g=>{const w=t.indexOf(g);if(!((!n||n.has(g.key))&&(!r||g.total>0)))return null;const k=g.values.map((j,_)=>`${_===0?"M":"L"}${y(_)},${b(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":g.key,"data-pyric-series-index":w,d:k,fill:"none",vectorEffect:"non-scaling-stroke"},g.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((g,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(g.start)} to ${i(g.end)}`},g.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(g=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":g.key,"data-pyric-series-index":t.indexOf(g),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:g.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(g.values[v.index])})]},g.key))]})]})})}const uv={listUsers:me.listUsers,subscribeUsers:me.subscribeUsers,createUser:me.createUser,updateUser:me.updateUser,deleteUser:me.deleteUser,clearUsers:me.clearUsers,getAuthProviderConfig:me.getAuthProviderConfig,setAuthProviderConfig:me.setAuthProviderConfig,subscribeAuthProviderConfig:me.subscribeAuthProviderConfig},$c=h.createContext(uv);function dv(){return h.useContext($c)}function Oc({value:e,children:t}){return h.createElement($c.Provider,{value:e},t)}function fv(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Ms(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=dv(),[c,l]=h.useState([]),[u,d]=h.useState(!0),[m,f]=h.useState(void 0),[p,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const _=I=>{j||(l(I),d(!1))},N=I=>{j||(l([]),f(I instanceof Error?I:new Error(String(I))),d(!1))},A=()=>{try{const I=t(e);I&&typeof I.then=="function"?I.then(_).catch(N):_(I)}catch(I){N(I)}};let R;try{A(),R=n(e,A)}catch(I){N(I)}return()=>{j=!0,R?.()}},[e,t,n]);const b=h.useMemo(()=>{const j=p.trim().toLowerCase();return j?c.filter(_=>fv(_,j)):c},[c,p]),v=h.useCallback(j=>r(e,j),[e,r]),g=h.useCallback((j,_)=>s(e,j,_),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),k=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(_=>l(_)).catch(()=>{}):l(j)},[e,t]);return{users:b,totalCount:c.length,isLoading:u,error:m,filter:p,setFilter:y,createUser:v,updateUser:g,deleteUser:w,clearUsers:x,refresh:k}}const hv=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],pv=1e3;function Tc(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>pv)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 hv)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const mv={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},yv=new Set(["password","anonymous","phone"]),bv=/^[^@]+@[^@]+\.[^@]+$/,da=6;function gv(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=>!yv.has(t))}:{...mv}}function vv(e){const t=gv(e);return{fields:t,initial:{...t}}}function wv(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function xv(e){const t={},n=e.email.trim(),r=e.password;n&&!bv.test(n)&&(t.email="Invalid email"),r&&r.length<da&&(t.password=`Password should be at least ${da} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Tc(e.claimsText);return s.ok||(t.claims=s.message),t}function jv(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Mc(t.providerIds,n.providerIds):t[r]!==n[r])}function Mc(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function Uc(e){const t=Tc(e.claimsText);return t.ok?t.claims:void 0}function kv(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=Uc(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function _v(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=Uc(t)??{}),Mc(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Bc(e={}){const[t,n]=h.useReducer(wv,e.initial,vv),r=h.useMemo(()=>xv(t.fields),[t.fields]),s=h.useMemo(()=>jv(t),[t]),i=h.useCallback((c,l)=>n({type:"setField",field:c,value:l}),[]),a=h.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:a,toCreateRequest:()=>kv(t),toUpdateRequest:()=>_v(t),dispatch:n}}const Sv={"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 Cn(e){return Sv[e]??e}function fa(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function Ev(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:Cn("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:Cn(t.providerId)},t.providerId))}function ha(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Lc({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:c,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:m=ha,formatLastLoginAt:f=ha,emptyState:p,noResultsState:y,className:b,virtualizeThreshold:v=100,rowHeight:g=44,virtualizedHeight:w="60vh"}){if(n)return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const j=!!r?.trim();return o.jsx("div",{className:b,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":j?"":void 0,children:j?y??"No results":p??"No users for this project yet"})}const x=e.length>v,k=j=>o.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":j.uid,"data-pyric-user-disabled":j.disabled?"":void 0,children:[c?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:c(j)}):null,o.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?o.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(j),children:i?i(j):fa(j)}):(i??fa)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??Ev)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:m(j.createdAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(j.lastLoginAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:j.uid}),u?o.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(j)}):null]},j.uid);return o.jsxs("div",{className:b,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":x?"":void 0,"data-pyric-selection":c?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[c?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,o.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),x?o.jsx(Ts,{items:e,estimateSize:g,height:w,getItemKey:j=>j.uid,renderItem:k}):o.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(k)})]})}function Cv({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return o.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[o.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:a=>t(a.target.value)}),n!=null&&o.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&o.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function Nv({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:wc.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:Cn(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Fc({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:c}){const l=Bc({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),m=(y,b,v,g,w=null)=>({name:y,label:b,input:g,error:w,kind:v,defaultRender:()=>v==="checkbox"?o.jsxs("label",{"data-pyric-field-label":y,children:[g,o.jsx("span",{"data-pyric-label-text":!0,children:b})]},y):v==="group"?o.jsxs("fieldset",{"data-pyric-field-label":y,children:[o.jsx("legend",{"data-pyric-label-text":!0,children:b}),g]},y):o.jsxs("label",{"data-pyric-field-label":y,children:[o.jsx("span",{"data-pyric-label-text":!0,children:b}),g,w!=null&&o.jsx("p",{role:"alert","data-pyric-field-error":y,children:w})]},y)}),f=[m("email","Email","text",o.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:y=>l.setField("email",y.target.value)}),l.errors.email??null),m("password","Password","text",o.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:y=>l.setField("password",y.target.value)}),l.errors.password??null),m("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:y=>l.setField("displayName",y.target.value)})),m("phone-number","Phone number","text",o.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:y=>l.setField("phoneNumber",y.target.value)})),m("photo-url","Photo URL","text",o.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:y=>l.setField("photoUrl",y.target.value)})),...u==="create"?[m("providers","Sign-in providers","group",o.jsx(Nv,{selected:l.fields.providerIds,onChange:y=>l.setField("providerIds",y)}))]:[],m("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:y=>l.setField("emailVerified",y.target.checked)})),m("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:y=>l.setField("disabled",y.target.checked)}))],p=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return o.jsxs("form",{className:a,"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(y=>c?o.jsx(h.Fragment,{children:c(y)},y.name):y.defaultRender()),o.jsx(Cv,{value:l.fields.claimsText,onChange:y=>l.setField("claimsText",y),error:l.errors.claims}),i,o.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?o.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,o.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}function Rv({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:c,className:l}){const u=h.useRef(null),d=h.useRef(null);return h.useEffect(()=>{if(!e)return;const m=f=>{f.key==="Escape"&&(f.stopPropagation(),t(!1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,t]),h.useEffect(()=>{if(e)return d.current=document.activeElement,u.current?.focus(),()=>{d.current?.focus?.()}},[e]),!e||typeof document>"u"?null:Os.createPortal(o.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:m=>{m.target===m.currentTarget&&t(!1)},children:[o.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),o.jsxs("div",{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:[o.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?o.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,o.jsxs("div",{"data-pyric-confirm-actions":!0,children:[o.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:a}),o.jsx("button",{ref:u,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:c,children:i})]})]})]}),document.body)}const Vc=h.createContext(null);function kt(){const e=h.useContext(Vc);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function Us({children:e,dialogClassName:t}){const[n,r]=h.useState(null),s=h.useRef(!1),i=h.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),a=h.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),c=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=h.useMemo(()=>i,[i]);return o.jsxs(Vc.Provider,{value:l,children:[e,n?o.jsx(Rv,{open:!0,onOpenChange:c,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:a,className:t}):null]})}function Av(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Iv({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const c=kt(),l=async()=>{await c({title:n,body:r??`This will permanently delete ${Av(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:l})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function Dv(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 Pv={addDoc:co,collection:It,deleteDoc:Nr,doc:He,getDoc:Eo,getDocs:gn,limit:wn,onSnapshot:hf,query:vn,setDoc:fn,startAfter:ff},qc=h.createContext(Pv);function Bs(){return h.useContext(qc)}function $v({value:e,children:t}){return h.createElement(qc.Provider,{value:e},t)}function Ov(e){const{onSnapshot:t}=Bs(),[n,r]=h.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return h.useEffect(()=>{if(!e){r({data:void 0,error:void 0,isLoading:!1});return}return r(i=>({data:i.data,error:void 0,isLoading:!0})),t(e,i=>r({data:i,error:void 0,isLoading:!1}),i=>r({data:void 0,error:Dv(i),isLoading:!1}))},[t,e]),n}function Jn(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&nt(e)!==null?"vector":Array.isArray(e)?"array":e instanceof bt?"timestamp":e instanceof ft?"geopoint":e instanceof On?"bytes":typeof e=="object"&&Wc(e)?"timestamp":typeof e=="object"&&zc(e)?"geopoint":typeof e=="object"&&Tv(e)?"reference":typeof e=="object"?"map":"null"}function Wc(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 zc(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function Tv(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 nt(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&tn(t.value)||t.__type__==="__vector__"&&tn(t.value))return nn(t.value);if(tn(t._values))return nn(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(tn(n))return nn(n)}catch{}return null}function tn(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function nn(e){const t=e.slice();return{values:t,dimension:t.length}}const pa=4;function Kc(e){const t=e.values.slice(0,pa).join(", "),n=e.values.length>pa?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function Nn(e){const t=nt(e);if(t)return Kc(t);if(Array.isArray(e))return e.map(Nn);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]=Nn(i);return r}}return e}function Hc(){return crypto.randomUUID()}function Mv(e){const t=Hc(),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))rs(n,t,r,s);return n}function rs(e,t,n,r){const s=Jn(r),i=Hc(),a={id:i,parentId:t,key:n,type:s,value:Uv(s)?void 0:r};if(e.nodes[i]=a,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[c,l]of Object.entries(r))rs(e,i,c,l);else if(s==="array"&&Array.isArray(r))for(const c of r)rs(e,i,null,c);return i}function Uv(e){return e==="map"||e==="array"}function Gc(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return ss(e,e.rootId)}function ss(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]=ss(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(ss(e,s));return r}default:return n.value}}function is(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 Jc(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 Yc(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 bt?void 0:"Expected a Timestamp";case"geopoint":return t instanceof ft?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 On?void 0:"Expected a Bytes value";case"vector":return nt(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Qc(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=Yc(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]??[],a=new Map;for(const c of i){const l=t[c];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[c].error=t[c].error??"Field name is required");const d=a.get(u)??[];d.push(c),a.set(u,d)}for(const[c,l]of a)if(c&&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 Ls(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return bt.now();case"geopoint":return new ft(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return On.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function as(e){if(e===null||typeof e!="object"||nt(e)!==null)return e;if(Wc(e)){const n=e;return new bt(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(zc(e)){const n=e;return new ft(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(as);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=as(s);return n}return e}function Xc(e){const t=Mv(as(e)),{tree:n,errorCount:r}=Qc(t);return{tree:n,initial:n,errorCount:r}}function Bv(e,t){switch(t.type){case"setValue":return at(e,n=>Fv(n,t.nodeId,t.value));case"setType":return at(e,n=>Vv(n,t.nodeId,t.newType));case"setKey":return at(e,n=>qv(n,t.nodeId,t.key));case"addMapEntry":return at(e,n=>Wv(n,t.parentId,t.key,t.childType));case"addArrayEntry":return at(e,n=>zv(n,t.parentId,t.childType));case"remove":return at(e,n=>Kv(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:Lv(e.initial)};case"replaceData":return Xc(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=is(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=is(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function at(e,t){const n=t(is(e.tree)),{tree:r,errorCount:s}=Qc(n);return{...e,tree:r,errorCount:s}}function Lv(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function Fv(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function Vv(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 a of i)for(const c of Jc(e,a))delete e.nodes[c],delete e.childIds[c];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:Ls(n);return e.nodes[t]={...r,type:n,value:s},e}function qv(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 Wv(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),a=r==="map"||r==="array"?void 0:Ls(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:a},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function zv(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:Ls(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 Kv(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Jc(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 Zc(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=Xc(t));const[r,s]=h.useReducer(Bv,n.current),i=h.useCallback((w,x)=>s({type:"setValue",nodeId:w,value:x}),[]),a=h.useCallback((w,x)=>s({type:"setType",nodeId:w,newType:x}),[]),c=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),l=h.useCallback((w,x,k)=>s({type:"addMapEntry",parentId:w,key:x,childType:k}),[]),u=h.useCallback((w,x)=>s({type:"addArrayEntry",parentId:w,childType:x}),[]),d=h.useCallback(w=>s({type:"remove",nodeId:w}),[]),m=h.useCallback(()=>s({type:"reset"}),[]),f=h.useCallback(w=>s({type:"replaceData",data:w}),[]),p=h.useCallback(w=>s({type:"touch",nodeId:w}),[]),y=h.useCallback(()=>s({type:"touchAll"}),[]),b=h.useCallback(()=>Gc(r.tree),[r.tree]),v=r.tree!==r.initial,g=r.errorCount===0;return h.useMemo(()=>({...r,isDirty:v,isValid:g,dispatch:s,setValue:i,setType:a,setKey:c,addMapEntry:l,addArrayEntry:u,remove:d,reset:m,replaceData:f,touch:p,touchAll:y,toData:b}),[r,v,g,i,a,c,l,u,d,m,f,p,y,b])}function Hv({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,c]=h.useState(!0),[l,u]=h.useState(void 0),[d,m]=h.useState(!1),[f,p]=h.useState(0),[y,b]=h.useState(n),v=h.useRef(0),[g,w]=h.useState(0),{addDoc:x,deleteDoc:k,doc:j,getDoc:_,getDocs:N,limit:A,onSnapshot:R,query:I,setDoc:C,startAfter:S}=Bs();h.useEffect(()=>{b(n)},[e,r,n,t]),h.useEffect(()=>{let P=!1;r==="paged"&&i([]),m(!1),c(!0),u(void 0);const O=t??e,T=r==="live"?y:n,$=I(O,A(T)),Y=se=>{P||(i([...se.docs]),m(se.docs.length===T),c(!1))},ce=se=>{P||(u(se instanceof Error?se:new Error(String(se))),c(!1))};if(r==="live"){const se=++v.current,zl=R($,Kl=>{w(se),Y(Kl)},ce);return()=>{P=!0,zl()}}return N($).then(se=>{Y(se)}).catch(ce),()=>{P=!0}},[e,N,A,r,R,n,t,I,y,f]);const E=h.useCallback(()=>{if(!d||a)return;if(r==="live"){c(!0),b($=>$+n);return}const P=s[s.length-1];if(!P)return;c(!0);const T=I(t??e,S(P),A(n));N(T).then($=>{i(Y=>[...Y,...$.docs]),m($.docs.length===n),c(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),c(!1)})},[e,s,N,d,a,A,r,n,t,I,S]),D=h.useCallback(async(P,O,T)=>{if(P==null){const Y=await x(e,O);return r==="paged"&&p(ce=>ce+1),Y}const $=j(e,P);if(T?.onExisting==="fail"){const Y=await _($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const se=new Error(`Document "${P}" already exists.`);throw se.code="already-exists",se}}return await C($,O),r==="paged"&&p(Y=>Y+1),$},[x,e,j,_,r,C]),V=h.useCallback(async P=>{await k(P),r==="paged"&&p(O=>O+1)},[k,r]),G=h.useCallback(()=>p(P=>P+1),[]);return{documents:s,isLoading:a,error:l,subscriptionGeneration:g,hasMore:d,loadMore:E,createDocument:D,deleteDocument:V,refresh:G}}function Gv({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=h.useState([]),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),l(void 0);return}let m=!1;return a(!0),l(void 0),u.current(e,t).then(f=>{m||(s(f),a(!1))}).catch(f=>{m||(l(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{m=!0}},[e,d]),{subcollections:r,isLoading:i,error:c}}function ma(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function ya(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Rn(e,t){if(Object.is(e,t))return!0;if(ma(e))return e.isEqual(t);if(ma(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)=>Rn(s,t[i]));if(!ya(e)||!ya(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&Rn(e[s],t[s]))}function Jv({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function Yv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Qv={type:"string",Display:Jv,Edit:Yv};function Xv({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function Zv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,a=i===""?Number.NaN:parseFloat(i);t(a)},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const ew={type:"number",Display:Xv,Edit:Zv};function tw({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function nw({value:e,onChange:t,path:n}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:o.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]})})}const rw={type:"boolean",Display:tw,Edit:nw};function sw({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function iw({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const aw={type:"null",Display:sw,Edit:iw};function el(e){if(e instanceof bt)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 ow({value:e,path:t}){const n=el(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return o.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function cw({value:e,onChange:t,error:n,path:r}){const s=el(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),a=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,16);return o.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"datetime-local",value:a,onChange:c=>{const l=c.target.value;if(!l)return;const u=new Date(l);t(bt.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const lw={type:"timestamp",Display:ow,Edit:cw};function uw({value:e,path:t}){return o.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 dw({value:e,onChange:t,error:n,path:r}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new ft(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new ft(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const fw={type:"geopoint",Display:uw,Edit:dw},tl=h.createContext({});tl.Provider;function hw(){return h.useContext(tl)}function pw({value:e,path:t}){const{onReferenceClick:n}=hw();return n?o.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}):o.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function mw({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,a=i.split("/").filter(Boolean),c=a[a.length-1]??"",l=e.firestore??{};t({path:i,id:c,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const yw={type:"reference",Display:pw,Edit:mw};function bw({value:e,path:t}){const n=e.toBase64();return o.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(e.toUint8Array().byteLength),children:n})}function gw({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("textarea",{value:e.toBase64(),onChange:s=>{try{t(On.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const vw={type:"bytes",Display:bw,Edit:gw};function os({value:e,path:t,fieldEditors:n}){const r=Jn(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function nl({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Jn(t),a=i==="map"||i==="array",[c,l]=h.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 a?o.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[o.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":c,onClick:()=>l(m=>!m),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),c?o.jsx(os,{value:t,path:n,fieldEditors:r}):null]}):o.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),o.jsx("span",{...u,children:e}),o.jsx(os,{value:t,path:n,fieldEditors:r})]})}function ww({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return o.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>o.jsx(nl,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const xw={type:"map",Display:ww};function jw({value:e,path:t,fieldEditors:n}){return o.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>o.jsx(nl,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const kw={type:"array",Display:jw},ba=4;function _w(e){return e.length<=ba?`[${e.join(", ")}]`:`[${e.slice(0,ba).join(", ")}, …]`}function Sw({value:e,path:t}){const n=nt(e);return n?o.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),o.jsx("span",{"data-pyric-vector-preview":!0,children:_w(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function Ew(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 Cw({value:e,onChange:t,error:n,path:r}){const s=nt(e),i=s?JSON.stringify(s.values):"[]",[a,c]=h.useState(i),[l,u]=h.useState(void 0),d=p=>{c(p);const y=Ew(p);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},m=s?s.dimension:0,f=l??n;return o.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(m),"data-pyric-error":f?"":void 0,children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${m}`}),o.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),o.jsx("textarea",{"data-pyric-vector-raw":!0,value:a,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?o.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const Nw={type:"vector",Display:Sw,Edit:Cw},ga={string:Qv,number:ew,boolean:rw,null:aw,timestamp:lw,geopoint:fw,reference:yw,bytes:vw,map:xw,array:kw,vector:Nw};function rl(e){return e?{...ga,...e}:ga}function Yn(e={}){const t=h.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=h.useState("wide");return h.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=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 c.observe(a),()=>c.disconnect()},[n,r]),{ref:t,size:s}}const sl=h.createContext(null);function Le(){const e=h.useContext(sl);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function Rw({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Zc({initial:e}),a=rl(t),c=h.useRef(n);c.current=n,h.useEffect(()=>{c.current?.(i)},[i]);const{ref:l,size:u}=Yn();return o.jsx(sl.Provider,{value:{editor:i,fieldEditors:a},children:o.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 Aw(){const{editor:e}=Le(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(Fs,{nodeId:n,path:Iw(e,n)},n)),o.jsx(il,{parentId:e.tree.rootId})]})}function Iw(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 Fs({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Le(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx($w,{node:s,path:t});if(s.type==="array")return o.jsx(Ow,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const c=s.touched?s.error:void 0;return o.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":c?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(Vs,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:c,onChange:l=>n.setValue(s.id,l)})]})}function Vs({node:e,path:t}){const{editor:n}=Le(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:o.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?o.jsx("input",{type:"text",value:e.key??"",onChange:a=>n.setKey(e.id,a.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,o.jsx(Pw,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const Dw=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function Pw({node:e}){const{editor:t}=Le(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=Dw.filter(s=>!(n?.type==="array"&&s==="array"));return o.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=>o.jsx("option",{value:s,children:s},s))})}function $w({node:e,path:t}){const{editor:n}=Le(),r=n.tree.childIds[e.id]??[];return o.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?o.jsx(Vs,{node:e,path:t}):null,o.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const a=t?`${t}.${i.key??""}`:i.key??"";return o.jsx(Fs,{nodeId:s,path:a},s)})}),o.jsx(il,{parentId:e.id})]})}function Ow({node:e,path:t}){const{editor:n}=Le(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[o.jsx(Vs,{node:e,path:t}),o.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const a=t?`${t}[${i}]`:`[${i}]`;return o.jsx("li",{"data-field-index":String(i),children:o.jsx(Fs,{nodeId:s,path:a})},s)})}),o.jsx(Tw,{parentId:e.id})]})}function il({parentId:e}){const{editor:t}=Le();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function Tw({parentId:e}){const{editor:t}=Le();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const va={Root:Rw,Fields:Aw};function Mw({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):o.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(a=>o.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":a.id,children:o.jsx("button",{type:"button",onClick:()=>r?.(a),"data-pyric-collection-select":!0,children:a.id})},a.path))})}const Nt=new Map;function qs({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),c=h.useRef(new Map),[l,u]=h.useState(Nt);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(Nt)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(Nt);return}const m=new Map;for(const[f,p]of t){const y=d.entries.has(f),b=d.entries.get(f);if(y&&n(b,p))continue;const v=a.current.get(f)===0?1:0;a.current.set(f,v),m.set(f,{kind:y?"modified":"added",cycle:v})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let y=m.size>0;for(const b of f.keys())t.has(b)||(p.delete(b),y=!0);for(const[b,v]of m)p.set(b,v);return y?p.size===0?Nt:p:f});for(const[f,p]of m){const y=c.current.get(f);y&&clearTimeout(y);const b=setTimeout(()=>{c.current.delete(f),u(v=>{if(v.get(f)?.cycle!==p.cycle)return v;const g=new Map(v);return g.delete(f),g.size===0?Nt:g})},r);c.current.set(f,b)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of c.current.values())clearTimeout(d);c.current.clear()},[]),l}function Rt(e){return e.ref}function Uw({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:c,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:m=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const y=h.useMemo(()=>new Map(e.map(g=>[Rt(g).path,g.data()])),[e]),b=qs({scope:d,entries:y,equals:Rn,ready:!t});if(n)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const v=e.length>m;return o.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":v?"":void 0,children:[v?o.jsx(Ts,{items:e,estimateSize:f,height:p,getItemKey:g=>Rt(g).path,renderItem:g=>{const w=b.get(Rt(g).path);return o.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":g.id,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(Rt(g)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(g):g.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(g)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(g=>{const w=Rt(g),x=b.get(w.path);return o.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":g.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(w),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:a?a(g):g.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(g)}):null]},w.path)})}),r&&i?o.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const Bw=/^__.*__$/;function al(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(Bw.test(e))return"Cannot match __.*__ (reserved)";if(Fw(e)>1500)return"Cannot exceed 1500 bytes"}function Lw(e){return al(e)}function Fw(e){return new TextEncoder().encode(e).length}function Vw(e){return al(e)}const wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function qw(){let e="";for(let t=0;t<20;t++)e+=wa.charAt(Math.floor(Math.random()*wa.length));return e}const Ww={ref:Ut,listAll:Ps,getMetadata:Wp,getBlob:mb,uploadBytes:tc,uploadBytesResumable:vb,deleteObject:Ds},ol=h.createContext(Ww);function Qn(){return h.useContext(ol)}function zw({value:e,children:t}){return h.createElement(ol.Provider,{value:e},t)}function wr(e){return e.replace(/^\/+|\/+$/g,"")}function cs(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function xr(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(cs)}function Kw(e,t){const{listAll:n,ref:r}=Qn(),s=wr(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[c,l]=h.useState(0),u=h.useRef(new Map);h.useEffect(()=>{if(u.current.clear(),e==null){a({status:"idle",items:[],prefixes:[],error:void 0});return}let y=!1;return a({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(b=>{y||a({status:"success",items:[...b.items].sort(cs),prefixes:[...b.prefixes].sort(cs),error:void 0})}).catch(b=>{y||a({status:"error",items:[],prefixes:[],error:b instanceof Error?b:new Error(String(b))})}),()=>{y=!0}},[e,s,c]);const d=h.useCallback(()=>l(y=>y+1),[]),m=h.useCallback(y=>{if(e==null)return;const b=y.endsWith("/"),v=wr(y),g=s===""?"":`${s}/`;if(!v.startsWith(g)||v===s)return;const w=v.slice(g.length),x=w.indexOf("/");a(k=>{if(k.status==="idle")return k;if(x===-1)return b?(u.current.set(v,k.prefixes.some(_=>_.fullPath===v)?null:v),{...k,prefixes:xr(k.prefixes,r(e,v))}):(u.current.set(v,k.items.some(_=>_.fullPath===v)?null:v),{...k,items:xr(k.items,r(e,v))});const j=`${g}${w.slice(0,x)}`;return u.current.set(v,k.prefixes.some(_=>_.fullPath===j)?null:j),{...k,prefixes:xr(k.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const b=wr(y),v=u.current.get(b);if(u.current.delete(b),v===null)return;const g=v??b;a(w=>({...w,items:w.items.filter(x=>x.fullPath!==g),prefixes:w.prefixes.filter(x=>x.fullPath!==g)}))},[]),p=h.useMemo(()=>[...i.prefixes.map(y=>({kind:"folder",name:y.name,fullPath:y.fullPath,ref:y})),...i.items.map(y=>({kind:"object",name:y.name,fullPath:y.fullPath,ref:y}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:m,removeItem:f}}function Q(e){return e.split("/").filter(Boolean).join("/")}function Hw(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>Q(r)),c=s?Q(t):i,l=h.useCallback(p=>{const y=Q(p);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>c===""?[]:c.split("/"),[c]),d=h.useCallback(p=>{const y=Q(p);l(y.includes("/")||c===""?y:`${c}/${y}`)},[c,l]),m=h.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=h.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:c,segments:u,setPath:l,enter:d,up:m,navigateToIndex:f}}const xa={status:"idle",blob:void 0,url:void 0,error:void 0};function Gw(e,t){const{getBlob:n,getMetadata:r,ref:s}=Qn(),i=t==null?null:Q(t),a=e!=null&&i!=null&&i!=="",[c,l]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(xa),[m,f]=h.useState(0),p=h.useRef(0);h.useEffect(()=>{if(p.current++,d(xa),!a){l({status:"idle",metadata:void 0,error:void 0});return}let g=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{g||l({status:"success",metadata:w,error:void 0})}).catch(w=>{g||l({status:"error",metadata:void 0,error:w instanceof Error?w:new Error(String(w))})}),()=>{g=!0}},[e,i,m]);const y=u.url;h.useEffect(()=>{if(y!==void 0)return()=>{URL.revokeObjectURL(y)}},[y]);const b=h.useCallback(()=>f(g=>g+1),[]),v=h.useCallback(()=>{if(e==null||i==null||i==="")return;const g=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(w=>{g===p.current&&d({status:"success",blob:w,url:URL.createObjectURL(w),error:void 0})}).catch(w=>{g===p.current&&d({status:"error",blob:void 0,url:void 0,error:w instanceof Error?w:new Error(String(w))})})},[e,i]);return{status:c.status,metadata:c.metadata,error:c.error,refresh:b,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function Jw(){const[e,t]=h.useState(()=>new Map),n=h.useCallback(u=>e.has(u),[e]),r=h.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const m=new Map(d);return m.set(u.fullPath,u),m})},[]),s=h.useCallback(u=>{t(d=>{if(!d.has(u))return d;const m=new Map(d);return m.delete(u),m})},[]),i=h.useCallback(u=>{t(d=>{const m=new Map(d);return m.has(u.fullPath)?m.delete(u.fullPath):m.set(u.fullPath,u),m})},[]),a=h.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),c=h.useCallback(()=>t(new Map),[]);return{selected:h.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:a,clear:c}}function Yw(e,t){const n=Ut(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function Qw(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function Xw(e){return{async*start(t){const n=e??{listAll:Ps,deleteObject:Ds};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const c=await n.listAll(a);s.push(...c.prefixes);for(const l of c.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(Qw(a))}catch{}yield{deletedCount:r,done:!0}}}}function Zw(e,t={}){const n=Qn(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(0),d=h.useRef(t);return d.current=t,{deleteEntries:h.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const b=d.current.impl??Xw(n);let v=0;try{for(const g of f){d.current.list?.removeItem(g.fullPath);try{if(g.kind==="object")await n.deleteObject(n.ref(e,g.fullPath)),v++;else for await(const w of b.start(n.ref(e,g.fullPath))){if(p!==u.current)return y;if(s(v+w.deletedCount),w.done){v+=w.deletedCount;break}}y.deleted.push(g.fullPath),p===u.current&&s(v)}catch(w){const x=w instanceof Error?w:new Error(String(w));y.failed.push({fullPath:g.fullPath,error:x}),d.current.list?.insertItem(g.kind==="folder"?`${g.fullPath}/`:g.fullPath),p===u.current&&y.failed.length===1&&l(x)}}return y}finally{p===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:c}}const ex=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),tx=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 nx(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[Fn],[c,l]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?Gr(r):r;l({status:"ready",rules:w,source:"option",error:void 0})}catch(w){l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let g=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{g||l({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{g||l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}),()=>{g=!0}},[a,r]);const u=s!==void 0?s:a?.context.auth??null,{rules:d,status:m}=c,f=i?.size,p=i?.contentType,y=h.useCallback(g=>{if(d==null)return m==="ready"?tx:ex;const w=Q(g),x=a?.bucket??"pyric-default",k=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=I=>Xo(d,{request:{auth:u,method:I,path:k,...I==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),_=j("read"),N=j("create"),A=j("delete"),R=N;return{read:_.allowed,write:R.allowed,delete:A.allowed,upload:N.allowed,reasons:{read:_.allowed?[]:_.reasons,write:R.allowed?[]:R.reasons}}},[d,m,a?.bucket,u,f,p]),b=typeof n=="string"?n:(n??[]).join(`
113
+ `),v=h.useMemo(()=>{const g=typeof n=="string"?[n]:n??[],w={};for(const x of g)w[Q(x)]=y(x);return w},[b,y]);return{status:m,source:c.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:c.error}}function ja(e,t){return e===""?t:t===""?e:`${e}/${t}`}function rx(e){return e instanceof Blob?e.size:e.byteLength}function sx(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function ix(e,t={}){const{ref:n,uploadBytes:r}=Qn(),s=Q(t.path??""),[i,a]=h.useState([]),c=h.useRef(t);c.current=t;const l=h.useCallback(f=>{a(p=>p.map(y=>y.id===f.id?f:y))},[]),u=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const y=(Array.isArray(f)?f:[f]).map(b=>{const v=sx(b);return{task:{id:crypto.randomUUID(),fullPath:ja(s,Q(v.path)),status:"running",bytesTransferred:0,totalBytes:rx(v.data)},entry:v}});a(b=>[...b,...y.map(v=>v.task)]);for(const{task:b}of y)c.current.list?.insertItem(b.fullPath),c.current.onProgress?.(b);return Promise.all(y.map(async({task:b,entry:v})=>{try{const g=await r(n(e,b.fullPath),v.data,v.metadata),w={...b,status:"success",bytesTransferred:b.totalBytes,metadata:g.metadata};return l(w),c.current.onProgress?.(w),c.current.onComplete?.(w),w}catch(g){const w={...b,status:"error",error:g instanceof Error?g:new Error(String(g))};return c.current.list?.removeItem(b.fullPath),l(w),c.current.onError?.(w),w}}))},[e,s,l,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=ja(s,Q(f));if(p==="")throw new Error("createFolder: folder name is empty");c.current.list?.insertItem(`${p}/`);try{await r(Yw(e,p),new Blob([]),{contentType:"text/plain"})}catch(y){throw c.current.list?.removeItem(p),y}},[e,s,r]),m=h.useCallback(()=>{a(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:m}}function ax({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=Q(e),a=i===""?[]:i.split("/");return o.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:o.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[o.jsx("li",{"data-pyric-breadcrumb-item":!0,children:o.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":a.length===0?"":void 0,"aria-current":a.length===0?"page":void 0,children:n})}),a.map((c,l)=>{const u=l===a.length-1,d=a.slice(0,l+1).join("/");return o.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),o.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:c})]},d)})]})})}function ox({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:c,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:m=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:y,size:b}=Yn();if(n)return o.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 o.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 o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const v=x=>{if(!a)return{denied:!1};const k=a.verdictFor(x.fullPath);return k.read?{denied:!1}:{denied:!0,reason:k.reasons.read.join("; ")}},g=x=>{const k=x.kind==="object"&&x.fullPath===i;return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>x.kind==="folder"?r?.(x.fullPath):s?.(x.ref),"data-pyric-entry-select":!0,"data-pyric-selected":k?"":void 0,"aria-selected":k||void 0,children:c?c(x):x.name}),l?o.jsx("span",{"data-pyric-storage-action":!0,children:l(x)}):null]})},w=e.length>m;return o.jsx("div",{ref:y,className:d,"data-pyric-ui":"object-browser","data-size":b,"data-pyric-virtualized":w?"":void 0,children:w?o.jsx(Ts,{items:e,estimateSize:f,height:p,getItemKey:x=>`${x.kind}:${x.fullPath}`,renderItem:x=>{const k=v(x);return o.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:g(x)})}}):o.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(x=>{const k=v(x);return o.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:g(x)},`${x.kind}:${x.fullPath}`)})})})}async function cl(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,a)=>e.file(i,a));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((a,c)=>s.readEntries(a,c));if(i.length===0)break;for(const a of i)await cl(a,r,n)}}}async function cx(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 cl(i,"",t);else{const a=r.getAsFile?.();a&&t.push({file:a,relativePath:a.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function lx({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),c=h.useRef(0),l=h.useCallback(f=>{f.preventDefault(),!n&&(c.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(c.current=Math.max(0,c.current-1),c.current===0&&a(!1))},[n]),m=h.useCallback(f=>{if(f.preventDefault(),c.current=0,a(!1),n)return;const p=f.dataTransfer;p&&cx(p).then(y=>{y.length>0&&e(y)})},[n,e]);return o.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:m,children:t})}function ux(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 dx(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 ka(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=ux(e),{base:s,counter:i}=dx(n);let a=i===null?1:i+1;for(;;){const c=`${s} (${a})${r}`;if(!t.has(c))return c;a+=1}}function fx(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=ka(s,n);return n.add(l),l}const a=s.slice(0,i);let c=r.get(a);return c===void 0&&(c=ka(a,n),n.add(c),r.set(a,c)),`${c}${s.slice(i)}`})}function _a(e){const t=Q(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const ll=[];function hx(e,t){switch(t.type){case"create":{const n=_a(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(_a(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=Q(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:ll}}function px(e,t){const n=Q(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 Sa(e,t){return e.includes(Q(t))}function mx(e){const t=Q(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const yx=256*1024;function ls(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const bx={id:"image",match:e=>ls(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?o.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function gx({blob:e,isJson:t}){const[n,r]=h.useState(void 0);return h.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:o.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const vx={id:"text",match:e=>{const t=ls(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:yx,render:({metadata:e,blob:t})=>t?o.jsx(gx,{blob:t,isJson:ls(e)==="application/json"}):null},wx=[bx,vx];function xx(e,t){for(const n of[...t??[],...wx])if(n.match(e))return n}const jx=[{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 kx({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[jx.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":t,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[o.jsx("dt",{children:t}),o.jsx("dd",{children:n})]},`custom:${t}`))]})}function _x({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:c}=Yn(),l=Gw(e,t),{metadata:u,blobStatus:d,loadBlob:m}=l,f=u?xx(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,y=f?.needsBlob===!0&&!p;if(h.useEffect(()=>{y&&d==="idle"&&m()},[y,d,m]),l.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let b,v={};return f===void 0?v={"data-pyric-preview-none":""}:p?v={"data-pyric-preview-too-large":""}:y&&d==="loading"?v={"data-pyric-preview-loading":""}:y&&d==="error"?(v={"data-pyric-preview-error":""},b=l.blobError?.message):(!y||d==="success")&&(b=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":c,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(kx,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:b}),s]})}const ul=h.createContext(null);function Sx(){const e=h.useContext(ul);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function Ex({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=h.useState([]),a=h.useCallback(u=>{i(d=>d.filter(m=>m.id!==u))},[]),c=h.useCallback(u=>{const d=crypto.randomUUID(),m=u.duration??t;return i(f=>[...f,{id:d,...u}]),m>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},m),d},[t]),l=h.useMemo(()=>({toast:c,dismiss:a,toasts:s}),[c,a,s]);return o.jsxs(ul.Provider,{value:l,children:[e,o.jsx(Cx,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function Cx({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:Os.createPortal(o.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(a=>o.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":a.kind??"info",role:a.kind==="error"?"alert":"status",children:[o.jsx("div",{"data-pyric-toast-title":!0,children:a.title}),a.body?o.jsx("div",{"data-pyric-toast-body":!0,children:a.body}):null,o.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(a.id),children:"×"})]},a.id))}),document.body)}function Nx({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:c="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:m}){const f=kt(),{toast:p}=Sx(),{deleteEntries:y,isRunning:b,progress:v}=Zw(e,{impl:n,list:r}),g=s?t.map(j=>({entry:j,verdict:s.verdictFor(j.fullPath)})).filter(j=>!j.verdict.delete):[],w=g.length===0?void 0:`Delete denied for ${g[0].entry.fullPath}${g.length>1?` (+${g.length-1} more)`:""}: ${g[0].verdict.reasons.write.join("; ")}`,x=b||t.length===0||e==null||g.length>0,k=async()=>{if(x||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:a??o.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>o.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:c}))return;const _=await y(t);_.failed.length===0?(p({title:`Deleted ${_.deleted.length} ${_.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(_)):(p({title:`Delete failed for ${_.failed.length} of ${t.length}`,kind:"error",body:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:_.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(_))};return d?o.jsx(o.Fragment,{children:d({onClick:k,isRunning:b,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:k,className:m,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":b?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:b?`Deleting… (${v})`:c})}function An(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 dl(e){const t=e.indexOf("?");return Rs(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function Rx(e){const{tab:t,rest:n,query:r}=dl(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:An(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 Ax(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 fl(e){const{tab:t,query:n}=dl(e),r=Rx(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Ea=null,us=fl("");function Ix(){const e=mc();return e!==Ea&&(Ea=e,us=fl(e)),us}function Dx(){return us}function rn(e){de(Ax(e))}function Px(e){de({tab:"traffic",query:{inspect:e}})}function Xn(){const e=h.useSyncExternalStore(Kt,Ix,Dx),t=h.useCallback(s=>rn(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":rn({view:"auth",uid:s.uid});break;case"storage":rn({view:"storage",kind:"object",path:s.objectPath});break;case"document":rn({view:"firestore",path:An(s.path)});break}},[]),r=h.useCallback(s=>Px(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const $x={narrowBreakpoint:640,mediumBreakpoint:920};function Ox(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function Tx(e,t){const n=Ox(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 jr({label:e,error:t,hint:n,children:r}){return o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:e}),r,t?o.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?o.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function hl({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,c]=h.useState(()=>qw()),[l,u]=h.useState(null),[d,m]=h.useState(null),[f,p]=h.useState(!1),y=h.useRef(null),b=e==="collection"&&s?Lw(s):void 0,v=a?Vw(a):void 0,w=!(e==="collection"&&(!s||b))&&!!a&&!v&&!f;h.useEffect(()=>{const j=_=>{_.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!l)){if(!l.isValid){l.touchAll();return}p(!0),m(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:Gc(l.tree)}),r()}catch(j){m(j instanceof Error?j:new Error(String(j))),p(!1)}}},k=e==="collection"?"Start a collection":"Add a document";return o.jsx("div",{className:"fs-modal-backdrop",onMouseDown:j=>{j.target===j.currentTarget&&!f&&r()},children:o.jsxs("div",{ref:y,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":k,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[o.jsx("h2",{className:"fs-modal__title",children:k}),o.jsx(jr,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(jr,{label:"Collection ID",error:b,children:o.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:j=>i(j.target.value),"data-pyric-field":"collection-id","aria-invalid":b?"true":void 0})}):null,o.jsx(jr,{label:"Document ID",error:a?v:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:o.jsx("input",{autoFocus:e==="document",type:"text",value:a,onChange:j=>c(j.target.value),"data-pyric-field":"doc-id","aria-invalid":v||!a?"true":void 0})}),o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:"Fields"}),o.jsx("div",{className:"fs-modal__fields",children:o.jsx(va.Root,{initial:{},onChange:u,children:o.jsx(va.Fields,{})})})]}),d?o.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,o.jsxs("div",{className:"fs-modal__actions",children:[o.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),o.jsx("button",{type:"button",className:"fs-editor__save",disabled:!w,onClick:()=>void x(),children:f?"Saving…":"Save"})]})]})})}function pl({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),c=()=>{if(!n){const l=a.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return h.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),o.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[o.jsx("button",{ref:a,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:c,children:o.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),o.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>o.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 ml(e){return JSON.stringify(e)}function Mx(e,t){const n=new Map,r=(s,i)=>{const a=t(s),c=ml(i);if(a==="map"){const l=s,u=Object.keys(l).sort();n.set(c,[a,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(a==="array"){const l=s;n.set(c,[a,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(c,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function yl(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 ml(n)}function Ux(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 Bx(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 Ca(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 Lx=42;function Fx(e,t,n,r=Lx){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(l=>Ca(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${Ca(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function Vx(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function qx(e){return e.shiftKey===!0}const bl=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],Wx=[...bl,"map","array"];function zx({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:c,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const m=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>m,[]),p=Zc({initial:f}),y=p.replaceData,b=h.useMemo(()=>rl(i),[i]),v=kt(),[g,w]=h.useState(()=>new Set),[x,k]=h.useState(null),j=h.useRef(e),_=h.useRef(new Set),N=h.useRef(!1),[A,R]=h.useState(null),I=h.useMemo(()=>Mx(m,Jn),[m]),C=qs({scope:t.path,entries:I,equals:Rn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,R(null),n(p.toData()).catch($=>{R($ instanceof Error?$:new Error(String($)))}))},[p.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,_.current.clear(),y(e.data()??{}))},[x,y,e]);const S=h.useCallback($=>{w(Y=>{const ce=new Set(Y);return ce.has($)?ce.delete($):ce.add($),ce})},[]),[E,D]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?p.addMapEntry($,"","string"):p.addArrayEntry($,"string"),$!==p.tree.rootId){const ce=yl(p.tree,$);w(se=>new Set(se).add(ce))}D($)},[p]);h.useEffect(()=>{if(!E)return;const $=p.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(_.current.add(Y),k(Y),D(null))},[p.tree,E]);const G=h.useCallback($=>{p.remove($),_.current.delete($),N.current=!0,x===$&&k(null)},[p,x]),P=h.useCallback(async($,Y,ce)=>{if(qx(ce)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,T=p.tree.childIds[p.tree.rootId]??[];return o.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[o.jsxs("div",{className:"fs-doctree__head",children:[o.jsx("span",{className:"fs-doctree__docid",children:O}),o.jsx(pl,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await v({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}]})]}),A?o.jsx("p",{className:"fs-doctree__err",children:A.message}):null,o.jsxs("ul",{className:"fs-doctree__rows",children:[c?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:c,children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>V(p.tree.rootId,"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),T.map($=>o.jsx(gl,{nodeId:$,depth:0,editor:p,registry:b,expanded:g,onToggle:S,editingId:x,setEditingId:k,newIdsRef:_,onAdd:V,onDelete:P,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),l&&u?o.jsx(vl,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function gl({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:m,onReferenceClick:f,updates:p}){const{tree:y}=n,b=y.nodes[e];if(!b)return null;const{label:v,isArrayChild:g}=Bx(y,e),w=b.type==="map"||b.type==="array",x=Ux(y,e),k=yl(y,e),j=p.get(k),_=s.has(k),N=a===e,A=l.current.has(e);return N?o.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:o.jsx(Kx,{node:b,isNew:A,isArrayChild:g,tree:y,editor:n,registry:r,path:x,onCommitNeeded:m,onDone:()=>{l.current.delete(e),c(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),c(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":_,onClick:()=>i(k),children:o.jsx("span",{"aria-hidden":"true",children:_?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),g?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?_?null:o.jsx("span",{className:"fs-doctree__preview",children:Fx(y,e,{asVectorView:nt,vectorPreview:Kc})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(os,{value:b.value,path:x,fieldEditors:r})}),o.jsxs("span",{className:"fs-doctree__hover",children:[o.jsxs("span",{className:"fs-doctree__typenote",children:["(",b.type,")"]}),w?o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${v||"document"}`,onClick:()=>u(e,b.type==="array"?"array":"map"),children:"+"}):o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${v}`,onClick:()=>c(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:R=>void d(b,v,{shiftKey:R.shiftKey}),children:"🗑"})]})]}),w&&_?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(R=>o.jsx(gl,{nodeId:R,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:m,onReferenceClick:f,updates:p},R)),o.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,b.type==="array"?"array":"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," ",b.type==="array"?"Add item":"Add field"]})})]}):null]})}function Kx({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:c,onDone:l,onCancelNew:u}){const[d,m]=h.useState(e.key??""),[f,p]=h.useState(e.type),[y,b]=h.useState(e.value),[v,g]=h.useState(!1),w=n?void 0:d===""?"Field name is required":Vx(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:Yc(f,y),k=!w&&!x,j=()=>{if(!k){g(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,y),c(),l()},_=()=>{t?u():l()},A=i[f]?.Edit,R=f!=="map"&&f!=="array"&&A?o.jsx(A,{value:y,path:a,error:v?x:void 0,onChange:S=>b(S)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,I=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:_,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:S=>{const E=S.target.value;p(E),E!=="map"&&E!=="array"&&E!==f&&b(Hx(E))},"aria-label":"Field type",children:(t?Wx:bl).map(S=>o.jsx("option",{value:S,children:S},S))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:S=>{S.key==="Enter"&&!S.target.matches("textarea")?(S.preventDefault(),j()):S.key==="Escape"&&(S.preventDefault(),_())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:S=>m(S.target.value),onBlur:()=>g(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,R,I]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function Hx(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function vl({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=Gv({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:o.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[o.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),o.jsx("ul",{className:"fs-doctree__sublist",children:s.map(a=>o.jsx("li",{children:r?o.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(a),"aria-label":`Open subcollection ${a.id}`,children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),o.jsx("span",{"aria-hidden":"true",children:"›"})]}):o.jsxs("div",{className:"fs-doctree__subrow",children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},a.path))})]})}function Gx(e){return e.split("/").filter(Boolean).length%2===0}function wl(e,t){async function*n(s,i,a=!1){const c=await t.listSubcollections(s.path);for(const l of c)yield*r(e.collection(s,l),i);a||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const a=await t.listDocuments(s.path);for(const c of a){const l=c.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,c.phantom===!0))}}return{async*start(s){const i={n:0};Gx(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function xl(e,t){for await(const n of e.start(t))if(n.done)return}async function jl({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:o.jsxs("label",{className:"fs-delete-recursive",children:[o.jsx("input",{type:"checkbox",onChange:a=>{s=a.currentTarget.checked}}),o.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await xl(r,t):await n.deleteDoc(t),!0):!1}function Jx(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function Yx(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 Qx(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function Na(e){return e.__pyricPhantom===!0}function Xx(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 Zx({handles:e}){const{target:t,navigate:n}=Xn(),r=e.adminFirestore,s=Bs(),i=h.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),a=h.useCallback(k=>{const j=typeof k=="function"?k(i):k;n({view:"firestore",path:j})},[n,i]),c=(k,j)=>a(_=>[..._.slice(0,k+1),j]),[l,u]=h.useState(null),d=h.useCallback(async({collectionId:k,docId:j,data:_})=>{if(!l||!k)return;const N=l.parentDocPath,A=N?s.collection(s.doc(r,N),k):s.collection(r,k);await Yx(s,A,j,_);const R=N?`${N}/${k}`:k;n({view:"firestore",path:An(`${R}/${j}`)})},[s,r,l,n]),m=[o.jsx(nj,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:k=>a([{kind:"collection",id:k,path:k}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((k,j)=>k.kind==="collection"?o.jsx(rj,{api:s,firestore:r,handles:e,collectionPath:k.path,selectedId:i[j+1]?.id??null,onSelect:_=>c(j,{kind:"document",id:_.id,path:_.path}),onCollectionDeleted:()=>a(_=>_.slice(0,j))},k.path):o.jsx(sj,{api:s,firestore:r,handles:e,docPath:k.path,onOpenSubcollection:_=>c(j,{kind:"collection",id:_.id,path:_.path}),onReferenceClick:_=>n({view:"firestore",path:An(_.path)}),onStartCollection:()=>u({parentDocPath:k.path}),onDeleted:()=>a(_=>_.slice(0,j))},k.path))],{ref:f,size:p}=Yn($x),{startIndex:y,visibleCount:b,emptySlots:v}=Tx(m.length,p),g=m.slice(y,y+b),w=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,x=[...g,...Array.from({length:v},(k,j)=>o.jsx(tj,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(p==="wide")return;const k=f.current;if(!k)return;const j=document.activeElement;if(j&&j!==document.body&&k.contains(j))return;const _=k.querySelector(".fs-columns > .fs-col:last-child");_&&(_.tabIndex=-1,_.focus({preventScroll:!0}))},[i.length,p]),o.jsx(Us,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[o.jsx(ej,{path:i,onHome:()=>a([]),onJump:k=>a(j=>j.slice(0,k+1))}),o.jsx("div",{className:"fs-columns",children:x}),l?o.jsx(hl,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function ej({path:e,onHome:t,onJump:n}){return o.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[o.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>o.jsxs(h.Fragment,{children:[o.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?o.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):o.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function tj({hint:e}){return o.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?o.jsx("p",{className:"fs-empty",children:e}):null})}function nj({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=h.useMemo(()=>n.map(a=>e.collection(t,a)),[e,t,n]);return o.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:"Collections"}),o.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),o.jsx(Mw,{collections:i,onSelect:a=>r(a.id),emptyState:o.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function rj({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const c=h.useMemo(()=>Xx(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:m,hasMore:f,loadMore:p,createDocument:y}=Hv({collection:c,mode:"live"}),[b,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(S=>{C||v(S.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,l]);const g=h.useMemo(()=>{const C=new Set(l.map(S=>S.id));return[...l,...b.filter(S=>S.length>0&&!C.has(S)).map(S=>Qx(e.doc(t,`${r}/${S}`)))]},[l,b,e,t,r]),w=r.split("/").pop()??r,[x,k]=h.useState(null),[j,_]=h.useState(!1),N=kt(),A=h.useMemo(()=>wl(e,n),[e,n]),R=h.useCallback(async C=>{k(null);try{await jl({confirm:N,ref:C,api:e,recursiveImpl:A})}catch(S){k(S instanceof Error?S:new Error(String(S)))}},[e,N,A]),I=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){k(null);try{await xl(A,c),a()}catch(S){k(S instanceof Error?S:new Error(String(S)))}}},[N,A,c,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>_(!0),children:"+ New"})}),o.jsx(pl,{items:[{label:"Delete collection",onSelect:()=>void I(),destructive:!0}]})]}),j?o.jsx(hl,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:S})=>{const E=await y(C,S,{onExisting:"fail"});i(E)},onClose:()=>_(!1)}):null,o.jsx(Uw,{documents:g,isLoading:u,error:d,updateScope:`${r}:${m}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:C=>{const S=C.ref;return o.jsx("span",{"data-pyric-selected":s===S.id?"":void 0,style:{display:"contents"},children:Na(C)?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"fs-doc-phantom",children:C.id}),o.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):C.id})},renderRowAction:C=>{if(Na(C))return null;const S=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${S.id}`,onClick:E=>{E.stopPropagation(),R(S)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function sj({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:c}){const l=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:m}=Ov(l),f=h.useCallback(async(k,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),p=kt(),y=h.useMemo(()=>wl(e,n),[e,n]),[b,v]=h.useState(null),g=h.useCallback(async()=>{v(null);try{await jl({confirm:p,ref:l,api:e,recursiveImpl:y})&&c()}catch(k){v(k instanceof Error?k:new Error(String(k)))}},[e,p,y,l,c]),w=h.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),x=u!=null&&Jx(u);return o.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[x?null:o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:l.id}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:a,children:"+ Collection"})})]}),u&&x?o.jsx(zx,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void g(),onDeleteDocumentFields:w,onCommit:async k=>{await e.setDoc(l,k)}},r):d?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):m?o.jsx("p",{className:"fs-empty",children:"Loading document…"}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"fs-empty",children:"This document does not exist."}),o.jsx(vl,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),b?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:b.message}):null]})}const ij="block w-full text-sm text-soft-white";function aj({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:c,updateUser:l}=Ms(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),c(t))},[t,c]);const m=n.find(f=>f.uid===u)??null;return o.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[o.jsxs("section",{className:"min-w-0",children:[o.jsx("input",{value:a,onChange:f=>c(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"}),o.jsx(Lc,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:ij,emptyState:o.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:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),o.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),o.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:m?o.jsx(oj,{user:m,onSave:f=>l(m.uid,f)},m.uid):o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function oj({user:e,onSave:t}){const n=Bc({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),c=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return o.jsxs("div",{"data-pyric-ui":"auth-editor",children:[o.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",o.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"})]}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",o.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?o.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),o.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[o.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?o.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?o.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:c,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"}),o.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 Ra(e){const t=Q(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Aa(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Ia(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const cj=[{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 lj(e){const t=Object.entries(e.customMetadata??{});return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[o.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),cj.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":n,children:[o.jsx("dt",{children:r}),o.jsx("dd",{children:i})]},n)}),t.length>0?o.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:r})]},`custom:${n}`))]})}function uj(){return o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:o.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 dj(){return o.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[o.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),o.jsx("path",{d:"M9.25 1.75v3h3"})]})}function fj(e){const t=e.kind==="folder";return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"storage__cell-name",children:[o.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?o.jsx(uj,{}):o.jsx(dj,{})}),o.jsx("span",{className:"storage__nm",children:e.name}),t?o.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),o.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),o.jsx("span",{className:"storage__cell-size"}),o.jsx("span",{className:"storage__cell-updated"})]})}function hj({storage:e,focusTarget:t}){const n=Xn(),r=t.kind==="object"?Q(t.path):null,s=t.kind==="prefix"?Q(t.path):r?Ra(r):"",i=h.useCallback(C=>{const S=Q(C);n.navigate(S?{view:"storage",kind:"prefix",path:S}:{view:"storage",kind:"root"})},[n.navigate]),a=Hw({path:s,onPathChange:i}),c=C=>{n.navigate({view:"storage",kind:"object",path:Q(C)})},l=Kw(e,a.path),u=Jw(),d=nx(e),[m,f]=h.useReducer(hx,ll),p=ix(e,{path:a.path,list:l,onComplete:C=>f({type:"materialize",path:Ra(C.fullPath)})});h.useEffect(()=>{if(l.status==="success")for(const C of l.entries)C.kind==="folder"&&Sa(m,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[l.status,l.entries,m]);const[y,b]=h.useState(!1),[v,g]=h.useState(""),[w,x]=h.useState(null),k=h.useRef(null),j=h.useMemo(()=>{const C=px(m,a.path).filter(D=>!l.entries.some(V=>V.kind==="folder"&&V.name===D));if(C.length===0)return l.entries;const S=C.map(D=>{const V=Aa(a.path,D);return{kind:"folder",name:D,fullPath:V,ref:{fullPath:V,name:D}}});return[...[...l.entries.filter(D=>D.kind==="folder"),...S].sort((D,V)=>D.name<V.name?-1:D.name>V.name?1:0),...l.entries.filter(D=>D.kind==="object")]},[l.entries,m,a.path]),_=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const S=new Set(j.map(D=>D.name)),E=fx(C.map(D=>D.relativePath),S);p.upload(C.map((D,V)=>({path:E[V],data:D.file})))},A=C=>{C.preventDefault();const S=mx(v);if(S){x(S);return}const E=Aa(a.path,Q(v));f({type:"create",path:E}),a.setPath(E),g(""),x(null),b(!1)};h.useEffect(()=>u.clear(),[a.path,u.clear]);const R=p.tasks.filter(C=>C.status==="error"),I=d.verdictFor(a.path);return o.jsx(Ex,{children:o.jsx(Us,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(ax,{path:a.path,rootLabel:"files",onNavigate:a.setPath}),o.jsx("div",{className:"storage__actions",children:u.size>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),o.jsx(Nx,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const S of u.selected)S.kind==="folder"&&C.deleted.includes(S.fullPath)&&f({type:"discard",path:S.fullPath});r&&u.selected.some(S=>S.kind==="object"?S.fullPath===r:r.startsWith(`${S.fullPath}/`))&&a.setPath(a.path),u.clear(),l.refresh()},onFailed:C=>{const S=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>S.has(E.fullPath))),l.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{b(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>k.current?.click(),children:"Upload files"}),o.jsx("input",{ref:k,type:"file",multiple:!0,hidden:!0,onChange:C=>{const S=Array.from(C.currentTarget.files??[]);S.length>0&&N(S.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:A,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{g(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&b(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.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,R.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[R.length===1?`Upload failed: ${Ia(R[0].fullPath)} — ${R[0].error?.message??"error"}`:`${R.length} uploads failed: ${R.map(C=>Ia(C.fullPath)).join(", ")}`,o.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,o.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[o.jsxs(lx,{className:"storage__browser",onFiles:N,disabled:!I.upload,disabledReason:I.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:_,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(ox,{entries:j,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:fj,renderRowAction:C=>o.jsx("label",{className:"storage__select-row",title:`Select ${C.name}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${C.name}`,checked:u.isSelected(C.fullPath),onChange:()=>u.toggle(C)})}),onNavigate:a.enter,onSelect:C=>c(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:Sa(m,a.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."})}),o.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",a.path||""]})]}),o.jsx("div",{className:"storage__inspector",children:r?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__back",onClick:()=>a.setPath(a.path),"aria-label":"Back to files",children:"‹ Files"}),o.jsx(_x,{storage:e,path:r,renderMetadata:lj})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function pj({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return o.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[o.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),o.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 kl({view:e}){const{target:t}=Xn(),n=Be(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(pj,{view:e}):n.authApi?o.jsx(Oc,{value:n.authApi,children:o.jsx(Da,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(Da,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function Da({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=Ms(n),c=h.useMemo(()=>new Set(a.map(l=>l.uid)),[a]);switch(e){case"firestore":{const l=o.jsx(Zx,{handles:t,knownUids:c});return s?o.jsx($v,{value:s,children:l}):l}case"auth":return o.jsx(aj,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=o.jsx(hj,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(zw,{value:i,children:l}):l}}}function mj(){return o.jsx(kl,{view:"firestore"})}function yj(){return o.jsx(kl,{view:"storage"})}function bj(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function gj(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function vj(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=bj(s,e);return i.size===s.size&&[...i].every(a=>s.has(a))?s:i})},[e]);const r=h.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 a=new Set(i);return a.has(s)?a.delete(s):a.add(s),a})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function wj({users:e,filter:t,onDelete:n,onComplete:r}){const s=kt(),[i,a]=h.useState(!1),[c,l]=h.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;a(!0),l(null);const f=await gj(e,n);a(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),c?o.jsx("span",{className:"auth-sub__error",children:c}):null]})}function _l(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 Sl(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 xj(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return o.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[o.jsx("span",{className:"auth-ident__primary",title:n,children:n}),o.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function jj({auth:e}={}){const t=Ue(),n=Be(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return o.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:o.jsx(Cj,{status:t.status})});const i=o.jsx(Us,{children:o.jsx(kj,{auth:r})});return s?o.jsx(Oc,{value:s,children:i}):i}function kj({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:c,updateUser:l,deleteUser:u}=Ms(e),d=Xn(),m=d.target?.view==="auth"?d.target.uid:null,f=g=>d.navigate({view:"auth",uid:g}),p=h.useMemo(()=>t.find(g=>g.uid===m)??null,[t,m]),[y,b]=h.useState(!1),v=vj(t);return o.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[o.jsxs("div",{className:"auth-sub",children:[o.jsxs("span",{className:"auth-sub__h",children:["users ",o.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),o.jsx("input",{className:"auth-sub__filter",value:i,onChange:g=>a(g.target.value),placeholder:"filter users…","aria-label":"Filter users"}),o.jsx("div",{className:"auth-sub__right",children:v.selectedUsers.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[v.selectedUsers.length," selected"]}),o.jsx(wj,{users:v.selectedUsers,filter:i,onDelete:g=>Promise.resolve(u(g)),onComplete:g=>{v.replace(g),m&&!g.includes(m)&&f(null)}}),o.jsx("button",{type:"button",className:"auth-sub__clear",onClick:v.clear,children:"Clear selection"})]}):o.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{b(!0),f(null)},children:"Add user"})})]}),o.jsxs("div",{className:"auth-body","data-auth-level":p||y?"detail":"list",children:[o.jsx("div",{className:"auth-list",children:o.jsx(Lc,{users:t,isLoading:r,error:s,filter:i,onSelect:g=>{b(!1),f(g.uid)},renderIdentifier:xj,formatCreatedAt:Sl,formatLastLoginAt:_l,renderSelectionHeader:o.jsx("label",{className:"auth-select",title:"Select all shown users",children:o.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:v.allVisibleSelected,onChange:g=>v.selectAll(g.currentTarget.checked)})}),renderSelection:g=>o.jsx("label",{className:"auth-select",title:`Select ${g.uid}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${g.uid}`,checked:v.isSelected(g.uid),onChange:()=>v.toggle(g.uid)})}),emptyState:o.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:o.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),o.jsx("div",{className:"auth-detail",children:y?o.jsx(_j,{onCancel:()=>b(!1),onCreate:async g=>{const w=await Promise.resolve(c(g));b(!1),f(w.uid)}}):p?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),o.jsx(Ej,{user:p,onSave:g=>{g.mode==="edit"&&l(g.uid,g.request)},onProvidersChange:async g=>{await Promise.resolve(l(p.uid,{providerUserInfo:g}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):o.jsx("div",{className:"auth-detail__empty",children:o.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function _j({onCreate:e,onCancel:t}){const[n,r]=h.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(a=>{r(a instanceof Error?a:new Error(String(a)))}))};return o.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsx("div",{className:"auth-editor__who",children:"New user"}),o.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),o.jsx(Fc,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const Pa=[...wc];function Sj({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(p=>p.providerId),c=a.includes("password"),l=a.filter(p=>p!=="password"),u=l.filter(p=>!Pa.includes(p)),d=p=>{r(null),t(p.map(y=>({providerId:y}))).catch(y=>{r(y instanceof Error?y:new Error(String(y)))})},m=(p,y)=>{d(y?[...l,p]:l.filter(b=>b!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return o.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[o.jsx("div",{className:"auth-group",children:"Sign-in providers"}),o.jsx("div",{className:"auth-providers-editor__list",children:[...Pa,...u].map(p=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[o.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:y=>m(p,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:Cn(p)}),o.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),c||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:c?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,o.jsx("div",{className:"auth-provider-custom",children:o.jsxs("label",{className:"auth-provider-custom__field",children:[o.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),o.jsxs("span",{className:"auth-provider-custom__row",children:[o.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),o.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function Ej({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,c]=h.useState(!1),l=m=>{i(null),c(!1);try{t(m),c(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=Sl(e.createdAt),d=_l(e.lastLoginAt);return o.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?o.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),o.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),o.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),o.jsx(Sj,{user:e,onChange:n}),o.jsxs(Fc,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,a?o.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),o.jsx("div",{className:"auth-editor__foot",children:o.jsx(Iv,{user:e,onDelete:r,className:"auth-del"})})]})}function Cj({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 o.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:o.jsx("p",{className:"auth-zero",children:t})})}function Nj(e){return e.operationContext.source.kind==="studio"}function Rj(e,t){return t?e.filter(n=>!Nj(n)):[...e]}const Aj=["all","allow","deny","bypassed"];function Zn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function Ij(e,t){return t==="all"?[...e]:e.filter(n=>Zn(n)===t)}function kr(e){return e.rulesDisposition.kind==="evaluated"}function $a(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}}const ds="inspect";function El(e){const t=e[ds];return t||null}function Cl(e,t){const{[ds]:n,...r}=e;return t?{...r,[ds]:t}:r}function Dj(e,t){return Cl(e,El(e)===t?null:t)}const Pj=h.lazy(()=>Po(()=>import("./RulesCodeEditor.DsTAsKIa.js"),__vite__mapDeps([5,1,3])));function Nl(e){return o.jsx(h.Suspense,{fallback:o.jsx($j,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(Pj,{...e})})}function $j({value:e,minHeightRem:t=14}){return o.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 Rl({denial:e,rulesSource:t}){const n=Ob(e);return o.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:[o.jsxs("section",{children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?o.jsx(ns,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(ns,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:e.unsupported?"unsupported":"denied"}),o.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),o.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?o.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."}):o.jsxs(o.Fragment,{children:[o.jsx(Oj,{denial:e,exp:n,rulesSource:t}),o.jsx(Lj,{denial:e})]}),o.jsx(Vj,{denial:e})]})}function Oj({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(zj,{denial:e,exp:t,rulesSource:n}):s?o.jsx(Kj,{exp:t}):o.jsx(Bj,{denial:e,exp:t,rulesSource:n})}function Tj(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 a=JSON.parse(i);return Array.isArray(a)?a:null}catch{return null}}function Mj(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function Uj(e,t){if(e===void 0||t===void 0)return t;const s=Tj(e);if(s!==null){const a=s.find(l=>l.authoredLine===t);if(a!==void 0)return a.generatedLine}return t}function Bj({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=Uj(n,r),i=n!==void 0?Mj(n):void 0,a=e.result==="allow",c=!!(i&&i.trim().length>0);return o.jsx($e,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:c?o.jsx(Nl,{value:i,readOnly:!0,markLine:s,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):o.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:[...t.ruleLines,...t.otherLines].join(`
114
+ `)||"(no trace)"})})}function Lj({denial:e}){const t=Lb(e);return t.length===0?null:o.jsx($e,{label:"show the work — how the condition evaluated",children:o.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)=>o.jsx(Al,{step:n},r))})})}const Fj={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function Al({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:`→ ${Il(e.value)}`;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[o.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:Fj[e.outcome]}),o.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),o.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?o.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>o.jsx(Al,{step:r},s))]})}function Il(e){if(e===void 0)return"undefined";try{return JSON.stringify(Nn(e))}catch{return String(e)}}function Vj({denial:e}){const t=Fb(e);return o.jsx($e,{label:"what the rule saw (request / resource)",children:o.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=>o.jsx(qj,{variable:n},n.name))})})}function qj({variable:e}){return o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?o.jsx(Dl,{value:e.value}):o.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Dl({value:e,depth:t=0}){const[n,r]=h.useState(t<2),s=Nn(e);if(s===null||typeof s!="object")return o.jsx("span",{className:"font-mono text-xs text-soft-white",children:Il(s)});const i=Array.isArray(s)?s.map((a,c)=>[String(c),a]):Object.entries(s);return i.length===0?o.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):o.jsxs("div",{className:"flex flex-col",children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),o.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?o.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([a,c])=>o.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[o.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[a,":"]}),o.jsx(Dl,{value:c,depth:t+1})]},a))}):null]})}function Wj(e,t,n,r){if(!e||!n)return;const i=e.split(/\r?\n/),a=t!==void 0&&t.length>0;let c;a?c=`".${t}"`:c=null;const l=[];for(let p=0;p<i.length;p++){const y=i[p];!y.includes(n)||!(c===null||y.includes(c))||l.push(p+1)}if(l.length===1)return l[0];if(l.length===0)return;const d=(r??"").split("/").filter(Boolean);if(d.length===0)return l[0];let m=l[0],f=-1;for(const p of l){let y=0;const b=p-2,v=Math.max(0,b-30);for(let g=b;g>=v;g--){const w=i[g];for(const x of d)w.includes(`"${x}"`)&&y++}y>f&&(f=y,m=p)}return m}function zj({denial:e,exp:t,rulesSource:n}){const r=Wj(n,t.phase,t.ruleExpression,e.rules?.matchedPath),s=e.result==="allow",i=n!==void 0&&n.trim().length>0;let a;t.implicitDeny||!t.ruleNode?a="rule node":r!==void 0?a=`rule node — ${t.ruleNode} · line ${r}`:a=`rule node — ${t.ruleNode}`;let c;return s?c="Deployed database.rules.json — the allowing rule is marked":c="Deployed database.rules.json — the denying rule is marked",o.jsxs(o.Fragment,{children:[o.jsx($e,{label:a,children:i?o.jsx(Nl,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:c}):o.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}`:""]})}),!i&&t.ruleExpression?o.jsx($e,{label:"rule expression",children:o.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?o.jsx($e,{label:"$variable bindings",children:o.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([l,u])=>`${l.startsWith("$")?l:`$${l}`} → ${u}`).join(", ")})}):null,e.rules?.reason?o.jsx($e,{label:"simulator reason",children:o.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}function Kj({exp:e}){return o.jsxs($e,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?o.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,o.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(`
115
+ `)||"(no trace)"})]})}function $e({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function Oa({eventId:e,onClose:t}){const r=Gb().find(a=>a.id===e),s=r?.service??"firestore",i=ng(s);return r?o.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[o.jsxs("div",{className:"traffic__inspector-bar",children:[o.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),o.jsx(Rl,{denial:r,rulesSource:i})]}):o.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[o.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."}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const Hj=new Intl.NumberFormat,Gj={reads:"read operations",writes:"writes",deletes:"deletes"},Jj={allows:"allowed requests",denies:"denied requests"};function Ta(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 Ma(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function Pl(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=`${Hj.format(n)} observed ${n===1?t.singular:t.plural}`,a=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(a);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${Ta(u)}.`:`${Ma(Ta(u))} tied for the largest share of ${t.subject} in this window.`}}const c=s[0],l=Math.round(c.total/n*100);return{total:n,headline:i,finding:`${Ma(a(c))} accounted for ${l}% of ${t.subject} in this window.`}}function Yj(e){return Pl(e,{labels:Gj,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 Qj(e){return Pl(e,{labels:Jj,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 Xj=new Intl.NumberFormat,Zj=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Ua(e){return Xj.format(e)}function At(e){return Zj.format(e)}function ek(e){return Zn(e)==="bypassed"}function tk(e){return e.every(t=>t.total===0)}function $l({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:c,methodology:l}){const[u,d]=h.useState(()=>new Set(n.map(f=>f.key))),m=h.useCallback(f=>{d(p=>{const y=new Set(p);return y.has(f)?y.delete(f):y.add(f),y})},[]);return o.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[o.jsxs("header",{className:"traffic__metric-story",children:[o.jsx("p",{className:"traffic__metric-eyebrow",children:e}),o.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),o.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),o.jsx(av,{series:n,visible:u,onToggle:m,formatValue:Ua,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),tk(n)?o.jsx("p",{className:"traffic__empty",children:i}):o.jsxs("div",{className:"traffic__metric-evidence",children:[o.jsxs("div",{className:"traffic__metric-evidence-header",children:[o.jsx("h4",{children:a}),o.jsxs("span",{children:[At(s.start),"–",At(s.end)]})]}),o.jsx(lv,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:Ua,formatTime:At,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:At(s.start)}),o.jsx("span",{children:At(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:c}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:l})]})]})]})}function nk({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=Lg({events:n,window:t,isAdmin:ek}),s=h.useMemo(()=>Yj(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx($l,{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:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts successful Firestore sandbox ",o.jsx("code",{children:"get"}),"/",o.jsx("code",{children:"list"}),","," ",o.jsx("code",{children:"create"}),"/",o.jsx("code",{children:"update"}),"/",o.jsx("code",{children:"set"}),", and"," ",o.jsx("code",{children:"delete"}),"/",o.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",o.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 rk({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=Fg({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>Qj(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx($l,{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:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",o.jsx("code",{children:"evaluated"}),", grouped by its ",o.jsx("code",{children:"allow"})," or ",o.jsx("code",{children:"deny"})," ","verdict."]}),o.jsxs("p",{children:[o.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."]})]})})})}const sk=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function ik(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function ak(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 ok(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:ak(n.length,r)}}function ck(e,t){return e?.start===t.start&&e.end===t.end?null:t}function lk(){const{tab:e,query:t}=we();return e!=="traffic"?"timeline":ik(t.view)}function uk(){const e=h.useSyncExternalStore(Kt,lk,()=>"timeline"),t=h.useCallback(n=>{const r={...we().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,de({tab:"traffic",query:r})},[]);return[e,t]}function dk(){const e=h.useSyncExternalStore(Kt,()=>we().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...we().query};n.hide==="studio"?delete n.hide:n.hide="studio",de({tab:"traffic",query:n})},[]);return[e,t]}function fk(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 Ba(e){return`${Lt(e.start)}–${Lt(e.end)}`}function hk({event:e}){const t=Zn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function pk(){return h.useSyncExternalStore(Kt,()=>El(we().query),()=>null)}const _r=100;function mk(){const e=Hb(),[t,n]=uk(),[r,s]=dk(),i=h.useMemo(()=>Rj(e,r),[e,r]),a=e.length-i.length,[c,l]=h.useState("all"),[u,d]=h.useState(null),m=pk(),[f,p]=h.useState(_r),y=E=>{de({tab:"traffic",query:Dj(we().query,E)})},b=()=>{de({tab:"traffic",query:Cl(we().query,null)})};h.useEffect(()=>{if(!m)return;const E=D=>{D.key==="Escape"&&b()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[m]);const v=h.useMemo(()=>{const E=Date.now();if(i.length===0)return{start:E-15*6e4,end:E};let D=1/0;for(const V of i)V.at<D&&(D=V.at);return{start:Math.min(D,E-6e4),end:E+1e3}},[i]),g=v.end,w=h.useMemo(()=>u?ok(i,u):null,[i,u]),x=w?.events??i,k=h.useMemo(()=>Ij(x,c).sort((E,D)=>D.at-E.at),[x,c]),{items:j}=Eg({events:k}),_=j.slice(0,f),N=j.length-_.length,A=i.length>=Sn,R=i.filter(E=>E.result==="deny").length,I=E=>o.jsx(hk,{event:E}),C=E=>{if(kr(E)){y(E.id);return}const D=$a(E);D&&de(D)},S=m!=null&&_.some(E=>E.type!=="group"&&E.event.id===m);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[sk.map(E=>o.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===E.id,onClick:()=>n(E.id),children:E.label},E.id)),o.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":r,onClick:s,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",r&&a>0?` (${a} hidden)`:""]})]}),t==="billable"?o.jsx(nk,{events:i,window:v}):t==="rules"?o.jsx(rk,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(rv,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(D=>ck(D,E)),m&&b()},liveAt:v.end,bucketCount:36,className:"traffic__timeline",header:o.jsxs("div",{className:"traffic__tl-header",children:[o.jsxs("span",{className:"traffic__tl-count",children:[i.length," requests",A?` (showing latest ${Sn})`:""]}),R>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":c==="deny",onClick:()=>l(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[R," denied"]}):null,o.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>o.jsxs("div",{className:"traffic__tl-axis",children:[o.jsx("span",{children:fk(E.start,g)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:Ba(E)}),o.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),o.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:o.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),w?o.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[o.jsxs("div",{className:"traffic__time-focus-story",children:[o.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),o.jsx("h3",{children:Ba(w.window)}),o.jsx("p",{children:w.finding})]}),o.jsx("button",{type:"button",onClick:()=>d(null),children:"Show all traffic"})]}):null,o.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[o.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),Aj.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":c===E,onClick:()=>l(E),children:E},E))]}),m&&!S?o.jsx(Oa,{eventId:m,onClose:b},m):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?c==="all"?"No requests occurred in the selected interval.":`No ${c} traffic occurred in the selected interval.`:c==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${c} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:_.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx(tv,{group:E,onSelect:D=>{const V=D;if(kr(V)){y(V.id);return}const G=$a(V);G&&de(G)},renderClassification:D=>I(D),formatTime:Lt})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Zn(E.event)??void 0,children:[o.jsx(Dc,{event:E.event,selected:E.event.id===m,onSelect:D=>C(D),renderClassification:D=>I(D),formatTime:Lt}),E.event.id===m&&kr(E.event)?o.jsx(Oa,{eventId:m,onClose:b},m):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>p(E=>E+_r),children:["Show ",Math.min(N,_r)," more (",N," hidden)"]}):null]})]})]})}const La=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],Fa=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function Ws(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`${La[t%La.length]}-${Fa[(t>>>4)%Fa.length]}`}function yk(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 bk(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function gk(e){const{provenance:t,identity:n}=yk(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:bk(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 vk(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=gk(e[r]);s&&n.push(s)}return n}const wk=20;function xk(e){de(e)}function yt({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:mt(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),xk(e))},children:n})}function jk(){const e=Ue(),t=Hn(),n=$s();if(t.status==="loading"||e.status==="pending")return o.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(o.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(o.jsxs(yt,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(o.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(o.jsxs(yt,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),Ws(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function kk(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function _k(){const e=Ht(),t=h.useMemo(()=>vk(e,wk),[e]);return o.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[o.jsxs("header",{className:"studio-home__feed-head",children:[o.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),o.jsx(yt,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?o.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):o.jsx("div",{className:"studio-home__feed-scroll",children:o.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[o.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),o.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),o.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:kk(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(yt,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const Sk=["firestore","auth","rtdb","storage","traffic"];function Ek(){const e=Be(),t=Ht(),n=h.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 o.jsx("div",{className:"studio-home__tiles",children:Sk.map(r=>{const s=et.find(i=>i.id===r);return s?o.jsxs(yt,{className:"studio-card studio-home__tile",target:{tab:r},children:[o.jsxs("span",{className:"studio-home__tile-top",children:[o.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?o.jsx("span",{className:"studio-badge",children:n[r]}):null]}),o.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function Ck(){const e=Hn(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),o.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."}),o.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),o.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),o.jsx(yt,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?o.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."]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),o.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function Nk(){const e=Be(),t=Ht(),n=Ue(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return o.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[o.jsxs("div",{className:"studio-home__hero",children:[o.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),o.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),o.jsx(Ac,{exposeFocus:$y}),o.jsx(jk,{}),o.jsx("div",{className:"studio-home__body",children:r?o.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"})]}):s?o.jsx(Ck,{}):o.jsxs(o.Fragment,{children:[o.jsx(_k,{}),o.jsx(Ek,{})]})})]})}function re(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function tt(e){return re(e).split("/").filter(Boolean)}function fs(e,t){return re([...tt(e),...t.split("/").filter(Boolean)].join("/"))}function Ol(e,t){const n=tt(e),r=tt(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 Tl(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 a=Tl(i);if(a===null){n=!0;continue}a!==i&&(n=!0),r[s]=a}return Object.keys(r).length===0?null:n?r:e}function Rk(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 zs(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Ml(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Ul(e,t){let n=e??null;for(const r of tt(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function Ak(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function hs(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((a,c)=>hs(a,t[c]));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(a=>a in r&&hs(n[a],r[a]))}function Ik(e,t){const n=new Map,r=(s,i)=>{if(!zs(s)){n.set(i,["leaf",s??null]);return}const a=Ml(s);n.set(i,["parent",a.map(([c])=>c)]);for(const[c,l]of a)r(l,fs(i,c))};return r(e,re(t)),n}function Dk(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(/[?#].*$/,""),re(t)}function Pk(e){const t=tt(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const $k=["string","number","boolean","json"];function Va(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function Ok(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function Tk(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function Mk(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 Bl(e){return{path:re(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Ll(e,t){const n=Ol(e.path,t);return n===null?null:Ul(e.value,n)}function Uk(e,t){const n=re(t);return n===e.path||e.expanded[n]===!0}function Bk(e,t,n){const r=Ml(Ll(e,t)),s=Math.min(r.length,e.pages[re(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function qa(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=Ol(t.path,s);a!==null&&zs(Ul(t.value,a))?n[s]=i:r=!0}return r?n:e}function Fl(e,t){switch(t.type){case"navigate":{const n=re(t.path);return n===e.path?e:Bl(n)}case"value":{if(re(t.path)!==e.path)return e;const n={...e,status:"live",value:Tl(t.value),error:null};return n.expanded=qa(e.expanded,n),n.pages=qa(e.pages,n),n}case"error":return re(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=re(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=re(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=re(t.path);return Fl(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=re(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const Lk=50;function Fk(e,t,n={}){const r=n.pageSize??Lk,s=re(t),[i,a]=h.useReducer(Fl,s,Bl),c=h.useMemo(()=>Ik(i.value,i.path),[i.path,i.value]),l=qs({scope:i.path,entries:c,equals:hs,ready:i.status==="live"});i.path!==s&&a({type:"navigate",path:s}),h.useEffect(()=>{let b=!1;const v=e.subscribeValue(s,g=>{b||a({type:"value",path:s,value:g})},g=>{b||a({type:"error",path:s,message:g instanceof Error?g.message:String(g)})});return()=>{b=!0,v()}},[e,s]);const u=h.useCallback(b=>Ll(i,b),[i]),d=h.useCallback(b=>Uk(i,b),[i]),m=h.useCallback(b=>Bk(i,b,r),[i,r]),f=h.useCallback(b=>a({type:"toggle",path:b}),[]),p=h.useCallback(b=>a({type:"show-more",path:b,pageSize:r}),[r]),y=h.useCallback(b=>l.get(re(b)),[l]);return h.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:m,toggle:f,showMore:p,updateAt:y}),[i,r,u,d,m,f,p,y])}function Vk({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=re(e),[a,c]=h.useState(!1),l=h.useRef(null);h.useEffect(()=>{a&&l.current?.select()},[a]);const u=f=>{f.preventDefault(),t(Dk(l.current?.value??"")),c(!1)},d=()=>c(!1),m=Pk(i);return o.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":a?"":void 0,"aria-label":"Database path",children:a?o.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?o.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,o.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})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[o.jsx("li",{"data-rtdb-crumb-item":!0,children:o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":m.length===0?"":void 0,"aria-current":m.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),m.map((f,p)=>{const y=p===m.length-1;return o.jsxs("li",{"data-rtdb-crumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":y?"":void 0,"aria-current":y?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),o.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>c(!0),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:o.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 qk({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=tt(i.path),c=a.length===0?r:a[a.length-1];return o.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?o.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):o.jsx(Vl,{tree:e,api:t,onNavigate:n,path:i.path,label:c,isViewRoot:!0})})}function Vl({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),c=zs(a),l=e.isExpanded(r),u=e.updateAt(r),[d,m]=h.useState(!1),[f,p]=h.useState(!1),[y,b]=h.useState(!1),[v,g]=h.useState(null),w=async(j,_)=>{try{await j(),g(null),_()}catch(N){g(N instanceof Error?N.message:String(N))}},x=()=>{m(!0),b(!1),c&&!l&&e.toggle(r)},k=c&&l?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":c?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":c&&l?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[c&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:o.jsx("path",{d:"M1 0l6 4-6 4z"})})}):o.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),o.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),c?null:o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),o.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":Ak(a),title:"Edit value",onClick:()=>{p(!0),b(!1)},children:Rk(a)})]}),o.jsx("span",{"data-rtdb-actions":!0,children:y?o.jsxs("span",{"data-rtdb-confirm":!0,children:[o.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",c?" subtree":"","?"]}),o.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void w(()=>t.remove(r),()=>b(!1)),children:"Delete"}),o.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>b(!1),children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${Wa(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Wa(r)}`,title:"Delete",onClick:()=>b(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(za,{initialType:Va(a),initialText:Ok(a,Va(a)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:j=>w(()=>t.set(r,j),()=>p(!1))}):null,d?o.jsx(za,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>m(!1),onSubmit:(j,_)=>w(()=>t.set(fs(r,_),j),()=>m(!1))}):null,k?o.jsxs("ul",{"data-rtdb-children":!0,children:[k.entries.map(([j])=>o.jsx("li",{children:o.jsx(Vl,{tree:e,api:t,onNavigate:n,path:fs(r,j),label:j})},j)),k.hiddenCount>0?o.jsx("li",{"data-rtdb-show-more-item":!0,children:o.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",k.hiddenCount," hidden)"]})}):null]}):null]})}function Wa(e){const t=tt(e);return t.length===0?"root":t[t.length-1]}function za({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),c=h.useRef(null),[l,u]=h.useState(t),[d,m]=h.useState(null),f=y=>{y.preventDefault();const b=a.current?.value??"";if(e){const g=Tk(b);if(g){m(g);return}}const v=Mk(l,c.current?.value??"");if(!v.ok){m(v.error);return}m(null),s(v.value,e?b.trim():void 0)},p=y=>{y.key==="Escape"&&i()};return o.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?o.jsx("input",{ref:a,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,o.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:y=>u(y.currentTarget.value),onKeyDown:p,children:$k.map(y=>o.jsx("option",{value:y,children:y},y))}),l==="boolean"?o.jsxs("select",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]}):o.jsx("input",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),o.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),o.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?o.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}function Wk(){const e=be(),t=e.status==="ready"?e.env.live:void 0;return o.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),o.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),o.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?o.jsx(Kk,{live:t}):o.jsx(zk,{})]})}function zk(){return o.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[o.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),o.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 Kk({live:e}){const[t,n]=h.useState("/"),r=Ws($s()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(c,l)=>e.setRtdbValue(c,l),remove:c=>e.deleteRtdbValue(c),subscribeValue:(c,l,u)=>e.subscribeRtdbValue(c,l,u)}),[e]),a=Fk(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(Vk,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(qk,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function Hk(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 sn(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Gk(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(sn(e.collections,"collection")),e.users&&t.push(sn(e.users,"user")),e.objects&&t.push(sn(e.objects,"file")),e.rtdbKeys&&t.push(sn(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function er(){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 Jk(){return o.jsxs("svg",{...er(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function Yk(){return o.jsxs("svg",{...er(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function Qk(){return o.jsxs("svg",{...er(),children:[o.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),o.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),o.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),o.jsx("path",{d:"M7 8.4v7.2"}),o.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function Xk(){return o.jsxs("svg",{...er(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function an({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return o.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[o.jsxs("span",{className:"studio-sandbox__action-top",children:[e,o.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),o.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function Zk(){const e=Xb(),t=Zb(),n=eg(),r=tg(),s=Hn(),i=h.useRef(null),a=Ws($s()),[c,l]=h.useState(!1),[u,d]=h.useState(!1),[m,f]=h.useState(!1),[p,y]=h.useState(!1),[b,v]=h.useState(""),g=Rc(),{ensure:w}=g;h.useEffect(()=>w(),[w]);const x=Hk(g.entries),k=Gk(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",_=async()=>{const S=await t();if(!S||typeof document>"u")return;const E=URL.createObjectURL(new Blob([S],{type:"application/json"})),D=document.createElement("a");D.href=E,D.download=`pyric-sandbox-${a||"export"}.json`,D.click(),URL.revokeObjectURL(E)},N=async S=>{const E=S.target.files?.[0];if(S.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},A=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},R=async()=>{const S=b.trim();S&&(await r.save(S),v(""),y(!1))},I=async S=>{typeof window<"u"&&!window.confirm(`Switch to branch "${S}"? This replaces the current sandbox state.`)||await r.switchTo(S)},C=async S=>{typeof window<"u"&&!window.confirm(`Delete branch "${S}"?`)||await r.remove(S)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:k}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(an,{glyph:o.jsx(Jk,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void _()}),o.jsx(an,{glyph:o.jsx(Yk,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(an,{glyph:o.jsx(Qk,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(S=>!S)}),o.jsx(an,{glyph:o.jsx(Xk,{}),name:c?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:c,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),p?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:S=>{S.preventDefault(),R()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:b,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:S=>v(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!b.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,m?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&k!=="empty — no data yet"?`This erases ${k}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void A(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(S=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:S}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void I(S),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(S),children:"Delete"})]})]},S))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function on(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 e_(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(a=>JSON.stringify(n[a])!==JSON.stringify(r[a]));if(i.length>0&&i.length<=3)return i.map(a=>`${a}: ${on(n[a])} -> ${on(r[a])}`).join(", ")}return`${on(t.before)} -> ${on(t.after)}`}function t_(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:e_(t),supported:t.qualification.supported}))}function n_(e){const t=e.mutation.events.find(a=>a.result==="allow"||a.result==="deny"||a.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.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 r_="pyric:assurance-campaign",s_="pyric-assurance-v1",ps=new Set;let Ka=!1,Ha;function Ga(e){for(const t of ps)t(e)}function Ja(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function i_(){if(!(Ka||typeof document>"u")){Ka=!0,globalThis.addEventListener(r_,e=>{const t=e.detail;Ja(t)&&Ga(t)});try{Ha=new BroadcastChannel(s_),Ha.onmessage=e=>{Ja(e.data)&&Ga(e.data)}}catch{}}}function a_(e){return i_(),ps.add(e),()=>ps.delete(e)}function Sr(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 o_=[Sr({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"}}),Sr({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"}),Sr({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"}}})],C_=o_.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const ms="pyric:assurance:campaigns",ql="pyric:assurance:campaign:";function c_(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function l_(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(ms)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${ql}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(c_);return t.length,t}catch{return[]}}function u_(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(ms)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(ms,JSON.stringify(n)),sessionStorage.setItem(`${ql}${e.campaignId}`,JSON.stringify(e))}catch{}}function d_(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 f_(){const[e,t]=h.useState(l_);return h.useEffect(()=>{const r=a_(s=>{u_(s),t(i=>d_(i,s))});return()=>{r()}},[]),e}function h_(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function p_(e){return e.replaceAll("-"," ")}function Ya({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function m_(){return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),o.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function Qa({attachment:e}){return e?o.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[o.jsxs("span",{children:[o.jsx("strong",{children:e.source.origin}),"read-only clone"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function y_({campaigns:e}){const t=f_(),n=e??t,r=we().query,[s,i]=h.useState(r.campaign??n.find(x=>x.report)?.campaignId??n[0]?.campaignId??""),a=n.find(x=>x.campaignId===s)??n[0],c=h.useMemo(()=>a?.report?t_(a.report):[],[a]),[l,u]=h.useState(r.probe??c[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{c.some(x=>x.id===l)||u(c[0]?.id??"")},[c,l]),!a)return o.jsx(m_,{});const d=a.context?.attachment,m=a.report;if(!m)return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:a.campaignId}),o.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),o.jsxs("p",{children:[a.observations.length," known-good operation(s) and"," ",a.probes.length," probe(s) are available."]}),o.jsx(Qa,{attachment:d}),d?.coverageGaps.length?o.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.service}),x.reason]},x.code))}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=c.find(x=>x.id===l)??c[0],p=m.results.find(x=>x.probeId===f?.id),y=p?n_(p):null,b=a.verifications?.at(-1),v=b!==void 0&&b.summary.controlsPassed===b.summary.probes&&b.summary.noCounterexamples===b.summary.probes&&b.summary.localCounterexamples===0&&b.summary.engineGaps===0&&b.summary.invalidProbes===0;function g(x){i(x);const j=n.find(_=>_.campaignId===x)?.report?.results[0]?.probeId??"";u(j),kn({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),kn({tab:"assurance",query:{campaign:a.campaignId,probe:x.id}})}return o.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[o.jsxs("header",{className:"assurance-surface__header",children:[o.jsxs("div",{children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-title",children:a.campaignId})]}),o.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?o.jsxs("label",{children:[o.jsx("span",{children:"Campaign"}),o.jsx("select",{value:a.campaignId,onChange:x=>g(x.target.value),children:n.map(x=>o.jsx("option",{value:x.campaignId,children:x.campaignId},x.campaignId))})]}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),o.jsx(Qa,{attachment:d}),o.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Controls"}),o.jsxs("strong",{children:[m.summary.controlsPassed,"/",m.summary.probes]})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Counterexamples"}),o.jsx("strong",{children:m.summary.localCounterexamples})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Candidate signals"}),o.jsx("strong",{children:m.summary.candidateSignals})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Engine gaps"}),o.jsx("strong",{children:m.summary.engineGaps})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Coverage gaps"}),o.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),b?o.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${v?"passed":"failed"}`,role:"status",children:[o.jsx("strong",{children:v?"Candidate rules verified":"Candidate rules need review"}),o.jsxs("span",{children:[b.summary.controlsPassed,"/",b.summary.probes," ","controls preserved"," | ",b.summary.noCounterexamples,"/",b.summary.probes," negative cases denied"]}),o.jsx("code",{children:b.campaignId})]}):null,d?.coverageGaps.length?o.jsxs("div",{className:"assurance-coverage-band",children:[o.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),o.jsx("span",{children:d.coverageGaps.map(x=>`${x.service}: ${x.reason}`).join(" ")})]}):null,o.jsxs("div",{className:"assurance-workspace",children:[o.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),o.jsx("span",{children:m.targetHash})]}),o.jsxs("div",{className:"assurance-table",role:"table",children:[o.jsxs("div",{className:"assurance-table__header",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Operation"}),o.jsx("span",{role:"columnheader",children:"Actor"}),o.jsx("span",{role:"columnheader",children:"Expected"}),o.jsx("span",{role:"columnheader",children:"Observed"}),o.jsx("span",{role:"columnheader",children:"Impact"})]}),c.map(x=>o.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":x.id===f?.id,onClick:()=>w(x),role:"row",children:[o.jsxs("span",{role:"cell",children:[o.jsx("small",{children:x.service}),x.operation]}),o.jsx("span",{role:"cell",children:x.actor}),o.jsx("span",{role:"cell",className:`assurance-verdict ${x.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:x.expected}),o.jsx("span",{role:"cell",className:`assurance-verdict ${h_(x.expected,x.observed)}`,children:x.observed}),o.jsx("span",{role:"cell",children:x.impact})]},x.id))]})]}),p?o.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:p_(p.classification)}),o.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),o.jsx("span",{children:p.actorEvidence.reachability})]}),o.jsxs("dl",{className:"assurance-facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Invariant"}),o.jsx("dd",{children:p.invariant.statement})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Mutation"}),o.jsx("dd",{children:p.mutationSpec.description})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Actor"}),o.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Fidelity"}),o.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(x=>!x.supported)?o.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(x=>!x.supported).map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.id}),x.reason]},x.id))}):null,p.stateDiff?o.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[o.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),o.jsxs("div",{className:"assurance-evidence__diff",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Before"}),o.jsx(Ya,{value:p.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(Ya,{value:p.stateDiff.after})]})]})]}):null,y?o.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[o.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),o.jsx(Rl,{denial:y})]}):o.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function Xa(){return Wn()}function Wl(){return`${Wn()}docs`}function Za(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function b_(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${Wl()}/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 g_({id:e}){const t=Ry(e),n=Ue(),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"),o.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[o.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),o.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),o.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),o.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>o.jsx("span",{children:s},s))})]})}function v_({id:e}){switch(e){case"home":return o.jsx(Nk,{});case"firestore":return o.jsx(mj,{});case"auth":return o.jsx(jj,{});case"storage":return o.jsx(yj,{});case"rtdb":return o.jsx(Wk,{});case"traffic":return o.jsx(mk,{});case"assurance":return o.jsx(y_,{});case"settings":return o.jsx(Zk,{});default:return o.jsx(g_,{id:e})}}function w_(){const[e,t]=Py(Ny,"home"),n=l=>t(l),[r,s]=h.useState(!1),i=b_(),a=e==="home";h.useEffect(()=>{const l=u=>{if(Ty(u)){if(r){u.preventDefault(),s(!1);return}if(a){Oy()&&u.preventDefault();return}u.preventDefault(),s(!0)}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const c=et.filter(l=>l.id!=="home");return o.jsxs("div",{className:"studio","data-surface":e,children:[o.jsxs("header",{className:"studio__chrome",children:[o.jsx("div",{className:"studio__bar",children:o.jsxs("div",{className:"studio__chrome-inner",children:[o.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[o.jsx("a",{className:"studio__brand",href:Xa(),"aria-label":"Pyric",children:"pyric"}),o.jsx("a",{className:"studio__nav-tab",href:Xa(),children:"Home"}),i?o.jsx("a",{className:"studio__nav-tab",href:Wl(),children:"Docs"}):null,o.jsx("a",{className:"studio__nav-tab",href:mt({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:Za(()=>n("home")),children:"Studio"})]}),o.jsx(_g,{})]})}),o.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:o.jsx("div",{className:"studio__chrome-inner",children:o.jsx("div",{className:"studio__nav",children:c.map(l=>o.jsx("a",{className:"studio__nav-tab",href:mt({tab:l.id}),"aria-current":l.id===e?"page":void 0,onClick:Za(()=>n(l.id)),children:l.label},l.id))})})})]}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx(v_,{id:e})})}),r?o.jsx(lg,{onClose:()=>s(!1)}):null]})}function x_(){return o.jsx(ky,{children:o.jsx(Sf,{children:o.jsx(gy,{mode:"local",children:o.jsx(w_,{})})})})}function N_(){return o.jsx(h.StrictMode,{children:o.jsx(x_,{})})}export{N_ as S,E_ as a,lb as b,Ut as r,me as s,tc as u};