@pyric/cli 0.1.0-alpha.27 → 0.1.0-alpha.29
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.
- package/dist/assurance/.generated/conformance-verdicts.d.ts +16 -0
- package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
- package/dist/assurance/.generated/conformance-verdicts.js +16 -0
- package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
- package/dist/bridge/surface/arguments/assurance.d.ts +6 -6
- package/dist/bridge/surface/arguments/messaging.d.ts +2 -2
- package/dist/bridge/surface/methods/assurance/map.d.ts +6 -6
- package/dist/bridge/surface/methods/assurance/replaySession.d.ts.map +1 -1
- package/dist/bridge/surface/methods/assurance/replaySession.js +18 -6
- package/dist/bridge/surface/methods/assurance/replaySession.js.map +1 -1
- package/dist/bridge/surface/methods/messaging/send.d.ts +4 -4
- package/dist/bridge/surface/render/discriminator-schemas.d.ts +4 -4
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +15 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/run.d.ts +42 -0
- package/dist/cli/run.d.ts.map +1 -0
- package/dist/cli/run.js +115 -0
- package/dist/cli/run.js.map +1 -0
- package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use.js +1 -1
- package/dist/conformance/.generated/can-i-use.js.map +1 -1
- package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
- package/dist/conformance/.generated/conformance-docs.js +1 -1
- package/dist/conformance/.generated/conformance-docs.js.map +1 -1
- package/dist/remote/local-storage-url.d.ts +2 -15
- package/dist/remote/local-storage-url.d.ts.map +1 -1
- package/dist/remote/local-storage-url.js +1 -60
- package/dist/remote/local-storage-url.js.map +1 -1
- package/dist/serve/assets/avatar-route.d.ts.map +1 -1
- package/dist/serve/assets/avatar-route.js +6 -6
- package/dist/serve/assets/avatar-route.js.map +1 -1
- package/dist/serve/assets/resolver.d.ts +3 -0
- package/dist/serve/assets/resolver.d.ts.map +1 -1
- package/dist/serve/assets/resolver.js +1 -1
- package/dist/serve/assets/resolver.js.map +1 -1
- package/dist/serve/entries/app-client.d.ts.map +1 -1
- package/dist/serve/entries/app-client.js +6 -0
- package/dist/serve/entries/app-client.js.map +1 -1
- package/dist/serve/site-ui/_astro/{RulesCodeEditor.kBYcclwV.js → RulesCodeEditor.Cp_-FK3b.js} +1 -1
- package/dist/serve/site-ui/_astro/app.C--T2qDK.js +151 -0
- package/dist/serve/site-ui/_astro/app.DqyhRyrU.js +1 -0
- package/dist/serve/site-ui/_astro/{chess-showcase.CZe_3fJZ.js → chess-showcase.CVhCNUi_.js} +1 -1
- package/dist/serve/site-ui/_astro/{example-runtime.CXSZXHZF.js → example-runtime.zC1l-Yka.js} +1 -1
- package/dist/serve/site-ui/_astro/{sandbox-controls.Bp5PoonS.js → sandbox-controls.Bv6lfpIe.js} +39 -39
- package/dist/serve/site-ui/_astro/{seed.BpXSRzLo.js → seed.B4vza_Bv.js} +1 -1
- package/dist/serve/site-ui/_astro/{writes.DHSW22XD.js → writes.Bg0YEEA7.js} +1 -1
- package/dist/serve/site-ui/auth/index.html +1 -1
- package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
- package/dist/serve/site-ui/docs/ai-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/api-reference/index.html +2 -1
- package/dist/serve/site-ui/docs/api-reference.md +1 -0
- package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-compat/index.html +2 -2
- package/dist/serve/site-ui/docs/auth-compat.md +1 -1
- package/dist/serve/site-ui/docs/auth-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +1 -1
- package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/index.html +13 -2
- package/dist/serve/site-ui/docs/build/cloud-storage.md +23 -0
- package/dist/serve/site-ui/docs/build/default-avatars/index.html +1 -1
- package/dist/serve/site-ui/docs/build/inspect-activity/index.html +1 -1
- package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
- package/dist/serve/site-ui/docs/conformance-scores/index.html +1 -1
- package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/database-compat/index.html +18 -18
- package/dist/serve/site-ui/docs/database-compat.md +17 -17
- package/dist/serve/site-ui/docs/examples/chess/index.html +1 -1
- package/dist/serve/site-ui/docs/examples/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/backend-bundlers/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/flutter/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/nextjs/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/node-host/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/start-building/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/vite/index.html +4 -2
- package/dist/serve/site-ui/docs/get-started/vite.md +4 -0
- package/dist/serve/site-ui/docs/index.json +60 -10
- package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/switch-and-impersonate-identities/index.html +1 -1
- package/dist/serve/site-ui/docs/overview/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-app-check-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-data-connect-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-eventarc-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-extensions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-functions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-installations-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-instance-id-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-machine-learning-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-phone-number-verification-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-project-management-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-remote-config-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-security-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-analytics-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-app-check-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-auth-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bundler-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-flow-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-app-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-repro-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +17 -3
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api.md +7 -5
- package/dist/serve/site-ui/docs/pyric-cli-vite-ssr-loader-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-lite-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-functions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-performance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-remote-config-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +120 -120
- package/dist/serve/site-ui/docs/pyric-rules-reference-api.md +53 -53
- package/dist/serve/site-ui/docs/pyric-sandbox-branches-store-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-checkpoints-directory-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-checkpoints-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-storage-sw-reference-api/index.html +102 -0
- package/dist/serve/site-ui/docs/pyric-storage-sw-reference-api.md +76 -0
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-listener-owner-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/reference/cli/index.html +12 -2
- package/dist/serve/site-ui/docs/reference/cli.md +24 -0
- package/dist/serve/site-ui/docs/rtdb-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rtdb-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rtdb-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rules-compat/index.html +68 -4
- package/dist/serve/site-ui/docs/rules-compat.md +67 -3
- package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-standard-library/index.html +18 -5
- package/dist/serve/site-ui/docs/secure/rtdb-rules-standard-library.md +19 -4
- package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +5 -5
- package/dist/serve/site-ui/docs/secure/simulate-and-lint.md +8 -8
- package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
- package/dist/serve/site-ui/docs/storage-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
- package/dist/serve/site-ui/docs/tutorial/index.html +1 -1
- package/dist/serve/site-ui/examples/chess/index.html +1 -1
- package/dist/serve/site-ui/firestore/index.html +1 -1
- package/dist/serve/site-ui/llms.txt +1 -0
- package/dist/serve/site-ui/rtdb/index.html +1 -1
- package/dist/serve/site-ui/settings/index.html +1 -1
- package/dist/serve/site-ui/storage/index.html +1 -1
- package/dist/serve/site-ui/studio/index.html +1 -1
- package/dist/serve/site-ui/traffic/index.html +1 -1
- package/dist/serve/vite-plugin.d.ts +6 -0
- package/dist/serve/vite-plugin.d.ts.map +1 -1
- package/dist/serve/vite-plugin.js +11 -1
- package/dist/serve/vite-plugin.js.map +1 -1
- package/dist/serve/vite-service-worker.d.ts +12 -0
- package/dist/serve/vite-service-worker.d.ts.map +1 -0
- package/dist/serve/vite-service-worker.js +33 -0
- package/dist/serve/vite-service-worker.js.map +1 -0
- package/dist/serve/worker/client/auth.d.ts.map +1 -1
- package/dist/serve/worker/client/auth.js +4 -3
- package/dist/serve/worker/client/auth.js.map +1 -1
- package/dist/serve/worker/client/rtdb-info.d.ts +0 -2
- package/dist/serve/worker/client/rtdb-info.d.ts.map +1 -1
- package/dist/serve/worker/client/rtdb-info.js +4 -17
- package/dist/serve/worker/client/rtdb-info.js.map +1 -1
- package/dist/serve/worker/client/rtdb-reads.d.ts.map +1 -1
- package/dist/serve/worker/client/rtdb-reads.js +3 -5
- package/dist/serve/worker/client/rtdb-reads.js.map +1 -1
- package/dist/serve/worker/host/auth-action-codes.js +2 -2
- package/dist/serve/worker/host/auth-action-codes.js.map +1 -1
- package/dist/serve/worker/host/auth-custom-token.d.ts.map +1 -1
- package/dist/serve/worker/host/auth-custom-token.js +4 -2
- package/dist/serve/worker/host/auth-custom-token.js.map +1 -1
- package/dist/serve/worker/host/dispatch.d.ts.map +1 -1
- package/dist/serve/worker/host/dispatch.js +3 -1
- package/dist/serve/worker/host/dispatch.js.map +1 -1
- package/dist/serve/worker/host-auth.d.ts +6 -0
- package/dist/serve/worker/host-auth.d.ts.map +1 -1
- package/dist/serve/worker/host-auth.js +16 -5
- package/dist/serve/worker/host-auth.js.map +1 -1
- package/dist/serve/worker/inbound-validation.d.ts.map +1 -1
- package/dist/serve/worker/inbound-validation.js +1 -0
- package/dist/serve/worker/inbound-validation.js.map +1 -1
- package/dist/serve/worker/protocol/storage.d.ts +1 -8
- package/dist/serve/worker/protocol/storage.d.ts.map +1 -1
- package/dist/serve/worker/protocol/storage.js +2 -14
- package/dist/serve/worker/protocol/storage.js.map +1 -1
- package/dist/serve/worker/protocol.d.ts +2 -0
- package/dist/serve/worker/protocol.d.ts.map +1 -1
- package/dist/serve/worker/protocol.js.map +1 -1
- package/package.json +12 -8
- package/src/assurance/.generated/conformance-verdicts.ts +16 -0
- package/src/bridge/surface/methods/assurance/replaySession.ts +19 -6
- package/src/cli/index.ts +15 -1
- package/src/cli/run.ts +139 -0
- package/src/conformance/.generated/can-i-use.ts +1 -1
- package/src/conformance/.generated/conformance-docs.ts +1 -1
- package/src/remote/local-storage-url.ts +1 -58
- package/src/serve/assets/avatar-route.ts +6 -7
- package/src/serve/assets/resolver.ts +4 -1
- package/src/serve/entries/app-client.ts +7 -0
- package/src/serve/vite-plugin.ts +15 -1
- package/src/serve/vite-service-worker.ts +44 -0
- package/src/serve/worker/client/auth.ts +4 -3
- package/src/serve/worker/client/rtdb-info.ts +4 -17
- package/src/serve/worker/client/rtdb-reads.ts +3 -4
- package/src/serve/worker/host/auth-action-codes.ts +2 -2
- package/src/serve/worker/host/auth-custom-token.ts +4 -2
- package/src/serve/worker/host/dispatch.ts +2 -0
- package/src/serve/worker/host-auth.ts +18 -5
- package/src/serve/worker/inbound-validation.ts +1 -0
- package/src/serve/worker/protocol/storage.ts +2 -14
- package/src/serve/worker/protocol.ts +2 -0
- package/dist/serve/site-ui/_astro/app.CiMHEvEW.js +0 -147
- package/dist/serve/site-ui/_astro/app.DpzsBfos.js +0 -1
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/RulesCodeEditor.Cp_-FK3b.js","_astro/sandbox-controls.Bv6lfpIe.js","_astro/index.DBy5LfQW.js","_astro/seed.B4vza_Bv.js","_astro/writes.Bg0YEEA7.js","_astro/index.DNyk7q8W.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as _h,d as ow,M as co,g as aw,e as cw,f as lw,o as vc,F as H,h as pt,m as qn,k as Te,l as Sh,n as uw,p as dw,q as On,t as Sn,u as kh,v as gs,w as je,x as Js,y as Fs,z as qs,A as Ys,B as Tt,C as Oi,S as Eh,D as Zr,E as jh,G as Qs,H as Ch,I as fw,J as hw,K as pw,L as mw,N as Ih,R as Me,O as $i,P as Rh,Q as Nh,T as yw,U as gw,V as na,W as ct,X as ra,Y as bw,Z as qt,_ as Rr,$ as ww,a0 as vw,a1 as xw,a2 as es,a3 as Ah,a4 as _w,a5 as De,a6 as Oh,a7 as Sw,a8 as kw,a9 as Ew,aa as jw,ab as Cw,ac as $h,ad as Iw,ae as Rw,af as Nw,ag as Aw,ah as Ow,ai as bs,aj as Ol,ak as $w,al as Pw,am as Dw,an as $l,ao as Tw,ap as Mw,aq as Lw,ar as Uw,as as Bw,at as Ph,au as Fw,av as qw,aw as Vw,ax as Ww,ay as Dh,az as Th,aA as Tn,aB as ts,aC as zw,aD as Hw,i as Kw,j as c,aE as Gw,aF as Jw,aG as Yw,aH as Qw,aI as Xw,aJ as Zw,aK as Mh,aL as ev,aM as xc,aN as tv,aO as nv,aP as rv,aQ as sv,aR as un,aS as Nr,aT as iv,aU as Lh,aV as Uh,aW as Pl,aX as ov,aY as av,aZ as cv,a_ as lv,a$ as uv,b0 as dv,b1 as fv,b2 as hv,b3 as pv,b4 as mv,b5 as Bh,b6 as yv,b7 as on,b8 as Vt,b9 as Mn}from"./sandbox-controls.Bv6lfpIe.js";import{r as y}from"./index.DBy5LfQW.js";import{a as gv,r as bv,b as Ar,d as st,T as Xs,c as Ct,t as sn,e as ns,f as Fh,h as Dl,j as _c,k as qh,l as Sc,u as sa,m as wv,n as kc,o as Vn,w as Vh,p as vv,q as xv,v as _v,x as Sv,y as kv,B as Ev,C as jv,z as Cv,A as Iv,D as ia,E as Rv,F as Nv,G as Av,Q as Ov,H as br,s as Zs,I as Wh,J as Tl,K as oa,L as $v,M as Pv,N as Ec,O as jc,g as ei,i as Dv}from"./writes.Bg0YEEA7.js";import{r as Tv}from"./index.DNyk7q8W.js";function Mv(e,t){const n=e.toLowerCase();let r=null;for(const s of t){const i=Lv(n,s.toLowerCase());(r===null||i<r.d)&&(r={key:s,d:i})}return r&&r.d<=Math.max(2,Math.floor(n.length/3))?r.key:null}function Lv(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;const n=new Array(t.length+1).fill(0).map((s,i)=>i),r=new Array(t.length+1).fill(0);for(let s=0;s<e.length;s++){r[0]=s+1;for(let i=0;i<t.length;i++){const o=e[s]===t[i]?0:1;r[i+1]=Math.min(r[i]+1,n[i+1]+1,n[i]+o)}for(let i=0;i<=t.length;i++)n[i]=r[i]}return r[t.length]}const an={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Uv=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],Bv={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 Fv(e){return Uv.includes(e)}class be extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ft extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const qv={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},Vv={true:"true",false:"false",null:"null"};function Wv(e){if(e.length>an.maxExpressionLength)throw new be(`expression exceeds ${an.maxExpressionLength}-character cap (got ${e.length})`,J(an.maxExpressionLength));const t=[];let n=0;for(;n<e.length;){const r=n,s=e[n];if(s===" "||s===" "||s==="\r"||s===`
|
|
3
|
+
`){n+=1;continue}if(s==='"'||s==="'"){const{token:o,next:a}=Kv(e,n,s);if(t.push(o),n=a,n<=r)throw new be("lexer stalled on string",J(r));continue}if(s>="0"&&s<="9"){const{token:o,next:a}=Hv(e,n);if(t.push(o),n=a,n<=r)throw new be("lexer stalled on number",J(r));continue}if(Pi(s)){const{token:o,next:a}=zv(e,n);t.push(o),n=a;continue}if(s==="$"){const{token:o,next:a}=Ml(e,n,"$","reference");t.push(o),n=a;continue}if(s==="@"){const{token:o,next:a}=Ml(e,n,"@","sentinel");t.push(o),n=a;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:J(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:J(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:J(n)}),n+=2):(t.push({kind:"lt",pos:J(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:J(n)}),n+=2):(t.push({kind:"gt",pos:J(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new be("unexpected '&' (did you mean '&&'?)",J(n));t.push({kind:"and",pos:J(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new be("unexpected '|' (did you mean '||'?)",J(n));t.push({kind:"or",pos:J(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:J(n)}),n+=1;continue}if(s==="=")throw new be("unexpected '=' (did you mean '=='?)",J(n));const i=qv[s];if(i){t.push({kind:i,pos:J(n)}),n+=1;continue}throw new be(`unexpected character ${JSON.stringify(s)}`,J(n))}return t.push({kind:"eof",pos:J(e.length)}),t}function J(e){return{offset:e,column:e+1}}function Pi(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function zh(e){return Pi(e)||e>="0"&&e<="9"}function zv(e,t){let n=t+1;for(;n<e.length&&zh(e[n]);)n+=1;const r=e.slice(t,n),s=Vv[r];return s?{token:{kind:s,pos:J(t)},next:n}:{token:{kind:"identifier",pos:J(t),value:r},next:n}}function Ml(e,t,n,r){const s=t+1;if(s>=e.length||!Pi(e[s]))throw new be(`expected identifier after '${n}'`,J(t));let i=s+1;for(;i<e.length&&zh(e[i]);)i+=1;const o=e.slice(s,i);return{token:{kind:r,pos:J(t),value:o},next:i}}function Hv(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 be("leading zeros are not allowed in number literals",J(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const a=e[n+1];if(a!==void 0&&a>="0"&&a<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(a!==void 0&&Pi(a)))throw new be("expected digit after '.' in number literal",J(n))}const i=e.slice(t,n),o=Number.parseFloat(i);if(!Number.isFinite(o))throw new be(`numeric literal '${i}' is not finite`,J(t));if(!s&&!Number.isSafeInteger(o))throw new be(`integer literal '${i}' exceeds safe integer range`,J(t));return{token:{kind:"number",pos:J(t),value:o},next:n}}function Kv(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:J(t),value:s},next:r+1};if(i==="\\"){const o=e[r+1];if(o===void 0)throw new be("unterminated escape sequence in string literal",J(r));switch(o){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
|
|
4
|
+
`;break;case"t":s+=" ";break;default:throw new be(`invalid escape sequence '\\${o}' (only \\", \\', \\\\, \\n, \\t are allowed)`,J(r))}r+=2}else{if(i===`
|
|
5
|
+
`||i==="\r")throw new be("unterminated string literal (newline before closing quote)",J(t));s+=i,r+=1}if(s.length>an.maxStringLiteralLength)throw new be(`string literal exceeds ${an.maxStringLiteralLength}-character cap`,J(t))}throw new be("unterminated string literal",J(t))}function Gv(e){const t=new Jv(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),Xv(n),n}class Jv{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=Yv(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 ft(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ft("unexpected end of expression",t.pos);default:throw new ft("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!Fv(n))throw new ft(`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=Bv[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 ft(`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 ft(`${n} (got ${Qv(r)})`,r.pos);return this.consume()}}function Yv(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 Qv(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function Xv(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>an.maxAstDepth)throw new ft(`expression AST exceeds depth cap of ${an.maxAstDepth}`,n.pos);return s}}class qe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function rs(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 Xe(e,t){return new qe("type-mismatch",t,e.pos)}function We(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Zv(e,t);case"sentinel":return ex(e,t);case"unary":return tx(e,t);case"binary":return nx(e,t);case"logical":return sx(e,t);case"ternary":return ix(e,t);case"fieldAccess":return ox(e,t);case"indexAccess":return ax(e,t)}}function Zv(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new qe("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 ex(e,t){const n=e.args.map(r=>{const s=We(r,t);if(rs(s))throw new qe("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 Xe(e,`'@increment' expects a numeric argument, got ${Ne(r)}`);return ti(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function tx(e,t){const n=We(e.operand,t);if(aa(n,e),e.op==="-"){if(typeof n!="number")throw Xe(e,`unary '-' expects a number, got ${Ne(n)}`);const r=-n;return ti(r,e),r}if(typeof n!="boolean")throw Xe(e,`unary '!' expects a boolean, got ${Ne(n)}`);return!n}function nx(e,t){const n=We(e.left,t),r=We(e.right,t);switch(aa(n,e),aa(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return ti(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Xe(e,`'+' expects (number, number) or (string, string); got (${Ne(n)}, ${Ne(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Xe(e,`'${e.op}' expects (number, number); got (${Ne(n)}, ${Ne(r)})`);let s;switch(e.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return ti(s,e),s}case"==":return Ll(e,n,r);case"!=":return!Ll(e,n,r);case"<":case"<=":case">":case">=":return rx(e,n,r)}}function Ll(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 Xe(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function rx(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw Xe(e,`'${e.op}' expects matching number/number or string/string operands; got (${Ne(t)}, ${Ne(n)})`);switch(e.op){case"<":return t<n;case"<=":return t<=n;case">":return t>n;case">=":return t>=n;default:throw new Error("unreachable")}}function sx(e,t){const n=We(e.left,t);if(typeof n!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; left is ${Ne(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=We(e.right,t);if(typeof r!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; right is ${Ne(r)}`);return r}function ix(e,t){const n=We(e.cond,t);if(typeof n!="boolean")throw Xe(e,`ternary condition must be boolean, got ${Ne(n)}`);return We(n?e.whenTrue:e.whenFalse,t)}function ox(e,t){const n=We(e.target,t);if(n==null)throw new qe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||rs(n))throw Xe(e,`cannot access field '${e.field}' on ${Ne(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function ax(e,t){const n=We(e.target,t);if(n==null)throw new qe("null-access","cannot index null target",e.pos);const r=We(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new qe("invalid-index",`array index must be a non-negative integer, got ${Ne(r)}`,e.pos);if(r<0)throw new qe("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"&&!rs(n)){if(typeof r!="string")throw new qe("invalid-index",`object key must be a string, got ${Ne(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Xe(e,`cannot index into ${Ne(n)}`)}function aa(e,t){if(rs(e))throw new qe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function ti(e,t){if(!Number.isFinite(e))throw new qe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function Ne(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(rs(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 Hh="$expr";class ni extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function cx(e,t){return ca(e,t,"")}function ca(e,t,n){if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const i=new Array(e.length);for(let o=0;o<e.length;o+=1)i[o]=ca(e[o],t,n===""?String(o):`${n}.${o}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,Hh))return lx(r,t,n);const s={};for(const i of Object.keys(r))s[i]=ca(r[i],t,n===""?i:`${n}.${i}`);return s}function lx(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new ni(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(a=>JSON.stringify(a)).join(", ")}]`,n);const s=e[Hh];if(typeof s!="string")throw new ni(`'$expr' value at '${n||"<root>"}' must be a string, got ${fx(s)}`,n);const i=dx(s,n);return ux(i,t,n)}function ux(e,t,n){try{return We(e,t)}catch(r){if(r instanceof qe){const s=new qe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function dx(e,t){try{return Gv(Wv(e))}catch(n){throw n instanceof be?Ul(n,be,t):n instanceof ft?Ul(n,ft,t):n}}function Ul(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function fx(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function hx(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 o=s;if(o.includes("'2+modules'")||o.includes('"2+modules"')){if(!n)return{ok:!1,summary:"Module resolve unavailable: this builder was not wired with `resolveModulesFn`. Use a package entry that wires module resolution, such as pyric/rules/internal/node, instead of importing the impl directly.",data:{code:"NO_MODULE_RESOLVER"}};const u=n(o);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};o=u.data.resolved}const l=(await t()).seed({rules:o,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:o,data:a}=r,u=(await t()).execute({method:s,path:i,auth:o,data:a});return{ok:u.allowed,summary:u.allowed?`${s} on ${i} allowed`:`${s} on ${i} denied`,data:{allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_read",description:"Read a document (`get`) or list a collection (`list`) from the seeded sandbox. Default uses admin access (bypasses rules). Set `evaluateRules: true` with an `auth` context to test read access control through the rules engine.",parameters:{type:"object",properties:{path:{type:"string",description:"Doc path for `get`, collection path for `list`."},method:{type:"string",enum:["get","list"],description:"Default `get`."},auth:{description:"Auth context. Required when `evaluateRules` is true."},evaluateRules:{type:"boolean",description:"Evaluate read rules against `auth`. Default false (admin read)."}},required:["path"]},async execute(r){const{path:s,method:i,auth:o,evaluateRules:a}=r,l=await t();if(a){const u=l.execute({method:i??"get",path:s,auth:o??null});return{ok:u.allowed,summary:u.allowed?`${i??"get"} on ${s} allowed`:`${i??"get"} on ${s} denied`,data:{allowed:u.allowed,document:u.data,debugMessages:u.debugMessages}}}return i==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:l.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:l.getDocument(s)}}}},{name:"firestore_simulator_batch",description:"Execute multiple writes atomically. All operations must pass rules — if any denies, none apply. Rules evaluate each op against pre-batch state (no cross-visibility within the batch).",parameters:{type:"object",properties:{operations:{type:"array",items:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]}},auth:{description:"Auth context for every op. `null` for unauthenticated."}},required:["operations","auth"]},async execute(r){const{operations:s,auth:i}=r,a=(await t()).batch(s,i);return{ok:a.allowed,summary:a.allowed?`Batch of ${s.length} op(s) committed`:`Batch of ${s.length} op(s) rejected by rules. To SEED data, use the admin data tool firestore_batch_write; to test rules, pass an auth the rules permit.`,data:{allowed:a.allowed,results:a.results}}}},{name:"firestore_create_with_auto_id",description:"Create a document at `<collection>/<auto-id>` with a Firestore-compatible 20-char alphanumeric id (mirrors the live SDK `addDoc()` flow). Rules evaluate as for an explicit-id `create`. Returns the minted path so the caller can re-read the doc without a side channel.",parameters:{type:"object",properties:{collection:{type:"string",description:"Collection path under which to mint the new document, e.g. `users` or `users/u1/posts`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }`."},data:{type:"object",description:"Document data.",additionalProperties:!0}},required:["collection","auth","data"]},async execute(r){const{collection:s,auth:i,data:o}=r,a=await t(),{path:l,result:u}=a.createWithAutoId(s,o,i);return{ok:u.allowed,summary:u.allowed?`Created ${l}`:`Create at ${l} denied by rules (as ${i?i.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:l,allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_undo",description:"Undo the last allowed write. Restores state to immediately before that op. Returns the undone event, or a `{ undone: false }` outcome when no retained write remains.",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).undo();return s?{ok:!0,summary:`Undid ${s.method} on ${s.path}`,data:{undone:!0,event:{method:s.method,path:s.path}}}:{ok:!0,summary:"Nothing to undo",data:{undone:!1}}}},{name:"firestore_simulator_redo",description:"Re-apply the most recently undone write. Pairs with `firestore_simulator_undo`. Returns the re-applied event, or `{ redone: false }` when the undo stack is empty (no recent undo to redo).",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${s.event?.method??"op"} on ${s.event?.path??"?"}`:"Redo restored a denied event (no state change)",data:{redone:!0,allowed:s.allowed,event:s.event?{method:s.event.method,path:s.event.path}:null,debugMessages:s.debugMessages}}:{ok:!0,summary:"Nothing to redo",data:{redone:!1}}}},{name:"firestore_simulator_events",description:'Return retained events — allowed and denied — with timestamps, auth, debug messages, and an omitted count when the bounded log was trimmed. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){const r=await t(),{omittedCount:s}=r.getEventRetention();return{ok:!0,summary:s>0?`Event log (${s} omitted)`:"Event log",data:{omittedCount:s,events:r.getEvents().map(o=>({id:o.id,method:o.method,path:o.path,allowed:o.allowed,auth:o.auth,debugMessages:o.debugMessages}))}}}},{name:"firestore_simulator_transaction",description:'Run a declarative transaction. Reads are captured server-side and referenced from write data via `{ "$expr": "..." }` wrappers — agents never see the read values, eliminating the "round-trip the doc through context" cost. Expression DSL: arithmetic (+ - * / %), comparison, &&/||/?:, $alias.field references, string literals in either "double" or \'single\' quotes, and @sentinel(...) calls (@increment, @serverTimestamp, @arrayUnion, @arrayRemove, @deleteField). Reads are omitted from the response by default; set `includeReads: true` when debugging a denial.',parameters:{type:"object",properties:{auth:{description:"Auth context for rule eval. `null` for unauthenticated."},readOnly:{type:"boolean",description:"Hint that the transaction is read-only. v1: writes are still committed; `readOnlyViolation: true` surfaces on the response if any was queued."},includeReads:{type:"boolean",description:"Default false. When true, the response includes the captured read data + per-write debugMessages."},reads:{type:"object",description:"Reads keyed by alias. Aliases referenced from write expressions as `$alias` (e.g. `$src.balance`).",additionalProperties:{type:"string"}},writes:{type:"array",minItems:1,items:{type:"object",properties:{method:{type:"string",enum:["create","update","set","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]},description:"Write operations to apply atomically."}},required:["reads","writes","auth"]},async execute(r){const{auth:s,readOnly:i,includeReads:o,reads:a,writes:l}=r;for(let h=0;h<l.length;h+=1){const f=l[h];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${h}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${h}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=o===!0;try{const h=u.transaction(p=>{const m={};for(const[g,b]of Object.entries(a)){const x=p.get(b).data();m[g]=x===void 0?null:x}for(let g=0;g<l.length;g+=1){const b=l[g];if(b.method==="delete"){p.delete(b.path);continue}const w=cx(b.data,{reads:m});if(w===null||typeof w!="object"||Array.isArray(w))throw new ni(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const x=w;switch(b.method){case"create":p.create(b.path,x);break;case"update":p.update(b.path,x);break;case"set":p.set(b.path,x);break}}},{auth:s,readOnly:i}),f={allowed:h.allowed,writes:h.writes.map(p=>{const m={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(m.error={code:p.error.code,message:p.error.message}),d&&(m.debugMessages=p.debugMessages),m})};return h.error&&(f.error={code:h.error.code,message:h.error.message}),h.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=h.reads.map(p=>({path:p.path,data:p.data}))),{ok:h.allowed,summary:h.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(h){if(h instanceof ni||h instanceof be||h instanceof ft||h instanceof qe)return{ok:!1,summary:`Transaction failed: ${h.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:h.message}}};throw h}}}]}function px(e){return hx({resolveSandbox:e.resolveSandbox,resolveModulesFn:_h})}const mx=new Set([".read",".write",".validate",".indexOn"]),yx=new Set([".read",".write",".validate"]),Cc=/[.#$/[\]]/,gx="Invalid rule expression. Expected 'true', 'false', or an expression string.",bx="Invalid indexOn expression. Must be either a string or an array of strings",Bl=`String can't contain ".", "#", "$", "/", "[", or "]"`,Fl="Expected '{'.",ql=e=>`Invalid key: ${e}. Index must be either .value or declared on a valid path`;function wx(e,t){const n=Array.isArray(e)?e:[e];for(const r of n){if(typeof r!="string"||r===".value")continue;const s=r.split("/");s.some(i=>i.includes("."))?t(ql(r),"error"):s.some(i=>Cc.test(i))&&t(ql(r),"warning")}}function Kh(e,t){const n=[],r=(i,o,a="error")=>{n.push({path:e,code:i,message:o,severity:a})},s=[];for(const[i,o]of Object.entries(t)){if(yx.has(i)){typeof o!="string"&&typeof o!="boolean"&&r("RULE_NOT_EXPRESSION",gx,typeof o=="number"||typeof o=="object"&&o!==null?"error":"warning");continue}if(i===".indexOn"){const u=h=>typeof h=="string";u(o)||Array.isArray(o)&&o.every(u)?wx(o,(h,f)=>r("INVALID_KEY",h,f)):r("INDEX_ON_SHAPE",bx,typeof o=="number"?"error":"warning");continue}const a=typeof o=="object"&&o!==null&&!Array.isArray(o);if(i.startsWith(".")){a?r("INVALID_KEY",Bl):r("EXPECTED_OBJECT",Fl);continue}i.startsWith("$")&&s.push(i);const l=i.startsWith("$")?i.slice(1):i;Cc.test(l)?r("INVALID_KEY",Bl,l.includes("#")?"error":"warning"):a||r("EXPECTED_OBJECT",Fl)}return s.length>1&&r("MULTIPLE_WILDCARDS",`Cannot have multiple default rules ('${s[0]}' and '${s[1]}').`),n}const ie=e=>e;function Ye(e){if(e===null)return"null";if(typeof e=="string"){if(/[\u0000-\u001f\u007f]/.test(e))throw new Error(`lit: ${JSON.stringify(e)} holds a newline or another control character, which RTDB rules literals here cannot carry.`);return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`RTDB rules have no literal for ${e}.`);return String(e)}if(typeof e=="boolean")return e?"true":"false";let t=typeof e;throw e===void 0?t="undefined":Array.isArray(e)&&(t="array"),new Error(`RTDB rules have no literal for ${t}.`)}function Gh(e,t){if(typeof t!="string"||t.length===0||Cc.test(t))throw new Error(`${e}: '${String(t)}' is not a field name; RTDB keys cannot be empty or contain . # $ / [ ].`);return t}function vx(e,t){let n=0,r=null,s=!1,i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(r){a==="\\"?o++:a===r&&(r=null);continue}if(s){a==="\\"?o++:i?a==="]"&&(i=!1):a==="["?i=!0:a==="/"&&(s=!1);continue}if(a==="'"||a==='"')r=a;else if(a==="/"&&/\(\s*$/.test(e.slice(0,o)))s=!0;else if(a==="("||a==="[")n++;else if(a===")"||a==="]")n--;else if(n===0&&t.some(l=>e.startsWith(l,o)))return!0}return!1}const Jh=(e,t)=>vx(e,t)?`(${e})`:e,Yh=e=>e.trim().length>0;function $n(...e){const t=e.filter(Yh);if(t.length===0)throw new Error("all: pass at least one condition; an empty all() would allow everything.");return t.length===1?t[0]:ie(t.map(n=>Jh(n,["||","?"])).join(" && "))}function Vl(...e){const t=e.filter(Yh);if(t.length===0)throw new Error("any: pass at least one condition; an empty any() would deny everything.");return t.length===1?t[0]:ie(t.map(n=>Jh(n,["&&","?"])).join(" || "))}const xx=`RtdbExpr {
|
|
6
|
+
Expr = Ternary
|
|
7
|
+
|
|
8
|
+
Ternary
|
|
9
|
+
= LogicalOr "?" Ternary ":" Ternary -- ternary
|
|
10
|
+
| LogicalOr
|
|
11
|
+
|
|
12
|
+
// \`||\` and \`&&\` match as flat chains, not left recursion, so a semantics
|
|
13
|
+
// folds a chain of any length in a loop instead of descending once per
|
|
14
|
+
// term. Production deploys a 2,000-term \`||\` chain (r51).
|
|
15
|
+
LogicalOr
|
|
16
|
+
= LogicalAnd ("||" LogicalAnd)+ -- or
|
|
17
|
+
| LogicalAnd
|
|
18
|
+
|
|
19
|
+
LogicalAnd
|
|
20
|
+
= Equality ("&&" Equality)+ -- and
|
|
21
|
+
| Equality
|
|
22
|
+
|
|
23
|
+
Equality
|
|
24
|
+
= Equality "===" Comparison -- strictEq
|
|
25
|
+
| Equality "!==" Comparison -- strictNeq
|
|
26
|
+
| Equality "==" Comparison -- looseEq
|
|
27
|
+
| Equality "!=" Comparison -- looseNeq
|
|
28
|
+
| Comparison
|
|
29
|
+
|
|
30
|
+
Comparison
|
|
31
|
+
= Comparison ">=" Additive -- gte
|
|
32
|
+
| Comparison "<=" Additive -- lte
|
|
33
|
+
| Comparison ">" Additive -- gt
|
|
34
|
+
| Comparison "<" Additive -- lt
|
|
35
|
+
| Additive
|
|
36
|
+
|
|
37
|
+
Additive
|
|
38
|
+
= Additive "+" Multiplicative -- add
|
|
39
|
+
| Additive "-" Multiplicative -- sub
|
|
40
|
+
| Multiplicative
|
|
41
|
+
|
|
42
|
+
Multiplicative
|
|
43
|
+
= Multiplicative "*" UnaryExpr -- mul
|
|
44
|
+
| Multiplicative "/" UnaryExpr -- div
|
|
45
|
+
| Multiplicative "%" UnaryExpr -- mod
|
|
46
|
+
| UnaryExpr
|
|
47
|
+
|
|
48
|
+
UnaryExpr
|
|
49
|
+
= "!" UnaryExpr -- not
|
|
50
|
+
| "-" UnaryExpr -- neg
|
|
51
|
+
| CallExpr
|
|
52
|
+
|
|
53
|
+
CallExpr
|
|
54
|
+
= CallExpr "." ident "(" ListOf<Expr, ","> ")" -- methodCall
|
|
55
|
+
| CallExpr "." ident -- memberAccess
|
|
56
|
+
| CallExpr "[" Expr "]" -- indexAccess
|
|
57
|
+
| Primary
|
|
58
|
+
|
|
59
|
+
Primary
|
|
60
|
+
= "(" Expr ")" -- paren
|
|
61
|
+
| Array
|
|
62
|
+
| literal
|
|
63
|
+
| ident
|
|
64
|
+
|
|
65
|
+
Array = "[" ListOf<Expr, ","> "]"
|
|
66
|
+
|
|
67
|
+
literal
|
|
68
|
+
= number
|
|
69
|
+
| string
|
|
70
|
+
| regex
|
|
71
|
+
| bool
|
|
72
|
+
| null
|
|
73
|
+
|
|
74
|
+
number
|
|
75
|
+
= digit+ "." digit+ exponent? -- float
|
|
76
|
+
| digit+ exponent -- exp
|
|
77
|
+
| digit+ -- int
|
|
78
|
+
|
|
79
|
+
exponent = ("e" | "E") ("+" | "-")? digit+
|
|
80
|
+
|
|
81
|
+
string
|
|
82
|
+
= "\\"" doubleStringChar* "\\"" -- double
|
|
83
|
+
| "'" singleStringChar* "'" -- single
|
|
84
|
+
|
|
85
|
+
doubleStringChar
|
|
86
|
+
= "\\\\" any -- escape
|
|
87
|
+
| ~"\\"" any -- char
|
|
88
|
+
|
|
89
|
+
singleStringChar
|
|
90
|
+
= "\\\\" any -- escape
|
|
91
|
+
| ~"'" any -- char
|
|
92
|
+
|
|
93
|
+
regex = "/" regexBody "/" regexFlags
|
|
94
|
+
|
|
95
|
+
regexBody = regexChar+
|
|
96
|
+
|
|
97
|
+
regexChar
|
|
98
|
+
= "\\\\" any -- escape
|
|
99
|
+
| regexClass -- class
|
|
100
|
+
| ~("/" | "\\n" | "[") any -- char
|
|
101
|
+
|
|
102
|
+
regexClass = "[" regexClassChar* "]"
|
|
103
|
+
|
|
104
|
+
regexClassChar
|
|
105
|
+
= "\\\\" any -- escape
|
|
106
|
+
| ~("]" | "\\n") any -- char
|
|
107
|
+
|
|
108
|
+
regexFlags = alnum*
|
|
109
|
+
|
|
110
|
+
bool
|
|
111
|
+
= "true" ~identChar -- true
|
|
112
|
+
| "false" ~identChar -- false
|
|
113
|
+
|
|
114
|
+
null = "null" ~identChar
|
|
115
|
+
|
|
116
|
+
ident = "$"? identStart identChar*
|
|
117
|
+
|
|
118
|
+
identStart = letter | "_"
|
|
119
|
+
|
|
120
|
+
identChar = alnum | "_" | "$"
|
|
121
|
+
}
|
|
122
|
+
`;let Wl;function Qh(){return Wl??=aw(xx),Wl}const ss="The expression chains more terms than the rules parser reads.",Xh=128*1024;function _x(e){return`The expression is ${e} characters long: the rules parser reads at most ${Xh}, a limit of this parser, not of production.`}function is(e){const t=e.trim();if(t.length>Xh)return{ok:!1,message:_x(t.length)};const n=ow(t,{comments:!1,regexLiterals:!0,multilineStrings:!0}).find(r=>r.depth>co);if(n!==void 0)return{ok:!1,message:`Brackets nest more than ${co} levels deep at offset ${n.open}: the rules parser reads at most ${co}, a limit of this parser, not of production.`};try{const r=Qh().match(t);return r.failed()?{ok:!1,message:r.message??"Parse failed"}:{ok:!0,match:r}}catch(r){if(r instanceof RangeError)return{ok:!1,message:ss};throw r}}function os(){return Qh().createSemantics()}const ri="unterminated string literal",Sx=/^[0-9a-fA-F]{2}$/,kx=/^[0-9a-fA-F]{4}$/,Ex={b:"\b",f:"\f",n:`
|
|
123
|
+
`,r:"\r",t:" ",v:"\v",0:"\0","\\":"\\","'":"'",'"':'"',"/":"/"};function Or(e){const t=Zh(e);return t.includes(`
|
|
124
|
+
`)||t.includes("\r")}function jx(e){let t=0;const n=e.length;let r=!0;for(;t<n;){const s=e[t];if(s===" "||s===" "||s===`
|
|
125
|
+
`||s==="\r"){t++;continue}if(s==='"'||s==="'"){const i=s;for(t++;t<n;){const o=e[t];if(o===`
|
|
126
|
+
`||o==="\r")return!0;if(o==="\\"){t+=2;continue}if(o===i){t++;break}t++}r=!1;continue}if(s==="/"&&r){t=cw(e,t),r=!1;continue}r=Cx(s),t++}return!1}function $r(e){const t=Zh(e);let n="",r=0;const s=t.length;for(;r<s;){const i=t[r];if(i!=="\\"){n+=i,r++;continue}if(r+1>=s){n+="\\";break}const o=t[r+1],a=Ex[o];if(a!==void 0){n+=a,r+=2;continue}if(o==="x"&&r+3<s){const l=t.slice(r+2,r+4);if(Sx.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=4;continue}}if(o==="u"&&r+5<s){const l=t.slice(r+2,r+6);if(kx.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=6;continue}}n+=o,r+=2}return n}function Zh(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==='"'&&n==='"'||t==="'"&&n==="'")return e.slice(1,-1)}return e}function Cx(e){return"(!,&|?:;=[<>+-*%".includes(e)}function mn(e,t){return e==="matches"?"matches() expects 1 regular expression literal argument.":t===0?`${e}() expects no arguments.`:t===1?`${e}() expects 1 argument.`:`${e}() expects two arguments.`}function ep(e){return`${e}() expects a string argument.`}function la(e){return`Argument ${e} of replace() must be a string.`}const tp="hasChildren() expects only a single argument (containing an array of child names).",np="hasChildren() expects an array of child names.",rp="hasChildren() expects an array of strings.";function si(e,t){switch(e){case"==":case"===":return t==="left"?"Invalid == expression: left operand is not a number, boolean, string, null.":"Invalid == expression: right operand is not a number, boolean, string, or null.";case"!=":case"!==":return`Invalid != expression: ${t} operand is not a number, boolean, string, or null.`;case"+":return`Invalid + expression: ${t} operand is not a number or string.`;case"-":case"*":case"/":case"%":return`Invalid ${e} expression: ${t} operand is not a number.`;default:return`Invalid ${e} expression: ${t} operand must be a number or string.`}}function zl(e){return`Unknown variable '${e}'.`}const sp="matches() expects a regular expression literal argument.",ip="regular expressions do not support flags other than i";function Ic(e){return e===""||e==="i"}const Ix=2147483647,ii=1e4,dn=2e5,oi=1e3;function Rx(e){return`For input string: "${e}"`}const Nx="Illegal regular expression, could not determinize efficiently",Ax=`Regular expression expands to more than ${dn} matcher states: pyric matches at most ${dn}, a limit of pyric, not of production.`,Hl=`Regular expression groups and quantifiers nest more than ${oi} levels deep: pyric reads at most ${oi}, a limit of pyric, not of production.`;function Ox(e){return hr(e)>ii?Nx:kn(e)>dn?Ax:null}function hr(e){switch(e.kind){case"empty":return 0;case"char":case"assert":return 1;case"seq":return fn(e.items.map(hr),ii);case"alt":return fn([hr(e.left),hr(e.right)],ii);case"rep":return $x(hr(e.body),e.min,e.max)}}function $x(e,t,n){if(n===0||e===0)return 0;if(e===1/0)return 1/0;const r=n===1/0?t+1:n;return fn([e*r],ii)}function kn(e){switch(e.kind){case"empty":return 0;case"char":case"assert":return 1;case"seq":return fn(e.items.map(kn),dn);case"alt":return fn([kn(e.left),kn(e.right),1],dn);case"rep":return Px(kn(e.body),e.min,e.max)}}function Px(e,t,n){return n===0?0:e===1/0?1/0:fn(n===1/0?[e*(t+1),1]:[(n-t)*(e+1),t*e],dn)}function fn(e,t){let n=0;for(const r of e)if(n+=r,n>t)return 1/0;return n}const op="Illegal regular expression, ";class ai extends SyntaxError{}const Dx={kind:"char",test:()=>!1},Tx={kind:"char",test:()=>!0},Mx="?*+{",Kl="0123456789",Gl=e=>e>="0"&&e<="9",Jl=e=>/^[A-Za-z0-9_]$/.test(e),Yl=e=>e.length===1&&`
|
|
127
|
+
\v\f\r`.includes(e),Lx={d:Gl,D:e=>!Gl(e),w:Jl,W:e=>!Jl(e),s:Yl,S:e=>!Yl(e)};class Ux{text;ignoreCase;pos=0;depth=0;constructor(t,n){this.text=t,this.ignoreCase=n}parse(){if(!this.more())return{kind:"empty"};const t=this.union();this.more()&&this.fail("end-of-string expected");const n=Ox(t);return n!==null&&this.refuse(n),t}union(){const t=[this.concat()];for(;this.match("|");)t.push(this.concat());return ua(t,0,t.length)}concat(){const t=[this.repeat()];for(;this.more()&&!this.peek(")|");)t.push(this.repeat());return t.length===1?t[0]:{kind:"seq",items:t}}repeat(){let t=this.characterSet(),n=0;for(;this.peek(Mx);)n++,this.depth+n>oi&&this.refuse(Hl),this.match("?")?t={kind:"rep",body:t,min:0,max:1}:this.match("*")?t={kind:"rep",body:t,min:0,max:1/0}:this.match("+")?t={kind:"rep",body:t,min:1,max:1/0}:t=this.counted(t);return t}counted(t){this.pos++;const n=this.integer();let r=n;return this.match(",")&&(r=this.peek(Kl)?this.integer():1/0),this.match("}")||this.fail(`expected '}' at position ${this.pos}`),n>r?Dx:{kind:"rep",body:t,min:n,max:r}}integer(){const t=this.pos;for(;this.peek(Kl);)this.pos++;t===this.pos&&this.fail(`integer expected at position ${this.pos}`);const n=this.text.slice(t,this.pos),r=Number(n);return r>Ix&&this.refuse(Rx(n)),r}characterSet(){if(!this.match("["))return this.simple();const t=this.match("^"),n=[this.setMember()];for(;this.more()&&!this.peek("]");)n.push(this.setMember());this.match("]")||this.fail(`expected ']' at position ${this.pos}`);const r=n.map(i=>this.memberTest(i)),s=i=>r.some(o=>o(i));return t?{kind:"char",test:i=>!s(i)}:{kind:"char",test:s}}setMember(){const t=this.charExp();if(t.kind==="class"||!this.match("-"))return t;const n={kind:"char",ch:"-"};if(this.peek("]"))return{kind:"class",test:this.unionTest([t,n])};const r=this.charExp();return r.kind==="class"?{kind:"class",test:this.unionTest([t,n,r])}:{kind:"range",from:t.ch,to:r.ch}}memberTest(t){return t.kind==="range"?this.rangeTest(t.from,t.to):this.unionTest([t])}unionTest(t){const n=t.map(r=>r.kind==="class"?r.test:this.literal(r.ch));return r=>n.some(s=>s(r))}simple(){if(this.match("."))return Tx;if(this.match("("))return this.group();const t=this.charExp();return{kind:"char",test:t.kind==="class"?t.test:this.literal(t.ch)}}group(){if(this.match(")"))return{kind:"empty"};this.depth++,this.depth>oi&&this.refuse(Hl);const t=this.union();return this.depth--,this.match(")")||this.fail(`expected ')' at position ${this.pos}`),t}charExp(){const t=this.match("\\"),n=this.next(),r=t?Lx[n]:void 0;return r?{kind:"class",test:r}:{kind:"char",ch:n}}literal(t){if(!this.ignoreCase)return r=>r===t;const n=ws(t);return r=>n.includes(r)}rangeTest(t,n){const r=Fx(t,n);if(!this.ignoreCase)return r;const s=n.charCodeAt(0)-t.charCodeAt(0);if(s<0)return r;if(s>Bx){const o=a=>l=>r(l)&&ws(l).includes(a);return a=>r(a)||ws(a).some(o(a))}const i=new Set;for(let o=t.charCodeAt(0);o<=n.charCodeAt(0);o++)for(const a of ws(String.fromCharCode(o)))i.add(a);return o=>i.has(o)}next(){return this.more()||this.fail("unexpected end-of-string"),this.text[this.pos++]}more(){return this.pos<this.text.length}peek(t){return this.more()&&t.includes(this.text[this.pos])}match(t){return this.text[this.pos]!==t?!1:(this.pos++,!0)}fail(t){throw new ai(`${op}${t}`)}refuse(t){throw new ai(t)}}const Bx=4096;function ws(e){const t=[e];for(const n of[e.toUpperCase(),e.toLowerCase()])n.length===1&&!t.includes(n)&&t.push(n);return t}function Fx(e,t){return n=>n.length===1&&n>=e&&n<=t}function ua(e,t,n){if(n-t===1)return e[t];const r=t+Math.floor((n-t)/2);return{kind:"alt",left:ua(e,t,r),right:ua(e,r,n)}}const qx=`${op}unescaped ^, ^ can only appear at the end of regular expressions`;class ap{source;flags;node;matcher;constructor(t,n,r){this.source=t,this.flags=n,this.node=r}test(t){return this.matcher??=lw(this.node),this.matcher(t.split(""))}}function cp(e){try{return lp(e,!1),null}catch(t){if(t instanceof ai)return t.message;throw t}}const Vx=1e6,lo=new Map;let uo=0;function Wx(e,t){const n=`${t}/${e}`,r=lo.get(n);if(r)return r;const s=lp(e,t.includes("i")),i=new ap(e,t,s),o=kn(s);return uo+o>Vx&&(lo.clear(),uo=0),lo.set(n,i),uo+=o,i}function lp(e,t){return new Ux(zx(e),t).parse()}function zx(e){const t=e.startsWith("^");let n=t?e.slice(1):e;const r=Hx(n);if(r&&(n=n.slice(0,-1)),Kx(n))throw new ai(qx);return`${t?"":".*"}${n}${r?"":".*"}`}function Hx(e){if(!e.endsWith("$"))return!1;let t=0;for(let n=e.length-2;n>=0&&e[n]==="\\";n--)t++;return t%2===0}function Kx(e){let t=0;for(;t<e.length;){const n=e[t];if(n==="\\")t+=2;else if(n==="[")t=Gx(e,t);else{if(n==="^"||n==="$")return!0;t++}}return!1}function Gx(e,t){let n=t+1;e[n]==="^"&&n++;let r=!0;for(;n<e.length;){const s=e[n];if(s==="]"&&!r)return n+1;n+=s==="\\"?2:1,r=!1}return n}const Jx=new Set(["__proto__","prototype","constructor"]);function Ql(e,t){return Jx.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 Rc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wr(e){if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=wr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(!Rc(e))return e??null;if(Object.hasOwn(e,".value"))return wr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;const s=wr(r);s!==null&&Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return Object.keys(t).length===0?null:t}function Yx(e){if(!Rc(e)||wr(e)===null)return null;const t=e[".priority"];return typeof t=="number"||typeof t=="string"?t:null}class Ft{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return wr(this._value)}exists(){return this.val()!==null}hasChild(t){return this.child(t).exists()}hasChildren(t){return t!==void 0?t.every(n=>this.hasChild(n)):Rc(this.val())}isString(){return typeof this.val()=="string"}isNumber(){return typeof this.val()=="number"}isBoolean(){return typeof this.val()=="boolean"}child(t){const n=t.split("/").filter(o=>o.length>0);if(n.length===0)return this;let r=this._value;for(const o of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,o)?r[o]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new Ft(r,i,this._root)}parent(){if(this._path==="/")throw new ee("Cannot call parent() on root.");const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new Ft(this._root,"/"):new Ft(this._root,"/").child(t.join("/"))}getPriority(){return Yx(this._value)}}class Qx{value;constructor(t){this.value=t}matches(t){return t.test(this.value)}contains(t){return this.value.includes(t)}beginsWith(t){return this.value.startsWith(t)}endsWith(t){return this.value.endsWith(t)}replace(t,n){return t===""?this.value:this.value.split(t).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}class ee extends Error{constructor(t){super(t),this.name="RtdbRuleRuntimeError"}}const Xl=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),Xx=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase"]);function Zn(e,t){if(t.length!==1)throw new ee(mn(e,1));const[n]=t;if(typeof n!="string")throw new ee(ep(e));return n}function Zx(e){if(e.length===0)return;if(e.length>1)throw new ee(tp);const[t]=e;if(!Array.isArray(t))throw new ee(np);if(!t.every(n=>typeof n=="string"))throw new ee(rp);return t}function e_(e){if(e.length!==1)throw new ee(mn("matches",1));const[t]=e;if(!(t instanceof ap))throw new ee(sp);return t}function t_(e){if(e.length!==2)throw new ee(mn("replace",2));const[t,n]=e;if(typeof t!="string")throw new ee(la(1));if(typeof n!="string")throw new ee(la(2));return[t,n]}const n_=new Set(["==","===","!=","!=="]),r_=new Set(["-","*","/","%"]),s_=new Set(["<","<=",">",">="]);function Zl(e,t){return t instanceof Ft||typeof t=="function"?!0:n_.has(e)?!1:r_.has(e)?typeof t!="number":typeof t!="number"&&typeof t!="string"}function Be(e,t,n,r){const s=t.eval(r);if(Zl(e,s))throw new ee(si(e,"left"));const i=n.eval(r);if(Zl(e,i)||s_.has(e)&&typeof s!=typeof i)throw new ee(si(e,"right"));return[s,i]}function i_(e){return e===null?"null":Array.isArray(e)?"array":typeof e}let fo;function o_(){if(fo)return fo;const e=os();return e.addOperation("eval(ctx)",{Expr(t){return t.eval(this.args.ctx)},Ternary_ternary(t,n,r,s,i){const o=t.eval(this.args.ctx);if(typeof o!="boolean")throw new ee("condition of ? must be boolean.");return o?r.eval(this.args.ctx):i.eval(this.args.ctx)},Ternary(t){return t.eval(this.args.ctx)},LogicalOr_or(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of || must be boolean.");if(s)return!0;for(const i of r.children){const o=i.eval(this.args.ctx);if(typeof o!="boolean")throw new ee("Right operand of || must be boolean.");if(o)return!0}return!1},LogicalOr(t){return t.eval(this.args.ctx)},LogicalAnd_and(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of && must be boolean.");if(!s)return!1;for(const i of r.children){const o=i.eval(this.args.ctx);if(typeof o!="boolean")throw new ee("Right operand of && must be boolean.");if(!o)return!1}return!0},LogicalAnd(t){return t.eval(this.args.ctx)},Equality_strictEq(t,n,r){const[s,i]=Be("===",t,r,this.args.ctx);return s===i},Equality_strictNeq(t,n,r){const[s,i]=Be("!==",t,r,this.args.ctx);return s!==i},Equality_looseEq(t,n,r){const[s,i]=Be("==",t,r,this.args.ctx);return s===i},Equality_looseNeq(t,n,r){const[s,i]=Be("!=",t,r,this.args.ctx);return s!==i},Equality(t){return t.eval(this.args.ctx)},Comparison_gte(t,n,r){const[s,i]=Be(">=",t,r,this.args.ctx);return s>=i},Comparison_lte(t,n,r){const[s,i]=Be("<=",t,r,this.args.ctx);return s<=i},Comparison_gt(t,n,r){const[s,i]=Be(">",t,r,this.args.ctx);return s>i},Comparison_lt(t,n,r){const[s,i]=Be("<",t,r,this.args.ctx);return s<i},Comparison(t){return t.eval(this.args.ctx)},Additive_add(t,n,r){const[s,i]=Be("+",t,r,this.args.ctx);return s+i},Additive_sub(t,n,r){const[s,i]=Be("-",t,r,this.args.ctx);return s-i},Additive(t){return t.eval(this.args.ctx)},Multiplicative_mul(t,n,r){const[s,i]=Be("*",t,r,this.args.ctx);return s*i},Multiplicative_div(t,n,r){const[s,i]=Be("/",t,r,this.args.ctx);return i===0?Number.NaN:s/i},Multiplicative_mod(t,n,r){const[s,i]=Be("%",t,r,this.args.ctx);return s%i},Multiplicative(t){return t.eval(this.args.ctx)},UnaryExpr_not(t,n){const r=n.eval(this.args.ctx);return typeof r=="boolean"?!r:!1},UnaryExpr_neg(t,n){const r=n.eval(this.args.ctx);if(typeof r!="number")throw new ee("Invalid unary - expression: operand is not a number.");return-r},UnaryExpr(t){return t.eval(this.args.ctx)},CallExpr_methodCall(t,n,r,s,i,o){const a=t.eval(this.args.ctx),l=r.sourceString,u=i.asIteration().children.map(h=>h.eval(this.args.ctx));if(a instanceof Ft)switch(l){case"val":return a.val();case"exists":return a.exists();case"hasChild":return a.hasChild(Zn(l,u));case"hasChildren":return a.hasChildren(Zx(u));case"isString":return a.isString();case"isNumber":return a.isNumber();case"isBoolean":return a.isBoolean();case"child":return a.child(Zn(l,u));case"parent":return a.parent();case"getPriority":return a.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof a=="string"){const h=new Qx(a);switch(l){case"matches":return h.matches(e_(u));case"contains":return h.contains(Zn(l,u));case"beginsWith":return h.beginsWith(Zn(l,u));case"endsWith":return h.endsWith(Zn(l,u));case"replace":return h.replace(...t_(u));case"toLowerCase":return h.toLowerCase();case"toUpperCase":return h.toUpperCase();default:throw Xl.has(l)?new ee(`Method '${l}' is not defined on a string.`):new Error(`Unknown string method: ${l}`)}}throw(Xl.has(l)||Xx.has(l))&&a!==void 0?new ee(`Method '${l}' is not defined on ${i_(a)}.`):new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval(this.args.ctx),i=r.sourceString;if(i==="length"){if(typeof s=="string")return s.length;throw new ee("No such method/property 'length'.")}return s==null?null:Ql(s,i)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(this.args.ctx),o=r.eval(this.args.ctx);if(typeof o!="string"&&typeof o!="number")throw new ee("Invalid property access.");return i==null?null:Ql(i,String(o))},CallExpr(t){return t.eval(this.args.ctx)},Primary_paren(t,n,r){return n.eval(this.args.ctx)},Primary(t){return t.eval(this.args.ctx)},Array(t,n,r){return n.asIteration().children.map(s=>s.eval(this.args.ctx))},literal(t){return t.eval(this.args.ctx)},number_float(t,n,r,s){return parseFloat(this.sourceString)},number_exp(t,n){return parseFloat(this.sourceString)},number_int(t){return parseInt(this.sourceString,10)},number(t){return t.eval(this.args.ctx)},string_double(t,n,r){if(Or(this.sourceString))throw new SyntaxError(ri);return $r(this.sourceString)},string_single(t,n,r){if(Or(this.sourceString))throw new SyntaxError(ri);return $r(this.sourceString)},string(t){return t.eval(this.args.ctx)},regex(t,n,r,s){if(!Ic(s.sourceString))throw new ee(ip);return Wx(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval(this.args.ctx)},null(t){return null},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$"){const o=s?.pathVariableBindings;if(o!==void 0){if(i in o)return o[i];if(i.slice(1)in o)return o[i.slice(1)]}return}switch(i){case"auth":return s?.auth??null;case"data":return s?.data;case"newData":return s?.newData;case"root":return s?.root;case"now":return s?.now;case"query":return s?.query??null;default:return}}}),fo=e,e}function up(e){const t=is(e);if(!t.ok)throw new Error(t.message);return o_()(t.match)}function Vs(e,t){return up(e).eval(t)}const eu=new WeakMap;function a_(e,t){let n=eu.get(e);return n===void 0&&(n=up(e.raw),eu.set(e,n)),n.eval(t)}let ho;const c_=/^\$[A-Za-z_]\w*$/,l_=/^(?:auth|data|newData|root|query)(?:\.|\[)/;function u_(e){return e==="now"||c_.test(e)||l_.test(e)}function d_(e){if(e.isLiteral())try{const t=Vs(e.sourceString,{});return typeof t=="string"?t:void 0}catch(t){if(t instanceof ee)return;throw t}}function xt(e){const[t,,n]=e.children;if(!(!t.isLiteral()||!n.isLiteral()))try{const r=Vs(t.sourceString,{}),s=Vs(n.sourceString,{});return typeof r=="number"&&!Number.isFinite(r)||typeof s=="number"&&!Number.isFinite(s)?void 0:Vs(e.sourceString,{})===!0}catch(r){if(r instanceof ee)return;throw r}}function At(e,t,n){const r=e.args.ctx;t.lint(r),n.lint(r);const s=xt(e);if(s!==void 0){r.constantComparisons.push({source:e.sourceString,value:s});return}const i=t.isLiteral(),o=n.isLiteral();if(i===o)return;let a=n;i&&(a=t);const l=d_(a);l!==void 0&&u_(l)&&r.warnings.push({code:"QUOTED_REFERENCE",message:`Comparison ${e.sourceString} quotes '${l}' as a string literal; it compares against the literal text '${l}' rather than evaluating ${l}.`})}function f_(){if(ho)return ho;const e=os();return e.addOperation("lint(ctx)",{_nonterminal(...t){t.forEach(n=>n.lint(this.args.ctx))},_iter(...t){t.forEach(n=>n.lint(this.args.ctx))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx;t.lint(a),i.asIteration().children.forEach(l=>l.lint(a)),r.sourceString==="child"&&t.isDataSnapshot()&&(a.hasDataChildAccess=!0)},CallExpr_memberAccess(t,n,r){t.lint(this.args.ctx)},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;i==="data"&&(s.hasData=!0),i==="newData"&&(s.hasNewData=!0)},Equality_strictEq(t,n,r){At(this,t,r)},Equality_strictNeq(t,n,r){At(this,t,r)},Comparison_gte(t,n,r){At(this,t,r)},Comparison_lte(t,n,r){At(this,t,r)},Comparison_gt(t,n,r){At(this,t,r)},Comparison_lt(t,n,r){At(this,t,r)},Equality_looseEq(t,n,r){At(this,t,r)},Equality_looseNeq(t,n,r){At(this,t,r)}}),e.addOperation("isDataSnapshot",{_nonterminal(...t){return t.length===1?t[0].isDataSnapshot():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isDataSnapshot()},ident(t,n,r){return this.sourceString==="data"},CallExpr_methodCall(t,n,r,s,i,o){const a=r.sourceString;return a==="parent"||a==="child"?t.isDataSnapshot():!1}}),e.addOperation("isNumberLiteral",{_nonterminal(...t){return t.length===1?t[0].isNumberLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isNumberLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},number(t){return Number.isFinite(Number(this.sourceString))}}),e.addOperation("isLiteral",{_nonterminal(...t){return t.length===1?t[0].isLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},literal(t){return t.ctorName==="regex"?!1:t.ctorName==="number"?Number.isFinite(Number(t.sourceString)):!0}}),e.addOperation("literalBoolean",{_nonterminal(...t){return t.length===1?t[0].literalBoolean():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalBoolean()},bool_true(t){return!0},bool_false(t){return!1},Equality_strictEq(t,n,r){return xt(this)},Equality_strictNeq(t,n,r){return xt(this)},Comparison_gte(t,n,r){return xt(this)},Comparison_lte(t,n,r){return xt(this)},Comparison_gt(t,n,r){return xt(this)},Comparison_lt(t,n,r){return xt(this)},Equality_looseEq(t,n,r){return xt(this)},Equality_looseNeq(t,n,r){return xt(this)}}),ho=e,e}function h_(e,t="read"){const n=is(e);if(!n.ok)return[];const{match:r}=n,s={warnings:[],hasData:!1,hasNewData:!1,hasDataChildAccess:!1,constantComparisons:[]};try{const i=f_()(r);i.lint(s);const o=t==="validate"?void 0:i.literalBoolean();if(o===!0)s.warnings.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"});else if(o===!1)s.warnings.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"});else for(const{source:a,value:l}of s.constantComparisons)s.warnings.push({code:"CONSTANT_COMPARISON",message:`Comparison ${a} is always ${l}.`})}catch(i){if(i instanceof RangeError)return[{code:"PARSE_ERROR",message:ss}];if(i instanceof SyntaxError)return[{code:"PARSE_ERROR",message:i.message}];throw i}return t==="write"&&s.hasData&&!s.hasNewData&&!s.hasDataChildAccess&&s.warnings.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),s.warnings}function p_(e,t){if(typeof t!="string"||t.length===0)throw new Error(`${e}: child path cannot be empty.`);for(const n of t.split("/"))Gh(e,n);return t}const m_=()=>ie("newData.hasChildren()"),y_=e=>ie(`newData.hasChild(${Ye(p_("hasChild",e))})`);let po;function g_(){if(po)return po;const e=os();return e.addOperation("identifiers",{_nonterminal(...t){return t.flatMap(n=>n.identifiers())},_iter(...t){return t.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(t,n,r,s,i,o){return[...t.identifiers(),...i.asIteration().children.flatMap(a=>a.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),po=e,e}const b_="Rule expressions may not contain assignments.";function w_(e){const t=e.replace(/'(?:\\.|[^'\\])*'?|"(?:\\.|[^"\\])*"?|\/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[a-zA-Z]*/g,'""');return/(^|[^=!<>])=(?!=)/.test(t)}function v_(e){if(jx(e))return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ri}],warnings:[],referencedIdentifiers:[]};const t=is(e);if(!t.ok)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:w_(e)?b_:t.message}],warnings:[],referencedIdentifiers:[]};let n;try{n=g_()(t.match).identifiers()}catch(s){if(s instanceof RangeError)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ss}],warnings:[],referencedIdentifiers:[]};throw s}const r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function x_(e){return e==="rtdb"?"database":"firestore"}function er(e){return e.kind==="doc"?e.path:{collection:e.collection,query:e.query}}function __(e){return e.path!==void 0?e.path:{collection:"",query:e.query}}function tu(e){const t=e.query;return t===void 0?{}:{query:t}}function S_(e){const t=vc(e),n="owners"in e&&Array.isArray(e.owners)?e.owners:void 0,r={actor:t.source,authLens:t.authLens,owners:n};return e.kind==="listener_attach"?{phase:"attach",listenerId:e.listenerId,service:"firestore",target:er(e.target),...r,...tu(e.target)}:e.kind==="listener_detach"?{phase:"detach",listenerId:e.listenerId,service:"firestore",target:er(e.target),...r}:e.kind==="listener_errored"?{phase:"errored",listenerId:e.listenerId,service:"firestore",target:er(e.target),...r}:e.kind==="snapshot_delivery"?{phase:"delivery",listenerId:e.listenerId,service:"firestore",target:er(e.target),...r}:e.kind==="snapshot_suppressed"?{phase:"suppressed",listenerId:e.listenerId,service:"firestore",target:er(e.target),...r}:e.kind==="listener"?{phase:e.phase,listenerId:e.listenerId,service:x_(e.service),target:__(e.target),...r,...tu(e.target)}:null}function Nc(e){const t=k_();for(const n of e)t.append(n);return t.snapshot()}function k_(){const e=new Map;return{append:n=>{const r=S_(n);if(r===null)return;if(r.phase==="attach"){const d={id:r.listenerId,service:r.service,target:r.target,actor:r.actor,authLens:r.authLens,attachedAt:n.at,deliveryCount:0,suppressedCount:0};r.owners!==void 0&&(d.owners=[...r.owners]),r.query!==void 0&&(d.query=r.query);const p=n.activity?.listenerId;typeof p=="string"&&(d.clientListenerId=p),e.set(r.listenerId,d);return}const o=e.get(r.listenerId);if(o===void 0)return;if(r.phase==="delivery"){o.deliveryCount+=1,o.lastDeliveryAt=n.at,r.owners!==void 0&&(o.owners=E_(o.owners,r.owners));return}if(r.phase==="suppressed"){o.suppressedCount+=1;return}e.delete(r.listenerId)},snapshot:()=>Object.freeze([...e.values()].map(n=>Object.freeze({...n}))),clear:()=>e.clear()}}function E_(e,t){const n=t.filter(s=>s.kind==="regions");return n.length===0?[...e??[]]:[...(e??[]).filter(s=>s.kind!=="regions"),...n]}function j_(e,t){return typeof e=="string"?e.startsWith(t):e.collection.startsWith(t)}const dp=Symbol("pyric/auth/target"),C_=Symbol("pyric.user.internal");function Y(e,t){return new H(e,`Firebase: ${t} (${e}).`)}const fp={PASSWORD:"password"},mo={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Di{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"?I_(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===fp.PASSWORD){const i=typeof n.email=="string"?n.email:"",o=typeof n.password=="string"?n.password:"";return new R_(i,o,s)}return new Di(r,s)}}function I_(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class R_ extends Di{email;secret;constructor(t,n,r=mo.EMAIL_PASSWORD){super(fp.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===mo.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===mo.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Ti extends Di{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 Ac(e,t){return t?new Ti(e,e):null}class En{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=En.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Ac(En.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Ti(En.PROVIDER_ID,En.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class jn{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=jn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Ac(jn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Ti(jn.PROVIDER_ID,jn.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class Cn{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=Cn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Ac(Cn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Ti(Cn.PROVIDER_ID,Cn.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const hp=[En.PROVIDER_ID,"apple.com",jn.PROVIDER_ID,Cn.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Oc(e,t=!1){const n=e[dp];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class N_{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 A_(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Xt(e){if(typeof e!="string"||e.length===0)throw Y("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw Y("auth/invalid-email","Error")}function tr(e){if(typeof e!="string"||e.length<6)throw Y("auth/weak-password","Password should be at least 6 characters")}function pp(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1}}}const O_=2166136261,$_=2654435769,P_=16777619;function nu(e,t){let n=t;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,P_);return n>>>0}function ru(e){return e.toString(16).padStart(8,"0")}function D_(e){const t=new TextEncoder().encode(e),n=new TextEncoder().encode([...e].reverse().join("")),r=nu(t,O_),s=nu(n,$_);return ru(r)+ru(s)}function T_(e){const t=Number.parseInt(e.slice(0,8),16),n=Number.parseInt(e.slice(8,16),16),r=t%360,s=40+n%80,i=(r+s)%360,o=60+t%16,a=45+n%16;return{hueStart:r,hueEnd:i,saturation:o,lightness:a}}function su(e){const n=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)[Symbol.iterator]().next();if(!n.done)return n.value.segment}function M_(e){const t=e.displayName?.trim();if(t){const r=su(t);if(r)return r.toUpperCase()}const n=e.email?.split("@")[0]?.trim();if(n){const r=su(n);if(r)return r.toUpperCase()}}function L_(e){return encodeURIComponent(e).replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}function U_(e){const t=D_(e.uid),{hueStart:n,hueEnd:r,saturation:s,lightness:i}=T_(t),o=`g${t}`,a=M_(e),l=e.pending===!0,u=a===void 0?"":`<text x="64" y="64" font-family="system-ui, -apple-system, sans-serif" font-size="56" fill="#fff" fill-opacity="${l?"0.55":"0.9"}" text-anchor="middle" dominant-baseline="central">${a}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><defs><linearGradient id="${o}" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="hsl(${n},${s}%,${i}%)"/><stop offset="100%" stop-color="hsl(${r},${s}%,${i}%)"/></linearGradient></defs><rect width="128" height="128" fill="url(#${o})"/>${u}${l?'<circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.25" stroke-width="6"/><circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.95" stroke-width="6" stroke-linecap="round" stroke-dasharray="44 308"><animateTransform attributeName="transform" type="rotate" from="0 64 64" to="360 64 64" dur="1s" repeatCount="indefinite"/></circle>':""}</svg>`}function B_(e){return`data:image/svg+xml,${L_(U_(e))}`}const F_=e=>B_(e),mp="(default)";function yp(e){return`${e}-default-rtdb`}function gp(e,t){return t!==void 0&&t.length>0&&(e===t||e===yp(t))}function bp(e){const t=q_(e,"Invalid Firebase Database URL");if(t.path!=="/")throw ci("Database URL must point to the root of a Firebase Database (not including a child path).");return t.instance}function q_(e,t){const n=z_(e);if(n.domain==="firebase.com")throw ci(`${n.host} is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`);const r=n.namespace;if((!r||r==="undefined")&&n.domain!=="localhost")throw ci("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");const s=n.host.toLowerCase(),i=n.pathSegments.length===0?"/":`/${n.pathSegments.join("/")}`;if(s.length===0||!Q_(r)&&s.split(":")[0]!=="localhost"||!X_(i))throw new Error(`${t} failed: url argument must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);const o=r!==n.subdomain?`?ns=${r}`:"";return{instance:{name:r,url:`${n.secure?"https://":"http://"}${s}/${o}`},host:s,path:i}}function $c(e){if(!G_.test(e))throw ci("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");return bp(`${e}.firebaseio.com`)}function V_(e){if(e===void 0)return;const t=e.trim();if(!(t===""||t.toLowerCase()==="default"))return/^[^./:?#]+$/.test(t)?$c(t):bp(e)}function da(e,t){return e===void 0?t??mp:e.name}function W_(e){const t=new Map;return{defaultKey:da(void 0,e.defaultName),keyOf:r=>da(r,e.defaultName),getOrCreate(r){let s=t.get(r);return s===void 0&&(s=e.create(r),t.set(r,s)),s},get:r=>t.get(r),delete:r=>t.delete(r),entries:()=>t.entries()}}function z_(e){let t=e,n="",r="",s="",i="",o=[],a=!0,l="https",u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),n=t.substring(0,Math.min(d,h)),d<h&&(o=H_(t.substring(d,h)));const f=K_(t.substring(Math.min(t.length,h)));u=n.indexOf(":"),u>=0?a=l==="https"||l==="wss":u=n.length;const p=n.slice(0,u);if(p.toLowerCase()==="localhost")r="localhost";else if(p.split(".").length<=2)r=p;else{const m=n.indexOf(".");s=n.substring(0,m).toLowerCase(),r=n.substring(m+1),i=s}return Object.prototype.hasOwnProperty.call(f,"ns")&&(i=f.ns),{host:n,domain:r,subdomain:s,secure:a,pathSegments:o,namespace:i}}function H_(e){const t=[];for(const n of e.split("/")){if(n.length===0)continue;let r=n;try{r=decodeURIComponent(n.replace(/\+/g," "))}catch{}t.push(r)}return t}function K_(e){const t={};e.charAt(0)==="?"&&(e=e.substring(1));for(const n of e.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2&&(t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]))}return t}const G_=/^[A-Za-z0-9][A-Za-z0-9-]*$/,J_=/[[\].#$/\u0000-\u001F\u007F]/,Y_=/[[\].#$\u0000-\u001F\u007F]/;function Q_(e){return e.length!==0&&!J_.test(e)}function X_(e){const t=e.replace(/^\/*\.info(\/|$)/,"/");return t.length!==0&&!Y_.test(t)}function ci(e){return new Error(`FIREBASE FATAL ERROR: ${e} `)}const Z_=new Set(["__proto__","prototype","constructor"]);function q(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(Z_.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 G(e){return e.length===0?"/":"/"+e.join("/")}function Lt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Lt(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Lt(r);return t}function fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(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)=>cn(s,t[i]));if(!fa(e)||!fa(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&cn(e[s],t[s]))}class eS{root={};snapshot(){return Lt(this.root)}restore(t){this.root=Lt(t)}read(t){const n=q(t);if(n.length>0&&n[0]===".info")return n.length===1?{connected:!0,serverTimeOffset:0}:n[1]==="connected"?!0:n[1]==="serverTimeOffset"?0:null;let s=this.root;for(const i of n){if(s===null||typeof s!="object"||Array.isArray(s))return null;const o=s;if(!Object.hasOwn(o,i))return null;s=o[i]}return fa(s)&&Object.keys(s).length===0?null:Lt(s)}write(t,n){const r=q(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Lt(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let a=0;a<r.length-1;a++){const l=r[a],u=Object.hasOwn(i,l)?i[l]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[l]=d,i=d}else i=u}const o=r[r.length-1];return n===null?(delete i[o],this.trim(r)):i[o]=Lt(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,o])=>({path:G(q(i)),value:o}));for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){const a=r[i].path,l=r[o].path;if(a===l)throw new Error(`multi-path update: duplicate path '${a}'.`);const u=a==="/"?"/":a+"/",d=l==="/"?"/":l+"/";if(a!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${a}'.`);if(l!=="/"&&a.startsWith(d))throw new Error(`multi-path update: '${a}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:o}of r){const a=this.write(i,o);s.push({path:i,prior:a})}return s}shallowUpdate(t,n){const r=[],s=q(t);for(const[i,o]of Object.entries(n)){const a=[...s,...q(i)],l=G(a),u=this.write(l,o);r.push({path:l,prior:u})}return r}trim(t){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=t.length-1;n>=1;n--){const r=t.slice(0,n),s=t[n-1];let i=this.root;for(let a=0;a<r.length-1;a++){const l=i[r[a]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const o=i[s];if(o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.keys(o).length===0){delete i[s];continue}return}}}const tS="12.13.0",nS=/[\[\].#$/\u0000-\u001F\u007F]/;function rS(e){return e.length!==0&&!nS.test(e)}function sS(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function iS(e){return e===".priority"||e===".value"||e===".sv"}function oS(e,t){ha(e,t,"set")}function ha(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(sS(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&&ha(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!iS(r)&&!rS(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 "]"`);ha(s,`${t}/${r}`,n)}}}function tn(e,t){return oS(e,t),vr(e)}function vr(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=vr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(Object.hasOwn(e,".value"))return vr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;if(n===".sv"){t[n]=r;continue}const s=vr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function aS(e){const t=[],n=(r,s)=>{if(r===null||typeof r!="object")return;const i=!Array.isArray(r);if(i&&Object.hasOwn(r,".priority")){const o=r[".priority"],a=typeof o=="object"&&o!==null&&".sv"in o;if(o!==null&&typeof o!="string"&&typeof o!="number"&&!a)throw new Error(`Firebase Database (${tS}) INTERNAL ASSERT FAILED: Invalid priority type found: ${typeof o}`);a||t.push({segments:s,priority:o})}if(i&&Object.hasOwn(r,".value")){n(r[".value"],s);return}for(const[o,a]of Object.entries(r))o.startsWith(".")||n(a,[...s,o])};return n(e,[]),t}function nn(e,t){const n=aS(e),r=n.find(s=>s.segments.length===0);return{priority:r?r.priority:t,inline:r!==void 0,nested:n.filter(s=>s.segments.length>0)}}function iu(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,".priority":t}:{".value":e,".priority":t}}function mt(e,t){const n=t.filter(s=>s.priority!==null);if(n.length===0||e===null)return e;let r=structuredClone(e);for(const{segments:s,priority:i}of n){if(s.length===0){r=iu(r,i);continue}let o=r;for(const u of s.slice(0,-1))o=typeof o=="object"&&o!==null&&!Object.hasOwn(o,".value")?o[u]:void 0;const a=s[s.length-1];if(typeof o!="object"||o===null||!Object.hasOwn(o,a))continue;const l=o;l[a]!==null&&(l[a]=iu(l[a],i))}return r}function cS(e,t=null){const n=nn(e,t),r=vr(e);return mt(r,[{segments:[],priority:n.priority},...n.nested])}function Ws(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>Ws(o));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const o of n)if(/^(0|[1-9]\d*)$/.test(o))s=Math.max(s,Number(o));else{r=!1;break}if(r&&s<2*n.length){const o=[];for(let a=0;a<=s;a++){const l=t[String(a)];o[a]=l===void 0?null:Ws(l)}return o}const i={};for(const[o,a]of Object.entries(t))i[o]=Ws(a);return i}function wp(e){return"/"+e.split("/").filter(Boolean).join("/")}function ou(e,t){return new Error(`Index not defined, add ".indexOn": "${t}", for path "${wp(e)}", to the rules`)}function lS(e){return e.limit===null&&e.bounds.length===0}function uS(e,t){return`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "${t}" at ${wp(e)} to your security rules for better performance.`}function dS(e){console.warn(`[${new Date().toISOString()}] @firebase/database:`,`FIREBASE WARNING: ${e} `)}function fS(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class hS{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=>G(q(n)))})}conflictsSince(t,n){const r=G(q(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>fS(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 nt(e){return e==="unsupported"?"unsupported":"deny"}function Ln(e){const t={engine:"rtdb",matchedPath:e.matchedPath,matchedRule:e.matchedRule,pathVariableBindings:e.pathVariableBindings,reason:e.reason,errorCode:e.errorCode};return e.trace!==void 0&&(t.rtdbTrace=e.trace),t}function Pe(e,t,n,r,s={}){const i={method:n,path:yt(r)};return s.data!==void 0&&(i.data=structuredClone(s.data)),s.query!==void 0&&(i.query=structuredClone(s.query)),{...Object.fromEntries(Object.entries(Ln(e)).filter(([,a])=>a!==void 0)),engine:"rtdb",auth:t===null?null:structuredClone(t),reasons:[...e.reasons],request:i}}function yt(e){return G(q(e))}class pS{sandbox;nextId=0;instanceField;constructor(t,n){this.sandbox=t,this.instanceField=n===void 0?{}:{instance:n}}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(t){return this.nextId+=1,`rtdb-${t}-${this.nextId.toString(36)}`}mutation(t,n,r,s={}){if(this.sandbox)try{pt(this.sandbox,qn({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,o={}){if(this.sandbox)try{let a;i&&(a=Ln(i));let l="user";o.origin&&(l=o.origin);let u=o.at;u===void 0&&(u=Te(this.sandbox).now()),pt(this.sandbox,Sh({service:"rtdb",...this.instanceField,method:n,path:yt(r),auth:t,result:s,origin:l,durationMs:o.durationMs,reasons:i?.reasons,rules:a,request:o.request,resourceBefore:o.resourceBefore,resourceAfter:o.resourceAfter,groupId:o.groupId,groupKind:o.groupKind,triggeredBy:o.triggeredBy,detail:o.detail,at:u}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{pt(this.sandbox,uw({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,method:n,path:yt(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),pt(this.sandbox,dw({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,phase:t,listenerId:n.id,target:{kind:i,path:yt(n.path),...s.query===void 0?{}:{query:s.query}},auth:r,result:s.result,size:s.size,sample:s.sample,reason:s.reason,error:s.error,triggeredBy:s.triggeredBy,detail:s.detail,reasons:s.reasons,rules:s.rules,owners:s.owners}),{service:"rtdb"})}catch{}}}class mS{values=new Map;get(t){return this.values.get(G(q(t)))??null}forChild(t){const n=q(t);return r=>this.get(G([...n,r]))}atOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of this.values)(i===n||i.startsWith(r))&&(s[i]=o);return s}clear(){this.values.clear()}clearAtOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n,r){if(this.clearAtOrBelow(t),n!==null){this.values.set(G(q(t)),n);return}r&&this.pruneMissingAncestors(t,r)}set(t,n){const r=G(q(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t,n){for(const r of t)this.clearAtOrBelow(r.path),r.value===null&&n&&this.pruneMissingAncestors(r.path,n)}pruneMissingAncestors(t,n){const r=q(t);for(let s=r.length-1;s>=0;s-=1){const i=G(r.slice(0,s));if(n(i))break;this.values.delete(i)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(G(q(n)),r)}}function Ut(e){if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("priority must be a valid Firebase priority (string, finite number, or null)")}const Wn=(...e)=>new Set(["Error",...e]),Pr=Wn("Boolean"),yS=Wn("Boolean","Number","String","Null","NullableSnapshot","Value","Auth","QueryValue","Mixed"),gS=Wn("Number","String","Value","Auth","QueryValue","Mixed"),bS=Wn("Number","String","Value","Auth","QueryValue","Mixed"),vp=Wn("Number","Value","Auth","QueryValue","Mixed"),Pc=Wn("String","Value","Auth","Mixed"),au=new Set(["String","Value","Auth"]),cu=new Set(["Snapshot","NullableSnapshot","Null"]);function wS(e,t){return e===t?e:cu.has(e)&&cu.has(t)?"NullableSnapshot":au.has(e)||au.has(t)?"Value":"Mixed"}function ue(e,t){return{code:e,message:t}}function vS(e){switch(e){case"==":case"===":case"!=":case"!==":return yS;case"<":case"<=":case">":case">=":case"+":return gS;default:return vp}}function xS(e,t,n){return e!=="+"&&e!=="-"&&e!=="*"&&e!=="/"&&e!=="%"?"Boolean":t==="Error"||n==="Error"?"Error":e!=="+"?"Number":t==="String"||n==="String"?"String":t==="Number"&&n==="Number"?"Number":"Value"}const gt=e=>ue("INVALID_ARGUMENT",e);function _t(e){return{returns:e,check:(t,n)=>n.length===0?null:gt(mn(t,0))}}function xr(e){return{returns:e,check(t,n){return n.length!==1?gt(mn(t,1)):Pc.has(n[0].type)?null:gt(ep(t))}}}const _S={returns:"Boolean",check(e,t){if(t.length===0)return null;if(t.length>1)return gt(tp);const n=t[0];return n.type==="Error"?null:n.type!=="Array"?gt(np):(n.elements??[]).every(r=>Pc.has(r))?null:gt(rp)}},SS={returns:"String",check(e,t){if(t.length!==2)return gt(mn(e,2));const n=t.findIndex(r=>!Pc.has(r.type));return n===-1?null:gt(la(n===0?1:2))}},kS={returns:"Boolean",check(e,t){if(t.length!==1)return gt(mn(e,1));const n=t[0].type;return n==="Regex"||n==="Error"?null:gt(sp)}},ES=new Map([["val",_t("Value")],["exists",_t("Boolean")],["isString",_t("Boolean")],["isNumber",_t("Boolean")],["isBoolean",_t("Boolean")],["parent",_t("Snapshot")],["getPriority",_t("Value")],["child",xr("Snapshot")],["hasChild",xr("Boolean")],["hasChildren",_S]]),lu=new Map([["contains",xr("Boolean")],["beginsWith",xr("Boolean")],["endsWith",xr("Boolean")],["replace",SS],["toLowerCase",_t("String")],["toUpperCase",_t("String")],["matches",kS]]),jS=new Map([["orderByKey","Boolean"],["orderByValue","Boolean"],["orderByPriority","Boolean"],["orderByChild","QueryValue"],["startAt","QueryValue"],["endAt","QueryValue"],["equalTo","QueryValue"],["limitToFirst","QueryValue"],["limitToLast","QueryValue"]]),CS="Invalid property access: target is not an object.";function xp(e,t){const n=()=>({kind:"error",error:ue("NO_SUCH_MEMBER",`No such method/property '${t}'.`)});switch(e){case"Error":return{kind:"error",error:null};case"Snapshot":case"NullableSnapshot":{const r=ES.get(t);return r?{kind:"method",method:r}:n()}case"String":case"Value":{const r=lu.get(t);return r?{kind:"method",method:r}:t==="length"?{kind:"property",type:"Number"}:n()}case"Auth":{const r=lu.get(t);return r?{kind:"method",method:r}:{kind:"property",type:"Auth"}}case"Query":{const r=jS.get(t);return r?{kind:"property",type:r}:n()}default:return{kind:"error",error:ue("NOT_AN_OBJECT",CS)}}}const IS=new Map([["auth","Auth"],["data","Snapshot"],["newData","Snapshot"],["root","Snapshot"],["now","Number"],["query","Query"]]),St={type:"Error"},Ie=e=>({type:e});function me(e,t){return e.errors.push(t),St}function Re(e,t){return t.type!=="Array"?t.type:(me(e,ue("UNEXPECTED_ARRAY","Unexpected array literal.")),"Error")}function Ee(e,t){return e.typeOf(t)}function Fe(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,Ee(e,r)),o=Re(r,Ee(n,r)),a=vS(s);return a.has(i)?a.has(o)?Ie(xS(s,i,o)):me(r,ue("INVALID_OPERAND",si(s,"right"))):me(r,ue("INVALID_OPERAND",si(s,"left")))}function uu(e,t,n){const r=this.args.ctx;let s=Re(r,Ee(e,r));return n.children.forEach((i,o)=>{const a=t.children[o].sourceString,l=Re(r,Ee(i,r));Pr.has(s)?Pr.has(l)?s=s==="Error"||l==="Error"?"Error":"Boolean":s=me(r,ue("INVALID_OPERAND",`Right operand of ${a} must be boolean.`)).type:s=me(r,ue("INVALID_OPERAND",`Left operand of ${a} must be boolean.`)).type}),Ie(s)}function du(e,t,n){const r=xp(Re(e,t),n);return r.kind==="error"?r.error?me(e,r.error):St:Ie(r.kind==="method"?"SnapshotMethod":r.type)}let yo;function RS(){if(yo)return yo;const e=os();return e.addOperation("literalString",{_nonterminal(...t){return t.length===1?t[0].literalString():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalString()},string(t){return $r(this.sourceString)}}),e.addOperation("typeOf(ctx)",{_nonterminal(...t){return t.length===1?Ee(t[0],this.args.ctx):St},_iter(){return St},_terminal(){return St},Ternary_ternary(t,n,r,s,i){const o=this.args.ctx,a=Re(o,Ee(t,o)),l=Re(o,Ee(r,o)),u=Re(o,Ee(i,o));return Pr.has(a)?l==="Error"||u==="Error"?St:Ie(wS(l,u)):me(o,ue("INVALID_OPERAND","condition of ? must be boolean."))},LogicalAnd_and:uu,LogicalOr_or:uu,Equality_strictEq:Fe,Equality_strictNeq:Fe,Comparison_gte:Fe,Comparison_lte:Fe,Comparison_gt:Fe,Comparison_lt:Fe,Equality_looseEq:Fe,Equality_looseNeq:Fe,Additive_add:Fe,Additive_sub:Fe,Multiplicative_mul:Fe,Multiplicative_div:Fe,Multiplicative_mod:Fe,UnaryExpr_not(t,n){const r=this.args.ctx,s=Re(r,Ee(n,r));return Pr.has(s)?Ie(s==="Error"?"Error":"Boolean"):me(r,ue("INVALID_OPERAND","! only operates on booleans."))},UnaryExpr_neg(t,n){const r=this.args.ctx,s=Re(r,Ee(n,r));return vp.has(s)?Ie(s==="Error"?"Error":"Number"):me(r,ue("INVALID_OPERAND","- only operates on numbers."))},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx,l=Re(a,Ee(t,a)),u=i.asIteration().children.map(m=>Ee(m,a)),d=r.sourceString,h=xp(l,d);if(h.kind==="error")return h.error?me(a,h.error):St;if(h.kind==="property")return me(a,ue("NOT_A_FUNCTION","Type error: Function call on target that is not a function."));const f=u.map(m=>d==="hasChildren"?m:Ie(Re(a,m)));if(f.some(m=>m.type==="Error"))return St;const p=h.method.check(d,f);return p?me(a,p):Ie(h.method.returns)},CallExpr_memberAccess(t,n,r){const s=this.args.ctx;return du(s,Ee(t,s),r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=this.args.ctx,o=Ee(t,i),a=r.literalString();if(a!==void 0)return du(i,o,a);const l=Re(i,o),u=Re(i,Ee(r,i));return l==="Error"||u==="Error"?St:l==="Auth"?bS.has(u)?Ie("Auth"):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access on 'auth' object.")):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access."))},Primary_paren(t,n,r){return Ee(n,this.args.ctx)},Array(t,n,r){const s=this.args.ctx;return{type:"Array",elements:n.asIteration().children.map(a=>Re(s,Ee(a,s)))}},number(t){return Ie("Number")},string(t){return Or(this.sourceString)?me(this.args.ctx,ue("PARSE_ERROR",ri)):Ie("String")},regex(t,n,r,s){const i=cp(n.sourceString);return i!==null?me(this.args.ctx,ue("INVALID_REGEX",i)):Ic(s.sourceString)?Ie("Regex"):me(this.args.ctx,ue("INVALID_REGEX",ip))},bool(t){return Ie("Boolean")},null(t){return Ie("Null")},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$")return s.pathVars.has(i.slice(1))?Ie("String"):me(s,ue("UNKNOWN_IDENTIFIER",zl(i)));if(i==="newData"&&s.context==="read")return me(s,ue("NEWDATA_IN_READ","newData is invalid in .read expressions."));const o=IS.get(i);return o?Ie(o):me(s,ue("UNKNOWN_IDENTIFIER",zl(i)))}}),yo=e,e}function NS(e,t,n=[]){const r=is(e);if(!r.ok)return[];const{match:s}=r,i={errors:[],context:t,pathVars:new Set(n.map(a=>a.startsWith("$")?a.slice(1):a))};let o;try{o=Re(i,RS()(s).typeOf(i))}catch(a){if(a instanceof RangeError)return[ue("PARSE_ERROR",ss)];throw a}return Pr.has(o)||me(i,ue("NOT_BOOLEAN","Expression must evaluate to a boolean.")),i.errors}const AS=/[.#$\[\]\u0000-\u001f\u007f]/,OS=/[.#$/\[\]\u0000-\u001f\u007f]/,$S=`Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`,PS="Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).",DS="Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.",TS="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.",MS="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().";function LS(e){const t=String(e);if(t==="$key"||t==="$priority"||t==="$value"){const n=t==="$key"?"orderByKey":t==="$priority"?"orderByPriority":"orderByValue";throw new Error(`orderByChild: "${t}" is invalid. Use ${n}() instead.`)}if(typeof e!="string"||e.length===0||AS.test(e))throw new Error(`orderByChild failed: path argument was an invalid path = "${t}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)}function _p(e,t){if(t===void 0)throw new Error(`${e} failed: value argument contains undefined `);if(typeof t=="function")throw new Error(`${e} failed: value argument contains a function `);if(typeof t=="number"&&!Number.isFinite(t))throw new Error(`${e} failed: value argument contains ${String(t)} `);if(!(t===null||typeof t!="object"))for(const[n,r]of Object.entries(t)){if(n!==".sv"&&(n.length===0||OS.test(n)))throw new Error(`${e} failed: value argument contains an invalid key (${n}) . ${$S}`);_p(e,r)}}function US(e){return e!==null&&typeof e=="object"&&Object.keys(e).length===1&&typeof e[".sv"]=="string"}function BS(e){if(e.orderBy?.kind==="child"&&e.orderBy.path.split("/").filter(Boolean).length===0)throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");for(const t of e.bounds){const n=t.value;switch(_p(t.kind,n),e.orderBy?.kind??"priority"){case"key":if(typeof n!="string")throw new Error(TS);if(t.key!==void 0)throw new Error(MS);break;case"priority":if(n!==null&&typeof n!="string"&&!(typeof n=="number"&&Number.isFinite(n))&&!US(n))throw new Error(PS);break;case"child":case"value":if(n!==null&&typeof n=="object")throw new Error(DS);break}}}function Dr(e){try{return e(),null}catch(t){return t instanceof Error?t.message:String(t)}}const Sp=On({orderByChild:je().nullable().optional(),orderByKey:Tt().nullable().optional(),orderByValue:Tt().nullable().optional(),orderByPriority:Tt().nullable().optional(),equalTo:Fs([je(),Sn(),Tt(),qs()]).optional(),limitToFirst:Sn().nullable().optional(),limitToLast:Sn().nullable().optional(),startAt:Fs([je(),Sn(),Tt(),qs()]).optional(),endAt:Fs([je(),Sn(),Tt(),qs()]).optional()});function FS(e){return e.orderByChild!=null?{kind:"child",path:e.orderByChild}:e.orderByKey===!0?{kind:"key"}:e.orderByValue===!0?{kind:"value"}:e.orderByPriority===!0?{kind:"priority"}:null}function qS(e){return[["startAt",e.startAt],["endAt",e.endAt],["equalTo",e.equalTo]].flatMap(([n,r])=>r==null?[]:[{kind:n,value:r}])}function kp(e){const t=Sp.strict().safeParse(e);if(!t.success)return`query is not a Realtime Database query: ${t.error.issues.map(o=>o.message).join("; ")}`;const n=t.data,r=n.orderByChild,s=r==null?null:Dr(()=>LS(r));if(s!==null)return s;if(n.orderByChild!=null&&n.orderByChild.split("/").filter(Boolean).length===0)return"orderByChild: cannot pass in empty path. Use orderByValue() instead.";if([n.orderByChild!=null,n.orderByKey===!0,n.orderByValue===!0,n.orderByPriority===!0].filter(Boolean).length>1)return"query names more than one of orderByChild, orderByKey and orderByValue.";if(n.equalTo!==void 0&&n.startAt!==void 0)return"equalTo: Starting point was already set (by another call to startAt, startAfter, or equalTo).";if(n.equalTo!==void 0&&n.endAt!==void 0)return"equalTo: Ending point was already set (by another call to endAt, endBefore, or equalTo).";if(n.limitToFirst!=null&&n.limitToLast!=null)return"query names both limitToFirst and limitToLast.";for(const[o,a]of[["limitToFirst",n.limitToFirst],["limitToLast",n.limitToLast]])if(a!=null&&(!Number.isInteger(a)||a<=0))return`query.${o} must be a positive integer.`;return Dr(()=>BS({orderBy:FS(n),bounds:qS(n),limit:null}))}const VS=On({operation:Ys(["read","write","validate"]),path:je().min(1).startsWith("/"),auth:Fs([On({uid:je(),tenant:je().optional(),token:Js(gs()).optional()}),qs()]),mockData:Js(gs()),newData:gs().optional(),updates:kh(On({path:je().min(1).startsWith("/"),value:gs()})).optional(),query:Sp.optional(),now:Sn().optional()});Ys(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);const WS=On({path:je(),kind:Ys(["read","write","validate"]),conditionText:je(),verdict:Ys(["ALLOW","DENY","ERROR","UNSUPPORTED"]),message:je().optional(),pathVariableBindings:Js(je()),instance:je().optional()});On({allowed:Tt(),unsupported:Tt().optional(),matchedPath:je(),matchedRule:je(),reason:je(),pathVariableBindings:Js(je()),trace:kh(WS)});const zS=["sub","aud","iss","auth_time","iat","exp"],HS=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce","sub","firebase"];function fu(e){const t=HS.filter(r=>Object.prototype.hasOwnProperty.call(e,r));if(t.length===0)return;const n=t.length>1?`Developer claims "${t.join('", "')}" are reserved and cannot be specified.`:`Developer claim "${t[0]}" is reserved and cannot be specified.`;throw new H("auth/reserved-claim",n)}function Ep(e){const t={...e};for(const n of zS)delete t[n];return t}function KS(e){return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoUrl:e.photoUrl,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerIds:e.providerUserInfo.map(t=>t.providerId)}}const GS=new Set(["password","phone","anonymous"]);function jp(e,t,n,r){const s={},i={user_id:e},o={};if(t!==null){t.displayName!==null&&(s.name=t.displayName),t.photoUrl!==null&&(s.picture=t.photoUrl),t.isAnonymous&&(i.provider_id="anonymous"),t.email!==null&&(i.email=t.email,i.email_verified=t.emailVerified,o.email=[t.email]),t.phoneNumber!==null&&(i.phone_number=t.phoneNumber,o.phone=[t.phoneNumber]);for(const a of t.providerIds)GS.has(a)||(o[a]=[t.uid])}return{...s,...n,...i,firebase:{identities:o,sign_in_provider:r}}}function hu(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function JS(e,t,n=Date.now()){const r=Math.floor(n/1e3),s=jp(e,null,t,null),i=hu(t.firebase)??{},o=s.firebase,a=hu(i.identities)??o.identities,l={...i,identities:a};return{sub:e,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:r,iat:r,exp:r+3600,...s,...t,user_id:t.user_id??s.user_id,firebase:l}}function YS(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function QS(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function XS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,".value")?e[".value"]:e}function ht(e,t,n){const r=XS(n);if(YS(e))return t;if(QS(e)){const o=e[".sv"].increment;return(typeof r=="number"?r:0)+o}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((o,a)=>ht(o,t,Array.isArray(r)?r[a]:void 0));let s;r!==null&&typeof r=="object"&&!Array.isArray(r)&&(s=r);const i={};for(const[o,a]of Object.entries(e)){const l=o===".value"?r:s?.[o];i[o]=ht(a,t,l)}return i}function pa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Cp(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function ZS(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object"||!Object.hasOwn(n,r))return;n=n[r]}return n}function Ip(e,t,n,r){if(n===void 0)return null;const s=ht(n,r,ZS(e,t));return cS(s)}const pu="\0__proto__";function li(e,t,n){if(Array.isArray(e))return e.map(s=>li(s,t,n));if(!pa(e))return e;const r={};for(const[s,i]of Object.entries(e))Cp(r,s===t?n:s,li(i,t,n));return r}function ek(e,t,n,r){const s=li(n,"__proto__",pu);return li(Ip(e,t,s,r),pu,"__proto__")}function tk(e,t,n,r,s,i){if(!s||s.length===0)return ma(e,n,Ip(e,t,r,i));let o=e;for(const a of s){const l=a.path.split("/").filter(Boolean);o=ma(o,l,ek(e,a.path,a.value,i))}return o}function ma(e,t,n){if(t.length===0)return n??null;const[r,...s]=t;if(!r)return e??null;const i=pa(e)&&Object.hasOwn(e,".value"),o=i?e[".value"]:e,a=pa(o);let l=null;a&&Object.hasOwn(o,r)&&(l=o[r]);const u=ma(l,s,n);if(u==null){if(!a)return e??null;const h={...o};return delete h[r],Object.keys(h).some(p=>p!==".priority")?(i&&Object.hasOwn(e,".priority")&&(h[".priority"]=e[".priority"]),h):null}const d=a?{...o}:{};return Cp(d,r,u),i&&a&&Object.hasOwn(e,".priority")&&(d[".priority"]=e[".priority"]),d}function Rp(e,t){try{const n=a_(e,t);return typeof n!="boolean"?{holds:!1,runtimeError:"Expression must evaluate to a boolean."}:{holds:n}}catch(n){if(n instanceof ee)return{holds:!1,runtimeError:n.message};throw n}}function ui(e,t,n,r,s){const i={path:e.path,kind:t,conditionText:n.raw,verdict:"UNSUPPORTED",pathVariableBindings:{...r}};if(s===void 0){const o=n.parsed.errors.map(a=>a.message).join("; ");i.message=o===""?"The simulator cannot evaluate this expression":`The simulator cannot evaluate this expression: ${o}`}else s.runtimeError!==void 0?(i.verdict="ERROR",i.message=s.runtimeError):i.verdict=s.holds?"ALLOW":"DENY";return i}function nk(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function rk(e,t){const n=Oi(e),r=JS(e.uid,n?.token??{},t),s={uid:e.uid,token:r},i=r.firebase,a=(typeof i=="object"&&i!==null?i:{}).sign_in_provider;return typeof a=="string"&&(s.provider=a),s}function mu(e,t,n,r,s,i,o,a){let l=null;const u=new Set;if(a&&a.length>0)for(const m of a)u.add(m.path.split("/").filter(Boolean).join("/"));else u.add(o.filter(Boolean).join("/"));const d=Array.from(u).map(m=>m.split("/").filter(Boolean));function h(m,g,b,w,x){if(b.exists()){const S=m.validate;if(S)if(!S.parsed.valid)i.push(ui(m,"validate",S,w,void 0)),l||(l={node:m,rule:S,bindings:w,unsupported:!0});else{const k=Rp(S,s(g,b,w));if(i.push(ui(m,"validate",S,w,k)),!k.holds)return{node:m,rule:S,bindings:w,runtimeError:k.runtimeError}}}const _=d.some(S=>S.length<=x.length&&S.every((k,I)=>k===x[I]))?nk(b):f(x);for(const S of _){const k=Ap(m,S);if(k===void 0)continue;const I=k.variable===void 0?w:{...w,[k.variable]:S},O=h(k.child,g.child(S),b.child(S),I,[...x,S]);if(O)return O}return null}function f(m){const g=new Set;for(const b of d)b.length>m.length&&m.every((x,v)=>x===b[v])&&g.add(b[m.length]);return g}return h(e,t,n,r,[])??l}function Np(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;const i=Ap(e,t[0]);if(i===void 0)return s;const o=i.variable===void 0?{...n}:{...n,[i.variable]:t[0]};return s.push(...Np(i.child,t.slice(1),o,r+1)),s}function sk(e){const t=e.path.split("/").filter(Boolean);return t[t.length-1]}function Ap(e,t){let n;for(const r of e.children){const s=sk(r);if(s===void 0)continue;if(s===t)return{child:r};s.startsWith("$")&&n===void 0&&(n={child:r,variable:s})}return n}function yu(e,t){let n="Validation rule evaluated to false";return e.unsupported?n=`Validation rule at '${e.node.path}' contains an expression the simulator cannot evaluate: ${e.rule.raw}. It was not evaluated; production may reject this write.`:e.runtimeError!==void 0&&(n=`Validation rule at '${e.node.path}' failed at evaluation: ${e.runtimeError}`),{success:!0,data:{allowed:!1,unsupported:e.unsupported===!0,matchedPath:e.node.path,matchedRule:e.rule.raw,reason:n,pathVariableBindings:e.bindings,trace:t}}}function ik(e,t){const n=e==="read"?t:void 0,r=n?.equalTo??null;return{orderByChild:n?.orderByChild??null,orderByKey:n?.orderByKey===!0,orderByValue:n?.orderByValue===!0,orderByPriority:n?.orderByPriority===!0,equalTo:r,limitToFirst:n?.limitToFirst??null,limitToLast:n?.limitToLast??null,startAt:n?.startAt??r,endAt:n?.endAt??r}}class ok{execute(t,n){const r=VS.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const s=r.data.query===void 0?null:kp(r.data.query);if(s!==null)return{success:!1,error:{code:"INVALID_INPUT",message:s,recoverable:!0}};const{operation:i,path:o,auth:a,mockData:l,newData:u,updates:d,query:h}=r.data,f=r.data.now??Date.now(),p=[];try{const m=o.split("/").filter(Boolean),g=t,b=Np(g,m,{}),w=new Ft(l,"/");let x=l;i!=="read"&&(x=tk(l,o,m,u,d,f));const v=new Ft(x,"/");let _=null;a&&(_=rk(a,f));const S=ik(i,h),k=($,C,N)=>{const A={...N};return{auth:_,data:$,newData:C,root:w,now:f,pathVariableBindings:A,query:S}};if(i==="validate"){const $=mu(g,w,v,{},k,p,m,d);if($)return yu($,p);const C=p[p.length-1],N=[...b].reverse().find(A=>A.node.validate!==void 0);return!C&&!N?{success:!1,error:{code:"NO_MATCHING_RULE",message:`No 'validate' rule found for path '${o}'`,recoverable:!0}}:{success:!0,data:{allowed:!0,matchedPath:C?.path??N.node.path,matchedRule:C?.conditionText??N.node.validate.raw,reason:"Validation rules evaluated to true",pathVariableBindings:C?.pathVariableBindings??N.pathVariableBindings,trace:p}}}let I;const O=new Map;for(const $ of b){const C=$.node[i];if(!C)continue;if(!C.parsed.valid){p.push(ui($.node,i,C,$.pathVariableBindings,void 0)),I||(I=$);continue}const N=m.slice(0,$.depth).join("/"),A=w.child(N),D=v.child(N),T=Rp(C,k(A,D,$.pathVariableBindings));if(p.push(ui($.node,i,C,$.pathVariableBindings,T)),T.runtimeError!==void 0&&O.set($,T.runtimeError),T.holds){if(i==="write"){const W=mu(g,w,v,{},k,p,m,d);if(W)return yu(W,p)}return{success:!0,data:{allowed:!0,matchedPath:$.node.path,matchedRule:C.raw,reason:"Rule expression evaluated to true",pathVariableBindings:$.pathVariableBindings,trace:p}}}}if(I){const $=I.node[i];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:I.node.path,matchedRule:$.raw,reason:`'${i}' rule at '${I.node.path}' contains an expression the simulator cannot evaluate: ${$.raw} — not evaluated; production may reject or allow this ${i}.`,pathVariableBindings:I.pathVariableBindings,trace:p}}}const P=[...b].reverse().find($=>$.node[i]!==void 0);if(P===void 0)return{success:!0,data:{allowed:!1,matchedPath:"",matchedRule:"",reason:`No '${i}' rule on '${o}' or its ancestors grants access; denied by default`,pathVariableBindings:b[b.length-1].pathVariableBindings,trace:p}};const R=P.node[i],E=O.get(P),j=E===void 0?"evaluated to false":`failed at evaluation: ${E}`;return{success:!0,data:{allowed:!1,matchedPath:P.node.path,matchedRule:R.raw,reason:`No '${i}' rule grants access; the deepest, at '${P.node.path}', ${j}`,pathVariableBindings:P.pathVariableBindings,trace:p}}}catch(m){return{success:!1,error:{code:"EVALUATION_ERROR",message:m instanceof Error?m.message:String(m),recoverable:!1}}}}}function Op(e,t,n=[]){try{const r=v_(e),s=r.valid?NS(e,t,n):r.errors,i=r.valid?h_(e,t):[];return{raw:e,parsed:{...r,valid:r.valid&&s.length===0,errors:s,warnings:i}}}catch(r){if(!(r instanceof RangeError))throw r;return{raw:e,parsed:{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ss}],warnings:[],referencedIdentifiers:[]}}}}function $p(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[o,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[o];if(l!==void 0)if(typeof l=="boolean"||typeof l=="string"||l===null)r[a]=Op(String(l),a,n);else{const u=JSON.stringify(l)??String(l);r[a]={raw:u,parsed:{raw:u,valid:!1,errors:[],warnings:[],referencedIdentifiers:[]}}}}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);const i=Kh(t,e);i.length>0&&(r.structure=i);for(const[o,a]of Object.entries(e)){if(o.startsWith(".")||mx.has(o)||typeof a!="object"||a===null||Array.isArray(a))continue;const l=t==="/"?`/${o}`:`${t}/${o}`,u=o.startsWith("$")?[...n,o]:[...n];r.children.push($p(a,l,u))}return r}function Dc(e){if(!e||typeof e!="object")throw new Error("Invalid rules JSON: expected an object");const t=e;if(!("rules"in t))throw new Error('Invalid rules JSON: missing top-level "rules" key');if(typeof t.rules!="object"||t.rules===null||Array.isArray(t.rules))throw new Error('Invalid rules JSON: "rules" must be an object');return $p(t.rules,"/",[])}function go(e){return e==="true"?!0:e==="false"?!1:e}function Pp(e){const t={};e.read&&(t[".read"]=go(e.read.raw)),e.write&&(t[".write"]=go(e.write.raw)),e.validate&&(t[".validate"]=go(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]]=Pp(n)}return t}function ak(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:Pp(e)}}function Tc(e,t){return new ok().execute(e,t)}function ck(e,t){let n=[e];for(const r of t){const s=[];for(const i of n)for(const o of i.children){const a=o.path.split("/").filter(Boolean),l=a[a.length-1];l&&(l===r||l.startsWith("$"))&&s.push(o)}if(n=s,n.length===0)break}return n}function Dp(e,t,n){return ck(e,t).filter(r=>r.indexOn?.some(s=>s===n||s.split("/").filter(Boolean).join("/")===n))}function lk(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:null}function uk(e){return e.kind==="value"?".value":e.path.split("/").filter(Boolean).join("/")}function dk(e){const t={orderByKey:e.orderBy?.kind==="key",orderByValue:e.orderBy?.kind==="value",orderByPriority:e.orderBy?.kind==="priority"};e.orderBy?.kind==="child"&&(t.orderByChild=e.orderBy.path);for(const n of e.bounds){const r=lk(n.value);n.kind==="equalTo"?t.equalTo=r:n.kind==="startAt"||n.kind==="startAfter"?t.startAt=r:(n.kind==="endAt"||n.kind==="endBefore")&&(t.endAt=r)}return e.limit?.kind==="limitToFirst"?t.limitToFirst=e.limit.n:e.limit?.kind==="limitToLast"&&(t.limitToLast=e.limit.n),t}function Je(e){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",Mc(t,e)}function Mc(e,t){return Object.assign(e,{denialContext:t})}class fk{clock;compiled=null;defaultPolicy="deny";constructor(t=new Eh){this.clock=t}setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=Dc(t)}hasRules(){return this.compiled!==null}missingQueryIndex(t,n){if(this.compiled===null||n.orderBy===null||n.orderBy.kind==="key"||n.orderBy.kind==="priority")return null;const r=uk(n.orderBy);return Dp(this.compiled,t.split("/").filter(Boolean),r).length>0?null:r}check(t,n,r){return this.evaluate(t,n,r).check}evaluate(t,n,r){if(t==="read"){if(n==="/.info"||n===".info")return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith("/.info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith(".info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]}}if(this.compiled===null)return this.defaultPolicy==="deny"?{check:"no-rule",reasons:["No RTDB rules loaded; default deny."],errorCode:"NO_MATCHING_RULE",errorMessage:"No RTDB rules loaded; default deny."}:{check:"allow",reasons:["No RTDB rules loaded; default allow."]};let i=null;r.auth!==null&&(i={uid:r.auth.uid,token:r.auth.token??{}},r.auth.tenant!==void 0&&(i.tenant=r.auth.tenant));let o=r.query;o===void 0&&r.querySpec!==void 0&&(o=dk(r.querySpec));const a=Tc(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates,query:o,now:r.now??this.clock.now()});return a.success?a.data.unsupported?{check:"unsupported",reasons:[`${a.data.matchedPath} ${t} UNSUPPORTED: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings,trace:a.data.trace}:{check:a.data.allowed?"allow":"deny",reasons:[`${a.data.matchedPath} ${t} ${a.data.allowed?"ALLOW":"DENY"}: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings,trace:a.data.trace}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class hk{tree=new eS;rules;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new mS;mutations=new hS;events;writeSubscribers=new Set;resetGeneration=0;clock;constructor(t,n){this.events=new pS(t,n),this.clock=t?Te(t):new Eh,this.rules=new fk(this.clock)}rulesSnapshot(){const t=[...this.priorities.entries()].map(([n,r])=>({segments:q(n),priority:r}));return mt(this.tree.snapshot(),t)}prioritiesBelow(t){const n=q(t),r=[];for(const[s,i]of this.priorities.entries()){const o=q(s);o.length>n.length&&n.every((l,u)=>o[u]===l)&&r.push({segments:o.slice(n.length),priority:i})}return r}unspecifiedIndexWarning(t,n){if(lS(n))return null;const r=this.rules.missingQueryIndex(t,n);return r===null?null:uS(t,r)}warnOnUnspecifiedIndex(t,n){if(n===void 0||Zr.isSilenced())return;const r=this.unspecifiedIndexWarning(t,n);r!==null&&dS(r)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Tp(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const i=gu(e),o=gu(t);return i!==o?i-o:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===!0?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function gu(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const pk=/^-?(0*)\d{1,10}$/,mk=-2147483648,yk=2147483647;function bu(e){if(pk.test(e)){const n=Number(e);if(n>=mk&&n<=yk)return n}return null}function di(e,t){if(e===t)return 0;const r=bu(e),s=bu(t),i=r!==null,o=s!==null;if(i){if(o){const l=r-s;return l===0?e.length-t.length:l}return-1}else if(o)return 1;return e<t?-1:1}function Tr(e,t,n,r=null){const s=e??{kind:"priority"};switch(s.kind){case"key":return t;case"value":return n;case"priority":return r;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const o=s.path.split("/").filter(l=>l.length>0);let a=n;for(const l of o){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function ln(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let i=Object.entries(e).map(([u,d])=>({key:u,value:d,priority:n(u)}));const o=t.orderBy?.kind==="key";i.sort((u,d)=>{if(o)return di(u.key,d.key);const h=Tr(t.orderBy,u.key,u.value,u.priority),f=Tr(t.orderBy,d.key,d.value,d.priority),p=Tp(h,f);return p!==0?p:di(u.key,d.key)});for(const u of t.bounds)i=i.filter(d=>gk(u,d,t.orderBy));const a=t.limit;if(a!==null){const u=a.n;if(a.kind==="limitToFirst")i=i.slice(0,u);else{if(u>=i.length)return i;i=i.slice(i.length-u)}}return i}function gk(e,t,n){const r=n?.kind==="key";let s;if(r)s=di(t.key,String(e.value));else{const u=Tr(n,t.key,t.value,t.priority);s=Tp(u,e.value)}const i=u=>di(t.key,u),o=s>0,a=s<0,l=s!==0;switch(e.kind){case"startAt":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0||i(u)>=0}case"startAfter":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0?!1:i(u)>0}case"endAt":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0||i(u)<=0}case"endBefore":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0?!1:i(u)<0}case"equalTo":{if(l)return!1;const u=e.key;return u===void 0||i(u)===0}}}function wu(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function bk(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&cn(n.value,s.value)})}function Lc(e,t){const n=new Error(`permission_denied at ${G(q(e))}: Client doesn't have permission to access the desired data.`);return n.code="PERMISSION_DENIED",Mc(n,t)}class wk{state;constructor(t){this.state=t}onValue(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:s});if(u.check!=="allow"){let d;s&&(d={query:s}),this.state.events.operation(t,"listen",n,nt(u.check),u,{at:l,durationMs:this.state.clock.now()-l,request:d,origin:"listener"});const h=Ln(u),f=Pe(u,t,"listen",n,d);if(this.state.events.listener("errored",{id:this.state.events.nextListenerId(),path:n},t,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:h}),i)return o&&o(),queueMicrotask(()=>{i(Lc(n,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(n,s),this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:u,at:l},i,o,a)}adminOnValue(t,n,r){return this.state.warnOnUnspecifiedIndex(t,r),this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l){const u=this.state.events.nextListenerId(),d=jh(l?.owner,l?.owners);this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:this.state.clock.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const h={id:u,auth:t,cb:r,path:n,query:s,cancelCallback:o,onCanceled:a,admin:i.origin==="admin",owners:d};if(this.state.valueListeners.add(h),this.state.events.listener("attach",h,t,{event:"value",result:"allow",detail:s?{query:s}:void 0,...s?{query:s}:{},owners:d}),s){const f=ln(this.state.tree.read(n),s,this.state.priorities.forChild(n));h.lastWindow=f,this.deliverInitial(h,{val:wu(f),exists:f.length>0,key:this.key(n),rows:f},{initial:!0,query:!0})}else{const f=this.snapshot(n);h.lastValue=f.val,h.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(h,f,{initial:!0})}return()=>{this.state.valueListeners.delete(h),this.state.events.listener("detach",h,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>G(q(r)));for(const r of this.state.valueListeners){const s=G(q(r.path));if(!n.some(a=>vk(s,a)))continue;if(r.query){const a=ln(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(bk(r.lastWindow??[],a)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=a,this.deliver(r,{val:wu(a),exists:a.length>0,key:this.key(r.path),rows:a},{query:!0});continue}const i=this.snapshot(r.path),o=this.state.priorities.stateAtOrBelow(r.path);if(cn(r.lastValue??null,i.val)&&r.lastPriorityState===o){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=o,this.deliver(r,i,{})}}off(t,n){const r=G(q(t));for(const s of[...this.state.valueListeners])G(q(s.path))===r&&(n!==void 0&&s.cb!==n||(this.state.valueListeners.delete(s),this.state.events.listener("detach",s,s.auth,{event:"value"})))}count(){return this.state.valueListeners.size}snapshot(t){const n=this.state.tree.read(t);return{val:n,exists:n!==null,key:this.key(t)}}key(t){const n=q(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){let s,i=!1;const o=Qs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:ya(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}deliverInitial(t,n,r){let s,i=!1;const o=Qs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});if(!i){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:ya(o)});return}this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}function ya(e){if(e!==void 0)return[e]}function vk(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function vu(e,t){const n=G(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of Object.entries(e))(i===n||i.startsWith(r))&&(s[i]=o);return s}function nr(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function vs(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}class xk{state;constructor(t){this.state=t}onChild(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:i});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,nt(d.check),d,{at:l,durationMs:this.state.clock.now()-l,origin:"listener",detail:{event:n},request:i?{query:i}:void 0});const h=Ln(d),f=Pe(d,t,"listen",r);if(this.state.events.listener("errored",{id:u,path:r},t,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:d.reasons},reasons:d.reasons,rules:h}),o)return a&&a(),queueMicrotask(()=>{o(Lc(r,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(r,i),this.attach(u,t,n,r,s,i,{origin:"listener",result:"allow",evaluation:d,at:l},o,a)}adminOnChild(t,n,r,s){return this.state.warnOnUnspecifiedIndex(n,s),this.attach(this.state.events.nextListenerId(),null,t,n,r,s,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l,u){const d=jh();this.state.events.operation(n,"listen",s,a.result,a.evaluation,{at:a.at,durationMs:this.state.clock.now()-a.at,request:o?{query:o}:void 0,origin:a.origin,detail:{event:r}});const h={id:t,auth:n,event:r,path:s,cb:i,spec:o,cancelCallback:l,onCanceled:u,admin:a.origin==="admin"};if(this.state.childListeners.add(h),this.state.events.listener("attach",h,n,{event:r,result:"allow",detail:o?{query:o}:void 0,...o?{query:o}:{},owners:d}),o){const f=ln(this.state.tree.read(s),o,this.state.priorities.forChild(s));if(h.lastWindow=f,h.lastPriorities=this.state.priorities.atOrBelow(s),r==="child_added")for(const{key:p,value:m}of f)this.deliver(h,{key:p,val:m,previousChildName:nr(f,p)},{initial:!0,query:!0})}else if(r==="child_added")for(const{key:f,val:p}of this.directChildren(s)){const m=this.directChildren(s);this.deliver(h,{key:f,val:p,previousChildName:vs(m,f)},{initial:!0})}return()=>{this.state.childListeners.delete(h),this.state.events.listener("detach",h,n,{event:r})}}off(t,n,r){const s=G(q(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||G(q(i.path))===s&&(r!==void 0&&i.cb!==r||(this.state.childListeners.delete(i),this.state.events.listener("detach",i,i.auth,{event:i.event})))}snapshotParents(){const t=new Map;for(const n of this.state.childListeners){const r=G(q(n.path));t.has(r)||t.set(r,{children:this.childStates(r),priorities:this.state.priorities.atOrBelow(r)})}return t}fanOut(t){if(this.state.childListeners.size===0)return;const n=new Map;for(const r of this.state.childListeners){if(r.spec){this.fanOutQuery(r);continue}const s=G(q(r.path)),i=n.get(s)??[];i.push(r),n.set(s,i)}for(const[r,s]of n){const i=t.get(r),o=i?.children??new Map,a=i?.priorities??{},l=this.childStates(r),u=[...l].map(([f,{val:p}])=>({key:f,val:p})),d=[...o].map(([f,{val:p}])=>({key:f,val:p})),h={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,{val:p,priority:m}]of l){const g=o.get(f);if(g===void 0){h.child_added.push({key:f,val:p,previousChildName:vs(u,f)});continue}const b=vs(u,f);cn(g.val,p)||h.child_changed.push({key:f,val:p,previousChildName:b}),g.priority!==m&&h.child_moved.push({key:f,val:p,previousChildName:b})}for(const[f,{val:p}]of o)l.has(f)||h.child_removed.push({key:f,val:p,previousChildName:vs(d,f),priorities:vu(a,G([...q(r),f]))});for(const f of s)for(const p of h[f.event])this.deliver(f,p,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:ln(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}childStates(t){const n=this.state.priorities.forChild(t);return new Map(this.directChildren(t).map(({key:r,val:s})=>[r,{val:s,priority:n(r)}]))}fanOutQuery(t){const n=t.lastWindow??[],r=ln(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=r;const s=t.lastPriorities??{};t.lastPriorities=this.state.priorities.atOrBelow(t.path);const i=new Map(n.map(l=>[l.key,l.value])),o=new Map(r.map(l=>[l.key,l.value])),a=[];if(t.event==="child_added")for(const l of r)i.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:nr(r,l.key)});else if(t.event==="child_changed")for(const l of r)i.has(l.key)&&!cn(i.get(l.key),l.value)&&a.push({key:l.key,val:l.value,previousChildName:nr(r,l.key)});else if(t.event==="child_removed")for(const l of n)o.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:nr(n,l.key),priorities:vu(s,G([...q(t.path),l.key]))});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=new Map(n.map(u=>[u.key,u]));for(const u of r){const d=l.get(u.key);if(!d)continue;const h=Tr(t.spec.orderBy,d.key,d.value,d.priority),f=Tr(t.spec.orderBy,u.key,u.value,u.priority);cn(h,f)||a.push({key:u.key,val:u.value,previousChildName:nr(r,u.key)})}}for(const l of a)this.deliver(t,l,{query:!0})}deliver(t,n,r){let s,i=!1;const o=Qs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:{key:n.key,val:n.val,previousChildName:n.previousChildName},detail:r,owners:ya(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}class _k{state;children;publish;constructor(t,n,r){this.state=t,this.children=n,this.publish=r}adminSet(t,n){Ut(n);const r=this.state.tree.read(t);if(r===null)return;const s=this.state.clock.now(),i=this.state.priorities.get(t);this.state.events.operation(null,"setPriority",t,"not-applicable",void 0,{at:s,origin:"admin",request:{data:n},resourceBefore:{data:r,exists:!0},resourceAfter:{data:r,exists:!0},detail:{admin:!0,priority:n,priorPriority:i}});const o=this.children.snapshotParents();this.state.priorities.set(t,n),this.publish([t],o),this.state.events.commit(null,"setPriority",t,{data:n,priorState:i,nextState:n,replay:{requestTime:s},detail:{admin:!0,priority:n,priorPriority:i}}),this.state.notifyWrite()}validate(t,n,r){Ut(r);const s=this.evaluation(t,n,r);if(s.check!=="allow")throw Je(Pe(s,t,"setPriority",n,{data:r}))}evaluation(t,n,r){const s=this.state.tree.read(n);return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:mt(s,[{segments:[],priority:r},...this.state.prioritiesBelow(n)])})}set(t,n,r){Ut(r);const s=this.state.tree.read(n),i=this.state.clock.now(),o=this.evaluation(t,n,r),a=this.state.priorities.get(n),l={at:i,durationMs:this.state.clock.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:a}};if(o.check!=="allow")throw this.state.events.operation(t,"setPriority",n,nt(o.check),o,l),Je(Pe(o,t,"setPriority",n,{data:r}));if(this.state.events.operation(t,"setPriority",n,"allow",o,l),this.state.events.commit(t,"setPriority",n,{data:r,priorState:a,nextState:s===null?null:r,replay:{requestTime:i},detail:{priority:r,priorPriority:a}}),s===null)return;const u=this.children.snapshotParents(),d=a!==r;this.state.priorities.set(n,r),this.publish([n],u),d&&this.state.events.mutation(t,"setPriority",yt(n),{before:a,after:r,detail:{priorityMetadata:!0}}),this.state.notifyWrite()}}function xu(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function pr(e,t,n,r,s=!1){const i=q(t);for(let a=0;a<i.length;a++){const l=G(i.slice(0,a)),u=e.tree.read(l);if(u!==null&&typeof u!="object"){const d=e.priorities.get(l);return{overwrittenAncestor:{path:l,state:mt(u,[{segments:[],priority:d}])}}}}const o=e.prioritiesBelow(t);return o.length>0?{priorExport:mt(n,[{segments:[],priority:r},...o])}:s&&r!==null?{priorPriority:r}:{}}const Sk=/\broot\b/,kk=/\bdata\b/,Ek=/\bparent\b/;function jk(e,t){return e===t||e==="/"||t==="/"?!0:t.startsWith(`${e}/`)||e.startsWith(`${t}/`)}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ck(e,t){if(!t.startsWith(".")&&Object.hasOwn(e,t)&&_u(e[t]))return e[t];for(const[n,r]of Object.entries(e))if(n.startsWith("$")&&_u(r))return r}function Ik(e,t,n){return typeof e!="string"?!1:Sk.test(e)?!0:kk.test(e)?Ek.test(e)||e.includes("[")?!0:n.some(r=>jk(t,r)):!1}function Su(e,t,n){const r=q(t);let s=e;for(let i=0;i<=r.length&&s!==void 0;i++){const o=G(r.slice(0,i));if(Ik(s[".read"],o,n))return!0;i<r.length&&(s=Ck(s,r[i]))}return!1}class Uc{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new _k(t,r,(s,i)=>this.changed(s,i))}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t)){this.state.tree.write(n,tn(ht(r,this.state.clock.now()),n==="/"?"":n));const{priority:s,nested:i}=nn(r,null);this.state.priorities.replace(n,this.state.tree.read(n)===null?null:s),this.storeNestedPriorities(n,i)}this.state.mutations.mark("/"),this.cancelDeniedListeners(["/"]),this.state.notifyWrite()}setRules(t){t===null?this.state.activeRules=null:this.state.activeRules=structuredClone(t),this.state.rules.setRules(t),this.cancelDeniedListeners(),this.state.notifyWrite()}setDefaultPolicy(t){this.state.rules.setDefaultPolicy(t),this.cancelDeniedListeners(),this.state.notifyWrite()}getActiveRules(){const t=this.state.activeRules===null;let n=null;return t||(n=structuredClone(this.state.activeRules)),n}snapshotState(){return this.state.tree.snapshot()}adminGet(t){const n=this.state.tree.read(t);return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=this.state.rules.missingQueryIndex(t,n);if(r!==null)throw this.state.events.operation(null,"get",t,"error",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},detail:{failure:"missing-index"}}),ou(t,r);const s=ln(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},resourceBefore:{data:xu(s),exists:s.length>0}}),s}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){const i=this.state.clock.now(),o=this.state.tree.read(t),a=tn(ht(n,i,o),t==="/"?"":t),l=nn(n,r);r=l.priority,s||=l.inline,Ut(r);const u=a===null?"remove":"set";this.state.events.operation(null,u,t,"not-applicable",void 0,{at:i,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:o,exists:o!==null},resourceAfter:{data:a,exists:a!==null}});const d=this.children.snapshotParents(),h=this.state.priorities.get(t),f=pr(this.state,t,o,h);this.state.tree.write(t,a),this.state.priorities.replace(t,a===null?null:r,g=>this.state.tree.read(g)!==null),this.storeNestedPriorities(t,l.nested),this.changed([t],d);const p=this.state.tree.read(t),m=s||h!==null;this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:o,nextState:p,replay:{requestTime:i},detail:{admin:!0,...m?{priority:r,priorPriority:h}:{},...f}}),this.state.notifyWrite()}adminUpdate(t,n){const r=this.state.clock.now(),s=this.state.tree.read(t),i=this.state.priorities.get(t),o=pr(this.state,t,s,i,!0),a=this.resolvePatch(t,n,r),l=this.patchPriorities(t,n),u=Object.keys(n).some(p=>p.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{at:r,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:u?{admin:!0,multiPath:!0,paths:Object.keys(a)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const d=this.children.snapshotParents();u?this.state.tree.multiUpdate(a):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(a).map(([p,m])=>[q(p).at(-1),m])));const h=p=>this.state.tree.read(p)!==null;this.state.priorities.applyUpdate(Object.entries(a).map(([p,m])=>({path:p,value:m})),h),this.storePatchPriorities(l),this.changed(Object.keys(a),d);const f=u?{admin:!0,multiPath:!0,paths:Object.keys(a),...o}:{admin:!0,multiPath:!1,keys:Object.keys(n),...o};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:f}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=this.state.clock.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),Je(Pe(i,t,"get",n));return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=this.state.clock.now(),i=this.readEvaluation(t,n,r);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r}}),Je(Pe(i,t,"get",n,{query:r}));const o=this.state.rules.missingQueryIndex(n,r);if(o!==null)throw this.state.events.operation(t,"get",n,"error",void 0,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},detail:{failure:"missing-index"}}),ou(n,o);const a=ln(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},resourceBefore:{data:xu(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){Ut(s),this.setInternal(t,n,r,"set",s,!0)}remove(t,n){this.setInternal(t,n,null,"remove",null,!1)}setPriority(t,n,r){this.priorityWrites.set(t,n,r)}validatePriority(t,n,r){this.priorityWrites.validate(t,n,r)}validateRead(t,n,r){const s=this.readEvaluation(t,n,r);if(s.check!=="allow")throw Je(Pe(s,t,"get",n,r?{query:r}:{}))}validateSet(t,n,r,s=null){const{evaluation:i,resolved:o}=this.setCheck(t,n,r,s);if(i.check!=="allow")throw Je(Pe(i,t,"onDisconnect",n,{data:o}))}validateUpdate(t,n,r){const s=this.updateCheck(t,n,r);if(s!==null)throw Je(Pe(s.evaluation,t,"onDisconnect",s.path,{data:s.value}))}registerDisconnect(t,n){const r=this.state.clock.now(),s=`onDisconnect.${n.kind}`,i=n.kind==="set"?n.value:n.kind==="update"?n.values:null,o=n.kind==="set"&&n.priority!==null?{priority:n.priority}:void 0;let a,l=null;if(n.kind==="update"){if(Object.keys(n.values).length===0)return;const d=this.updateEvaluations(t,n.path,n.values),h=d.find(f=>f.evaluation.check!=="allow");a=(h??d.at(-1)).evaluation,h!==void 0&&(l={path:h.update.path,data:h.update.value})}else{const d=n.kind==="set"?n.value:null,h=this.setCheck(t,n.path,d,n.kind==="set"?n.priority:null);a=h.evaluation,a.check!=="allow"&&(l={path:n.path,data:h.resolved})}const u={at:r,durationMs:this.state.clock.now()-r,request:{data:i,resourceData:i},detail:o};if(l!==null)throw this.state.events.operation(t,s,n.path,nt(a.check),a,u),Je(Pe(a,t,"onDisconnect",l.path,{data:l.data}));this.state.events.operation(t,s,n.path,"allow",a,u)}setCheck(t,n,r,s){const i=this.state.clock.now(),o=tn(ht(r,i,this.state.tree.read(n)),n==="/"?"":n),a=nn(r,s);Ut(a.priority);const l=mt(o,[{segments:[],priority:a.priority},...a.nested]);return{evaluation:this.writeEvaluation(t,n,l,i),resolved:o}}updateCheck(t,n,r){if(Object.keys(r).length===0)return null;for(const{update:s,evaluation:i}of this.updateEvaluations(t,n,r))if(i.check!=="allow")return{evaluation:i,path:s.path,value:s.value};return null}updateEvaluations(t,n,r){const s=this.state.clock.now(),i=this.state.rulesSnapshot(),o=this.patchPriorities(n,r),a=Object.entries(r).map(([l,u])=>{const d=G([...q(n),...q(l)]),h=tn(ht(u,s,this.state.tree.read(d)),d);return{path:d,value:mt(h,o.get(d)??[])}});return a.map(l=>({update:l,evaluation:this.state.rules.evaluate("write",l.path,{auth:t,mockData:i,newData:l.value,updates:a,now:s})}))}update(t,n,r){if(Object.keys(r).length===0)return;const s=this.state.clock.now(),i=this.resolvePatch(n,r,s),o=this.patchPriorities(n,r),a=Object.keys(r).some(v=>v.includes("/")),l=this.state.rulesSnapshot(),u=Object.entries(i).map(([v,_])=>({path:v,value:_})),d=u.map(v=>({path:v.path,value:mt(v.value,o.get(v.path)??[])})),h=Object.fromEntries(Object.entries(i).map(([v,_])=>[q(v).at(-1),_])),f=this.state.events.nextGroupId("update"),p=[];for(const[v,_]of u.entries()){const S=this.state.clock.now(),k=this.state.tree.read(_.path),I=this.state.rules.evaluate("write",_.path,{auth:t,mockData:l,newData:d[v].value,updates:d,now:s}),O={at:S,durationMs:this.state.clock.now()-S,origin:"batch",request:{data:_.value,resourceData:_.value},resourceBefore:{data:k,exists:k!==null},resourceAfter:{data:_.value,exists:_.value!==null},groupId:f,groupKind:"batch",detail:a?{multiPath:!0,rootPath:yt(n)}:{multiPath:!1,rootPath:yt(n),key:q(_.path).at(-1)}};if(I.check!=="allow"){const P={...O,detail:{...O.detail,patch:r}};throw this.state.events.operation(t,"update",_.path,nt(I.check),I,P),Je(Pe(I,t,"update",_.path,{data:_.value}))}p.push(()=>this.state.events.operation(t,"update",_.path,"allow",I,O))}for(const v of p)v();const m=this.state.tree.read(n),g=this.state.priorities.get(n),b=pr(this.state,n,m,g,!0),w=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,h),this.state.priorities.applyUpdate(u,v=>this.state.tree.read(v)!==null),this.storePatchPriorities(o),this.changed(Object.keys(i),w);const x=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:x,groupId:f,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i),...b}:{multiPath:!1,keys:Object.keys(h),...b}}),this.state.events.mutation(t,"update",yt(n),{after:a?i:h,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(h)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,o){const a=this.state.clock.now(),l=tn(ht(r,a,this.state.tree.read(n)),n==="/"?"":n),u=nn(r,i);i=u.priority,o||=u.inline,Ut(i);const d=this.state.tree.read(n),h=this.state.priorities.get(n),f=this.state.clock.now(),p=mt(l,[{segments:[],priority:i},...u.nested]),m=this.writeEvaluation(t,n,p,a),g={at:f,durationMs:this.state.clock.now()-f,request:{data:r,resourceData:r},resourceBefore:{data:d,exists:d!==null},resourceAfter:{data:l,exists:l!==null}};if(m.check!=="allow"){const k=o?{...g,detail:{priority:i}}:g;throw this.state.events.operation(t,s,n,nt(m.check),m,k),Je(Pe(m,t,s,n,{data:r}))}this.state.events.operation(t,s,n,"allow",m,g);const b=this.children.snapshotParents(),w=pr(this.state,n,d,h);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i,k=>this.state.tree.read(k)!==null),this.storeNestedPriorities(n,u.nested),this.changed([n],b);const x=this.state.tree.read(n),v=x===null?"remove":s,S={...o||h!==null?{priority:i,priorPriority:h}:{},...w};this.state.events.commit(t,v,n,{data:r,priorState:d,nextState:x,replay:{requestTime:a},detail:Object.keys(S).length>0?S:void 0}),this.state.events.mutation(t,v,yt(n),{before:d,after:x}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const o=G([...q(t),...q(s)]);return[o,tn(ht(i,r,this.state.tree.read(o)),o)]}))}changed(t,n){this.state.mutations.mark(t),this.cancelDeniedListeners(t),this.values.fanOut(t),this.children.fanOut(n)}cancelDeniedListeners(t){if(this.state.valueListeners.size===0&&this.state.childListeners.size===0)return;let n,r;if(t!==void 0){if(this.state.activeRules===null)return;const l=t.map(d=>G(q(d)));if(l.length===0)return;const u=this.state.activeRules.rules;n=[...this.state.valueListeners].filter(d=>!d.admin&&Su(u,d.path,l)),r=[...this.state.childListeners].filter(d=>!d.admin&&Su(u,d.path,l))}else n=[...this.state.valueListeners].filter(l=>!l.admin),r=[...this.state.childListeners].filter(l=>!l.admin);if(n.length===0&&r.length===0)return;const s=this.state.rulesSnapshot(),i=[],o=new Map;for(const l of n){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.query});if(u.check==="allow")continue;this.state.valueListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.query?{query:l.query}:void 0,detail:{revoked:!0}});const d=Ln(u);this.state.events.listener("errored",l,l.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,Pe(u,l.auth,"listen",l.path)),i.push(l)}const a=[];for(const l of r){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.spec});if(u.check==="allow")continue;this.state.childListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.spec?{query:l.spec}:void 0,detail:{event:l.event,revoked:!0}});const d=Ln(u);this.state.events.listener("errored",l,l.auth,{event:l.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,Pe(u,l.auth,"listen",l.path)),a.push(l)}for(const l of[...i,...a]){try{l.onCanceled&&l.onCanceled()}catch{}try{l.cancelCallback&&l.cancelCallback(Lc(l.path,o.get(l)))}catch{}}}readEvaluation(t,n,r){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:r})}writeEvaluation(t,n,r,s){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:r,now:s})}storeNestedPriorities(t,n){for(const{segments:r,priority:s}of n){const i=G([...q(t),...r]);this.state.priorities.set(i,this.state.tree.read(i)===null?null:s)}}patchPriorities(t,n){const r=new Map;for(const[s,i]of Object.entries(n)){const{priority:o,inline:a,nested:l}=nn(i,null),u=G([...q(t),...q(s)]);r.set(u,a?[{segments:[],priority:o},...l]:l)}return r}storePatchPriorities(t){for(const[n,r]of t){const s=r.find(i=>i.segments.length===0);s&&this.state.priorities.set(n,this.state.tree.read(n)===null?null:s.priority),this.storeNestedPriorities(n,r.filter(i=>i.segments.length>0))}}}function Rk(e){const t=e!==null;let n=!1;if(t){const r=typeof e=="object",s=Array.isArray(e);r&&(s||(n=!0))}if(n){const r=e,i=r[".pyricRtdbPersistence"]===1,o="data"in r;let a=!1;i&&o&&(a=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let h=!1;if(u&&d){const p=typeof l=="object",m=Array.isArray(l);p&&(m||(h=!0))}let f=!1;if(a&&h&&(f=!0),f){const p={},m=Object.entries(l);for(const[S,k]of m){const I=typeof k=="string",O=typeof k=="number";let P=!1;O&&Number.isFinite(k)&&(P=!0);let R=!1;I&&(R=!0),P&&(R=!0),R&&(p[S]=k)}const g=r.data;let b=null;g!==void 0&&g!==null&&(b=g);const x=r.rules;let v=null;if(x!==void 0&&x!==null){const k=typeof x=="object",I=Array.isArray(x);let O=!1;if(k&&(I||(O=!0)),O){const P=x;if("rules"in P){const E=P.rules;if(E!==null&&E!==void 0){const C=typeof E=="object",N=Array.isArray(E);let A=!1;C&&(N||(A=!0)),A&&(v={rules:E})}}}}return{data:b,priorities:p,rules:v}}}return{data:e,priorities:{},rules:null}}class Nk{state;values;children;writes;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.writes=new Uc(t,n,r)}exportTree(){return this.state.tree.snapshot()}exportState(){const t=this.state.activeRules!==null,n={".pyricRtdbPersistence":1,data:this.state.tree.snapshot(),priorities:Object.fromEntries(this.state.priorities.entries())};return t&&(n.rules=structuredClone(this.state.activeRules)),n}restore(t){const n=this.children.snapshotParents(),r=Rk(t);let s={};r.data!==null&&r.data!==void 0&&(s=r.data),r.rules!==null?(this.state.rules.setRules(r.rules),this.state.activeRules=structuredClone(r.rules)):(this.state.rules.setRules(null),this.state.activeRules=null),this.state.tree.restore(s),this.state.priorities.restore(r.priorities),this.state.mutations.mark("/"),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(t=!1){this.state.resetGeneration+=1;const n=this.children.snapshotParents();this.state.tree.restore({}),this.state.priorities.restore({}),this.state.mutations.mark("/"),t||(this.state.rules.setRules(null),this.state.activeRules=null),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const ku="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let Eu=0;const Zt=new Array(12).fill(0);function Ak(e=Date.now()){const t=e===Eu;Eu=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=ku.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(t){let i;for(i=11;i>=0&&Zt[i]===63;i--)Zt[i]=0;if(i<0)for(let o=0;o<12;o++)Zt[o]=Math.floor(Math.random()*64);else Zt[i]=(Zt[i]??0)+1}else for(let i=0;i<12;i++)Zt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ku.charAt(Zt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function Ok(e){return Mc(new Error("permission_denied"),e)}class $k{state;children;writes;constructor(t,n,r,s=new Uc(t,n,r)){this.state=t,this.children=r,this.writes=s}run(t,n,r,s){const i=s?.applyLocally!==!1,o=s?.admin===!0,a=q(n),l=a.length===0?null:a[a.length-1];let u=null,d=null,h,f=0,p=!1;do{f+=1;const E=this.state.mutations.begin();u=this.state.tree.read(n),d=o||this.canRead(t,n)?u:null;const j=d===null?null:Ws(Lt(d));let $=!1;try{h=r(j),$=this.state.mutations.conflictsSince(E,n)}finally{this.state.mutations.release(E)}if(!$||h===void 0){p=!0;break}}while(f<25);if(!p)throw new Error("maxretry");const m=this.state.events.nextGroupId("transaction");if(h===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:o?"admin":"transaction",groupId:m,groupKind:"transaction",resourceBefore:{data:d,exists:d!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:d,key:l};const g=this.state.clock.now(),b=tn(ht(h,g,u),n==="/"?"":n),w=this.state.priorities.get(n),x=nn(h,w);Ut(x.priority);const v=b===null?null:x.priority,_=this.state.clock.now();let S;if(!o){const E=mt(b,[{segments:[],priority:v},...x.nested]);if(S=this.state.rules.evaluate("write",n,{auth:t,mockData:this.state.rulesSnapshot(),newData:E,now:g}),S.check!=="allow")throw this.state.events.operation(t,"transaction",n,nt(S.check),S,{at:_,durationMs:this.state.clock.now()-_,origin:"transaction",request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction",detail:v!==null?{priority:v}:void 0}),Ok(Pe(S,t,"transaction",n,{data:h}))}const k=E=>this.state.tree.read(E)!==null,I=pr(this.state,n,u,w,!0),O=o?"not-applicable":"allow",P=o?"admin":"transaction";this.state.events.operation(t,"transaction",n,O,S,{at:_,durationMs:this.state.clock.now()-_,origin:P,request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"});const R=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.writes.changed([n],R),this.finishEvents(t,n,h,u,b,m,g,i,o,I),this.state.notifyWrite(),{committed:!0,val:b,key:l}}storeNestedPriorities(t,n,r){for(const{segments:s,priority:i}of n){const o=G([...t,...s]);this.state.priorities.set(o,r(o)?i:null)}}canRead(t,n){return this.state.rules.evaluate("read",n,{auth:t,mockData:this.state.rulesSnapshot(),now:this.state.clock.now()}).check==="allow"}finishEvents(t,n,r,s,i,o,a,l,u,d){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:o,groupKind:"transaction",replay:{requestTime:a},detail:{...u?{admin:!0}:{},committed:!0,applyLocally:l,...d}}),this.state.events.mutation(t,"transaction",yt(n),{before:s,after:i,detail:{committed:!0}})}}function ga(e){return e.split("/").find(t=>t.length>0)===".info"}function Pk(e,t){if(ga(t))throw new Error(`${e} failed = Can't modify data under /.info/`)}function Dk(){const e=new Error("INVALID_PARAMETERS: Invalid token in path");return e.code="INVALID_PARAMETERS",e}const Tk=/[[\].#$/\u0000-\u001F\u007F]/;function Mk(e,t=q){for(const r of Object.keys(e)){const s=t(r);s.forEach((i,o)=>{if(!(i===".priority"&&o===s.length-1)&&(i.length===0||Tk.test(i)))throw new Error(`update failed: values argument contains an invalid key (${i}) in path /${s.join("/")}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)})}const n=Object.keys(e).map(r=>`/${t(r).join("/")}`);for(let r=0;r<n.length;r++)for(let s=r+1;s<n.length;s++){const i=n[r],o=n[s],[a,l]=i.length<=o.length?[i,o]:[o,i];if(a===l||a==="/"||l.startsWith(`${a}/`))throw new Error(`update failed: values argument contains a path ${a} that is ancestor of another path ${l}`)}}function Lk(e,t){const n=e.replace(/^\/*\.info(\/|$)/,"/"),r=e.length===0,s=/[.#$[\]\u0000-\u001F\u007F]/.test(n);if(r||s)throw new Error(`child failed: path argument was an invalid path = "${e}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)}function Ce(e,t){const n=t===void 0?[e]:Object.keys(t).map(r=>`${e}/${r}`);if(ga(e)||n.some(ga))throw Dk()}class Uk{state;values;children;writes;transactions;persistence;constructor(t,n){this.state=new hk(t,n),this.values=new wk(this.state),this.children=new xk(this.state),this.writes=new Uc(this.state,this.values,this.children),this.transactions=new $k(this.state,this.values,this.children,this.writes),this.persistence=new Nk(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){Ce(t),this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){Ce(t),this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){Ce(t,n),this.writes.adminUpdate(t,n)}adminRemove(t){Ce(t),this.writes.adminRemove(t)}adminSetPriority(t,n){Ce(t),this.writes.adminSetPriority(t,n)}get(t,n){return this.writes.get(t,n)}getQuery(t,n,r){return this.writes.getQuery(t,n,r)}unspecifiedIndexWarning(t,n){return this.state.unspecifiedIndexWarning(t,n)}set(t,n,r){Ce(n),this.writes.set(t,n,r)}setWithPriority(t,n,r,s){Ce(n),this.writes.setWithPriority(t,n,r,s)}update(t,n,r){Ce(n,r),this.writes.update(t,n,r)}remove(t,n){Ce(n),this.writes.remove(t,n)}setPriority(t,n,r){Ce(n),this.writes.setPriority(t,n,r)}validateRead(t,n,r){this.writes.validateRead(t,n,r)}validatePriority(t,n,r){Ce(n),this.writes.validatePriority(t,n,r)}registerDisconnect(t,n){n.kind==="update"?Ce(n.path,n.values):Ce(n.path),this.writes.registerDisconnect(t,n)}validateSet(t,n,r,s=null){Ce(n),this.writes.validateSet(t,n,r,s)}validateUpdate(t,n,r){Ce(n,r),this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,o,a){return this.values.onValue(t,n,r,s,i,o,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return Ce(n),this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,o,a){return this.children.onChild(t,n,r,s,i,o,a)}adminOnChild(t,n,r,s){return this.children.adminOnChild(t,n,r,s)}off(t,n,r){(n===void 0||n==="value")&&this.values.off(t,r),n!=="value"&&this.children.off(t,n,r)}exportTree(){return this.persistence.exportTree()}exportPersistenceState(){return this.persistence.exportState()}restoreTree(t){this.persistence.restore(t)}resetTree(t=!1){this.persistence.reset(t)}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return Ak(this.state.clock.now())}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const ju=new WeakMap,Cu=new WeakMap;function Bk(e,t){const n=Fk(e);return n.getOrCreate(n.keyOf(t))}function Fk(e){const t=ju.get(e);if(t)return t;const n=new Set,r=()=>{for(const i of n)try{i()}catch{}},s=W_({create:i=>{const o=i===s.defaultKey?void 0:i,a=new Uk(e,o);return a.subscribeWrites(r),a}});return ju.set(e,s),e.onEvent(i=>{if(i.kind==="session_boundary"&&i.phase==="reset")for(const[,o]of s.entries())o.invalidateConnectionQueues(),Cu.has(e)||o.setRules(null)}),e.registerPersistableService("rtdb",{snapshot:()=>{const i=s.getOrCreate(s.defaultKey).exportPersistenceState(),o={};for(const[a,l]of s.entries())a!==s.defaultKey&&(o[a]=l.exportPersistenceState());return Object.keys(o).length>0&&i!==null&&typeof i=="object"&&!Array.isArray(i)?{...i,instances:o}:i},restore:i=>{if(!i||typeof i!="object")return;s.getOrCreate(s.defaultKey).restoreTree(i);const o=i;if(o.instances&&typeof o.instances=="object")for(const[a,l]of Object.entries(o.instances))s.getOrCreate(a).restoreTree(l)},subscribe:i=>(n.add(i),()=>{n.delete(i)}),reset:()=>{for(const[,i]of s.entries())i.resetTree(Cu.has(e))}}),s}const Mp="type.googleapis.com/google.rpc.BadRequest",Lp="type.googleapis.com/google.firebase.fcm.v1.FcmError";function as(e,t){return{"@type":Mp,fieldViolations:[{field:e,description:t}]}}function yn(e){return{"@type":Lp,errorCode:e}}function zn(e,t){return{status:400,error:{code:400,message:e,status:"INVALID_ARGUMENT",details:t}}}function Iu(){const e="Recipient of the message is not set.";return zn(e,[as("message",e),yn("INVALID_ARGUMENT")])}function qk(){const e="Exactly one of token, topic or condition is required.";return zn(e,[as("message",e),yn("INVALID_ARGUMENT")])}function Vk(){const e="The registration token is not a valid FCM registration token";return zn(e,[yn("INVALID_ARGUMENT"),as("message.token",e)])}function Up(){const e="Topic name contains invalid characters.";return zn(e,[as("message",e),yn("INVALID_ARGUMENT")])}function Wk(){return{status:400,error:{code:400,message:"Request contains an invalid argument.",status:"INVALID_ARGUMENT"}}}function zk(){return zn("Message is too large. The maximum is 4K (4096 bytes).",[{"@type":Mp},yn("INVALID_ARGUMENT")])}function Hk(){const e="TTL must be a non-negative integer.";return zn(e,[as("message.webpush.headers.TTL",e),yn("INVALID_ARGUMENT")])}function Kk(){return{status:404,error:{code:404,message:"Requested entity was not found.",status:"NOT_FOUND",details:[yn("UNREGISTERED")]}}}function Gk(e){return e.error.details?.find(n=>n["@type"]===Lp)?.errorCode}class tt extends Error{envelope;errorCode;constructor(t){super(t.error.message),this.name="BrokerSendError",this.envelope=t,this.errorCode=Gk(t)}}const Jk=/^[a-zA-Z0-9-_.~%]+$/,Mi=/^[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$/,Yk=4506,Ru=new TextEncoder;function Qk(e){if(e===void 0)return 0;let t=0;for(const[n,r]of Object.entries(e))t+=Ru.encode(n).length+Ru.encode(String(r)).length;return t}function Bc(e){return e.startsWith("/topics/")?e.slice(8):e}function Li(e){const t=Bc(e);return t.length>0&&Jk.test(t)}function Xk(e){const t=e;let n=0;const r=[];function s(){for(;n<t.length&&/\s/.test(t[n]);)n++}function i(l){return s(),t.startsWith(l,n)?(n+=l.length,!0):!1}function o(){if(s(),i("!"))return o();if(i("("))return a()?i(")"):!1;if(s(),t[n]!=="'")return!1;n++;const l=n;for(;n<t.length&&t[n]!=="'";)n++;if(n>=t.length)return!1;const u=t.slice(l,n);return n++,!i("in")||!i("topics")||!Li(u)?!1:(r.push(u),!0)}function a(){if(!o())return!1;for(;;){if(s(),i("&&")||i("||")){if(!o())return!1;continue}return!0}}return!a()||(s(),n!==t.length)?null:{topics:r}}function Zk(e){if(typeof e!="object"||e===null)throw new tt(Iu());const t=[];if(typeof e.token=="string"&&t.push({kind:"token",token:e.token}),typeof e.topic=="string"&&t.push({kind:"topic",topic:Bc(e.topic)}),typeof e.condition=="string"&&t.push({kind:"condition",condition:e.condition,topics:[]}),t.length===0)throw new tt(Iu());if(t.length>1)throw new tt(qk());const n=t[0];if(n.kind==="token"&&!Mi.test(n.token))throw new tt(Vk());if(n.kind==="topic"&&!Li(n.topic))throw new tt(Up());if(n.kind==="condition"){const s=Xk(n.condition);if(s===null)throw new tt(Wk());n.topics=s.topics}const r=e.webpush?.headers?.TTL;if(r!==void 0&&!/^\d+$/.test(String(r)))throw new tt(Hk());if(Qk(e.data)>Yk)throw new tt(zk());return n}function Bp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eE(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&Mi.test(n),i=Bp(r);if(!(s&&i))return!1;const a=typeof r.registrationId=="string"&&r.registrationId.length>0,l=typeof r.recipientId=="string"&&r.recipientId.length>0,u=r.state==="active"||r.state==="unregistered";return a&&l&&u}function tE(e){return typeof e=="string"&&Mi.test(e)}function nE(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&Li(n),i=Array.isArray(r)&&r.every(tE);return s&&i}function rE(e){if(!Bp(e))return!1;const t=e.version===1,n=Array.isArray(e.tokens)&&e.tokens.every(eE),r=Array.isArray(e.topics)&&e.topics.every(nE);return t&&n&&r}function sE(e){return/[.!?]$/.test(e)?e:`${e}.`}function Fp(e,t){return e===null||!e.startsWith("/")||e.startsWith("//")||t==null||!/^https?:\/\//.test(t)?e:new URL(e,t).href}function qp(){const e=globalThis.location?.origin;return typeof e=="string"&&/^https?:\/\//.test(e)?e:null}const iE="database.rules.json";function Nu(e,t){const n=e.lastIndexOf("."),r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=n>r+1?e.slice(n):"";if(s===".json")return;const i=s===".bolt"?"As of firebase-tools@15.0.0, .bolt rules are no longer supported.":`Unexpected rules format ${s}`;throw new Error(`${t}: ${i}`)}function oE(e){if(e===void 0)return da(void 0);const t=yp(e);try{return $c(t).name}catch{return t}}function aE(e,t={}){const n=t.resolveFile??(o=>o),r=oE(t.projectId);if(e==null){const o=iE;return{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:"firebase.json",configured:!1}],unresolved:[]}}if(!Array.isArray(e)){const o=typeof e=="object"?e.rules:void 0;if(typeof o!="string"||o==="")return{defaultInstance:r,targets:[],unresolved:[]};const a="firebase.json database.rules";return Nu(o,a),{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:a,configured:!0}],unresolved:[]}}const s=[],i=[];return e.forEach((o,a)=>{const l=`firebase.json database[${a}]`,u=o!==null&&typeof o=="object"?o:{};let d;if(typeof u.target=="string"&&u.target!==""){const f=t.targetInstances?.(u.target);d=Array.isArray(f)?f.filter(p=>typeof p=="string"&&p!==""):[]}else if(typeof u.instance=="string"&&u.instance!=="")d=[u.instance];else throw new Error(`${l}: Must supply either "target" or "instance" in database config`);if(typeof u.rules!="string"||u.rules==="")return;Nu(u.rules,l);const h=n(u.rules);if(d.length===0&&typeof u.target=="string"){i.push({target:u.target,label:l,file:h});return}for(const f of d){let p;try{p=$c(f).name}catch(g){const b=g instanceof Error?g.message.trim():String(g);throw new Error(`${l}: instance "${f}" is not a database instance name: ${b}`)}gp(p,t.projectId)&&(p=r);const m=s.find(g=>g.instance===p);if(m===void 0){s.push({instance:p,file:h,configuredFile:u.rules,label:l,configured:!0});continue}if(m.file!==h)throw new Error(`firebase.json deploys two rules files to database instance "${p}": ${m.file} from ${m.label} and ${h} from ${l}. The Firebase CLI deploys both at once, so the configuration does not determine which one production keeps. Deploy one rules file to each instance.`)}}),{defaultInstance:r,targets:s,unresolved:i}}const cE="__pyric_no_password__",lE=300*1e3;function bo(e){return Ep(e.claims)}class Vp{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new N_;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;photoOriginByUid=new Map;authenticatedAtByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;avatarMint=F_;tenantId=null;getTenantId(){return this.tenantId}setTenantId(t){this.tenantId=t}constructor(t,n=t,r=pp(),s){this.sandbox=t,this.session=n,this.usersByEmail=r.usersByEmail,this.usersByUid=r.usersByUid,this.userDbSubs=r.userDbSubscribers,this.providerConfig=r.providerConfig,this.providerConfigSubs=r.providerConfigSubscribers,this.sharedCounters=r.counters,this.cachedUser=this.buildUserFromState(n.currentUser),this.lastNotifiedUid=this.cachedUser?.uid??null;const i=n.onCurrentUserChanged(o=>{if(this.applyingTransition)return;const a=o===null?null:o.uid,l=this.cachedUser?.uid??null;a!==l&&(this.cachedUser=this.buildUserFromState(o)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}getCurrentSignInProvider(){const t=this.cachedUser;return t===null?null:this.signInProviderByUid.get(t.uid)??null}subscribe(t,n){const r=t==="auth-state"?this.authStateSubs:this.idTokenSubs,s={observer:n,hasFired:!1,lastValue:null};return r.push(s),queueMicrotask(()=>{r.includes(s)&&(s.hasFired&&s.lastValue===this.cachedUser||this.deliverOne(s,this.cachedUser))}),()=>{const i=r.indexOf(s);i!==-1&&r.splice(i,1)}}fanOut(t="both"){const n=this.cachedUser;if(t==="both"||t==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(t==="both"||t==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){this.fanOut("id-token");const t=this.cachedUser?.uid??null;this.lastNotifiedUid!==t&&(this.lastNotifiedUid=t,this.fanOut("auth-state"))}deliverOne(t,n){t.hasFired=!0,t.lastValue=n;const r=t.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(t,n=null){const r={email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:this.now().toISOString(),lastLoginAt:null,tenantId:null,...t},s=uE(r,n);return dE(r,s)&&(r.photoUrl=this.avatarMint({uid:r.uid,displayName:r.displayName,email:r.email,providerId:s})),r}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}now(){return Te(this.sandbox).date()}emitAuthEvent(t,n={}){try{pt(this.sandbox,qn({at:this.now().getTime(),service:"auth",op:t,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(t){return this.userDbSubs.add(t),()=>{this.userDbSubs.delete(t)}}isProviderEnabled(t){return this.providerConfig.get(t)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([t,n])=>({providerId:t,enabled:n}))}setProviderConfig(t,n){const r=this.providerConfig.get(t)??!0;r!==n&&(this.providerConfig.set(t,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:t,auth:null,before:{providerId:t,enabled:r},after:{providerId:t,enabled:n}}))}notifyProviderConfigChanged(){for(const t of[...this.providerConfigSubs])try{t()}catch{}}subscribeProviderConfig(t){return this.providerConfigSubs.add(t),()=>{this.providerConfigSubs.delete(t)}}setProviderEnforcementDelegated(t){this.providerEnforcementDelegated=t}setAvatarMint(t){this.avatarMint=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw Y("auth/operation-not-allowed",`${t} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${t}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(t){if(this.providerConfig.clear(),t&&typeof t=="object")for(const[n,r]of Object.entries(t))typeof r=="boolean"&&this.providerConfig.set(n,r);else this.providerConfig.set("password",!0),this.providerConfig.set("anonymous",!0);this.notifyProviderConfigChanged()}getPersistenceMode(){return this.persistenceMode}setPersistenceMode(t){this.persistenceMode!==t&&(this.persistenceMode=t,this.notifySessionChanged())}sessionChangeSubs=new Set;notifySessionChanged(){for(const t of[...this.sessionChangeSubs])try{t()}catch{}}subscribeSession(t){return this.sessionChangeSubs.add(t),()=>{this.sessionChangeSubs.delete(t)}}seedUsers(t){for(const r of t){const i=this.usersByUid.get(r.uid)?.email;typeof i=="string"&&i.length>0&&i.toLowerCase()!==r.email?.toLowerCase()&&this.usersByEmail.delete(i.toLowerCase());const l=r.providerId==="anonymous",u=r.providerUserInfo??[{providerId:r.providerId??"password"}],d=l?[]:u.map(k=>({...k})),h=d.some(k=>k.providerId==="password"),p=(r.password===cE||r.password==="__pyric_popup_no_password__")&&!h,m=l||p,g=this.makeStored({uid:r.uid,email:l?null:r.email??null,password:m?null:r.password??null,displayName:r.displayName??null,phoneNumber:r.phoneNumber??null,photoUrl:r.photoUrl??null,customClaims:r.customClaims??{},emailVerified:r.emailVerified??!1,disabled:r.disabled??!1,isAnonymous:l,providerUserInfo:d,tenantId:r.tenantId??null}),{createdAt:b,lastLoginAt:w,email:x}=r;b!==void 0&&(g.createdAt=b),w!==void 0&&(g.lastLoginAt=w),!l&&x!==void 0&&this.usersByEmail.set(x.toLowerCase(),g),this.usersByUid.set(r.uid,g)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){const{email:r,displayName:s,photoUrl:i,tenantId:o,phoneNumber:a,isAnonymous:l,disabled:u,emailVerified:d}=n,h=s!==null,f=i!==null,p=Object.keys(n.customClaims).length>0,m=o!==null;if(l){const _={uid:n.uid,providerId:"anonymous",createdAt:n.createdAt,lastLoginAt:n.lastLoginAt};h&&(_.displayName=s),f&&(_.photoUrl=i),p&&(_.customClaims=n.customClaims),u&&(_.disabled=!0),m&&(_.tenantId=o),t.push(_);continue}if(r===null)continue;const b={uid:n.uid,createdAt:n.createdAt,lastLoginAt:n.lastLoginAt,email:r,providerId:n.providerUserInfo[0]?.providerId??"password",providerUserInfo:n.providerUserInfo.map(_=>({..._}))},{password:w}=n;w!==null&&(b.password=w),h&&(b.displayName=s),f&&(b.photoUrl=i),a!==null&&(b.phoneNumber=a),p&&(b.customClaims=n.customClaims),d&&(b.emailVerified=!0),u&&(b.disabled=!0),m&&(b.tenantId=o),t.push(b)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw Y("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw Y("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){tr(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){Xt(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw Y("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){Xt(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r!==void 0)return!r.providerUserInfo.some(l=>l.providerId==="password")&&r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw Y("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(o=>o.providerId===n))throw Y("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Xt(i);const o=i.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a.uid!==t)throw Y("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(tr(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==o&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(o,s),r.emailVerified!==void 0&&(s.emailVerified=r.emailVerified)}return s.providerUserInfo.push({providerId:n}),s.isAnonymous&&(s.isAnonymous=!1),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(t,n){const r=this.usersByUid.get(t);if(!r)throw Y("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw Y("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 Y("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Xt(t),tr(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw Y("auth/email-already-in-use",`An account already exists for ${t}.`);const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o)}),o}beforeAuthStateChanged(t,n){const r={callback:t,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(t){if(t===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(t),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const i of n)try{i()}catch{}const s=r instanceof Error?r.message:String(r);throw Y("auth/login-blocked",s)}}transitionCurrentUser(t,n){return t!==null&&n!==void 0&&this.scopeSignInToTenant(t),!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}scopeSignInToTenant(t){const n=this.tenantId;t.tenantId=n;const r=this.usersByUid.get(t.uid);r&&(r.tenantId=n)}setCurrentUser(t,n){if(t===null){const p=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}p!==null&&(this.tokenCache.delete(p.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:p.uid,auth:{uid:p.uid}}));return}const s=n!==void 0;s&&this.signInProviderByUid.set(t.uid,n),(s||!this.authenticatedAtByUid.has(t.uid))&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{};s&&o!==void 0&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),this.cachedUser=t;const u=this.mintToken(t.uid,a,t.tenantId??null),d={uid:t.uid,token:bo(u.result)};typeof t.tenantId=="string"&&(d.tenant=t.tenantId);const f=d;this.applyingTransition=!0;try{this.session.currentUser=f}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),s&&this.emitAuthEvent("sign_in",{path:t.uid,auth:f,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n??"anonymous"}})}setMockResult(t,n){this.flow.setMockResult(t,n)}consumeMockResult(t){return this.flow.consumeMockResult(t)}setResolver(t){this.flow.setResolver(t)}getResolver(){return this.flow.getResolver()}setRedirectResult(t){this.flow.setRedirectResult(t)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(t,n){let r=!1;const s=t.photoURL??null;let i=this.usersByUid.get(t.uid);i?Au(i,s)&&(r=!0):(i=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,photoUrl:s,isAnonymous:t.isAnonymous},n),this.usersByUid.set(t.uid,i),t.email&&this.usersByEmail.set(t.email.toLowerCase(),i),r=!0),i.providerUserInfo.some(o=>o.providerId===n)||(i.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(t){const{providerId:n}=t;let r;if("uid"in t){const s=this.usersByUid.get(t.uid);if(!s)throw Y("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);this.assertUserEnabled(s),r=s}else{const{spec:s}=t,i=s.photoUrl??null,o=this.usersByEmail.get(s.email.toLowerCase());o?(this.assertUserEnabled(o),r=o,Au(r,i)&&this.notifyUsersChanged()):(r=this.makeStored({uid:s.uid??fE(),email:s.email,displayName:s.displayName??null,photoUrl:i,customClaims:s.customClaims??{}},n),this.usersByUid.set(r.uid,r),this.usersByEmail.set(s.email.toLowerCase(),r),this.notifyUsersChanged())}return r.providerUserInfo.some(s=>s.providerId===n)||(r.providerUserInfo.push({providerId:n}),this.notifyUsersChanged()),{user:this.buildUserFromStored(r),providerId:n,operationType:"signIn"}}listIdentities(){return[...this.usersByUid.values()].map(t=>({uid:t.uid,email:t.email,displayName:t.displayName,providerId:t.isAnonymous?"anonymous":t.providerUserInfo[0]?.providerId??"password",providerUserInfo:[...t.providerUserInfo],isAnonymous:t.isAnonymous,customClaims:t.customClaims}))}toRecord(t){return{uid:t.uid,email:t.email,displayName:t.displayName,phoneNumber:t.phoneNumber,photoUrl:t.photoUrl,customClaims:{...t.customClaims},providerUserInfo:t.providerUserInfo.map(n=>({...n})),isAnonymous:t.isAnonymous,disabled:t.disabled,emailVerified:t.emailVerified,tenantId:t.tenantId,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>({...this.toRecord(t),photoUrl:en(t,this.photoOriginByUid)}))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const o of t){const a=o?.providerId?.trim();if(!a)throw Y("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);a==="password"||a==="anonymous"||s.has(a)||(s.add(a),i.push({providerId:a}))}return n&&i.unshift({providerId:"password"}),i}nextAvailableAdminUid(){for(;;){const t=`user-${this.sharedCounters.nextAdminUserId++}`;if(!this.usersByUid.has(t))return t}}createUser(t){t.customClaims!==void 0&&fu(t.customClaims);const n=t.uid??this.nextAvailableAdminUid();if(this.usersByUid.has(n))throw Y("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Xt(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw Y("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(tr(t.password),t.email===void 0))throw Y("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:t.email??null,password:t.password??null,displayName:t.displayName??null,phoneNumber:t.phoneNumber??null,photoUrl:t.photoUrl??null,customClaims:t.customClaims??{},disabled:t.disabled??!1,emailVerified:t.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(t.providerUserInfo??[],t.password!==void 0,"createUser")});this.usersByUid.set(n,r),r.email&&this.usersByEmail.set(r.email.toLowerCase(),r),this.notifyUsersChanged();const s=this.toRecord(r);return this.emitAuthEvent("user_create",{path:n,auth:null,after:s}),{...this.toRecord(r),photoUrl:en(r,this.photoOriginByUid)}}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw Y("auth/user-not-found",`No user found for uid ${t}.`);n.customClaims!==void 0&&fu(n.customClaims);const s=this.toRecord(r);if(n.email!==void 0){Xt(n.email);const o=n.email.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a!==r)throw Y("auth/email-already-in-use",`An account already exists for ${n.email}.`);r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n.email,this.usersByEmail.set(o,r)}n.password!==void 0&&(tr(n.password),r.password=n.password,r.providerUserInfo.some(o=>o.providerId==="password")||r.providerUserInfo.push({providerId:"password"})),n.providerUserInfo!==void 0&&(r.providerUserInfo=this.sanitizeLinkedProviders(n.providerUserInfo,r.password!==null,"updateUser")),n.displayName!==void 0&&(r.displayName=n.displayName),n.customClaims!==void 0&&(r.customClaims={...n.customClaims}),n.disabled!==void 0&&(r.disabled=n.disabled),n.emailVerified!==void 0&&(r.emailVerified=n.emailVerified),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:null,before:s,after:i}),{...this.toRecord(r),photoUrl:en(r,this.photoOriginByUid)}}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw Y("auth/user-not-found",`No user found for uid ${t}.`);const r=this.toRecord(n);this.usersByUid.delete(t),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(t),this.signInProviderByUid.delete(t),this.photoOriginByUid.delete(t),this.authenticatedAtByUid.delete(t),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:t,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const t=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:t}})}assertSignInAllowed(t){if(this.usersByUid.get(t)?.disabled)throw Y("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:en(t,this.photoOriginByUid),emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo,tenantId:t.tenantId})}mintAnonymousUser(){const t=`anonymous-${globalThis.crypto.randomUUID()}`,n=this.makeStored({uid:t,isAnonymous:!0});return this.usersByUid.set(t,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:t,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:t,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(t){const n=t.tenantId??null;switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous",n,!0,t.origin);case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password",n,!0,t.origin);case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password",n,!0,t.origin);case"provider":case"custom":case"uid":{const r=t.kind==="provider";r&&this.assertProviderEnabled(t.providerId);const s=this.usersByUid.get(t.uid);if(s===void 0)throw Y("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);this.assertUserEnabled(s);const a=s.isAnonymous?"anonymous":s.providerUserInfo[0]?.providerId??"password";let l=r?t.providerId:a;t.kind==="custom"&&(l="custom");const d=t.kind!=="uid"||!this.authenticatedAtByUid.has(t.uid);return this.establishDetachedSession(this.buildUserFromStored(s),l,n,d,t.origin)}}}establishDetachedSession(t,n,r,s=!0,i){this.signInProviderByUid.set(t.uid,n),i!==void 0&&this.photoOriginByUid.set(t.uid,i),s&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{},l=o!==void 0;l&&(t.photoURL=en(o,this.photoOriginByUid)),l&&s&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),t.tenantId=r;const u=this.mintToken(t.uid,a,r),d={uid:t.uid,token:bo(u.result)};return r!==null&&(d.tenant=r),this.emitAuthEvent("sign_in",{path:t.uid,auth:d,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:d}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims,tenantId:t.tenant??n.tenantId}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{},tenantId:t.tenant??null})}mintToken(t,n,r){const s=this.now(),i=new Date(s.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,a=this.signInProviderByUid.get(t)??null,l=new Date(this.authenticatedAtByUid.get(t)??s.getTime()),u=this.usersByUid.get(t),d={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(l.getTime()/1e3),iat:Math.floor(s.getTime()/1e3),exp:Math.floor(i.getTime()/1e3),...jp(t,u?{...KS(u),photoUrl:en(u,this.photoOriginByUid)}:null,n,a)},f=Oi({uid:t,tenant:r??void 0,token:d})?.token??d,p=A_(t,Ep(f),o),m={token:p,claims:f,expirationTime:i.toISOString(),issuedAtTime:s.toISOString(),authTime:l.toISOString(),signInProvider:a},g={token:p,result:m},b=this.tokenCache.get(t)??new Map;return b.set(r,g),this.tokenCache.set(t,b),g}getIdTokenFor(t,n,r,s=null){return this.getIdTokenResultFor(t,n,r,s).token}getIdTokenResultFor(t,n,r,s=null){if(r){const l=this.mintToken(t,n,s),u=this.session.currentUser;if(u!==null&&u.uid===t&&(u.tenant??null)===s){this.applyingTransition=!0;try{this.session.currentUser={...u,token:bo(l.result)}}finally{this.applyingTransition=!1}}return this.fanOut("id-token"),l.result}const i=this.tokenCache.get(t)?.get(s);return i!==void 0?i.result:this.mintToken(t,n,s).result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",o=t.providers??[{providerId:"password"}],l=t.isAnonymous===!0?[]:o.map(d=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:d.providerId})),u={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:i,providerData:l,getIdToken:async d=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId),getIdTokenResult:async d=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId)};return Object.defineProperty(u,C_,{value:{updateProfile:d=>(this.updateProfileFor(u,d),Promise.resolve()),delete:()=>(this.deleteFor(u),Promise.resolve()),updateEmail:d=>(this.updateEmailFor(u,d),Promise.resolve()),updatePassword:d=>(this.updatePasswordFor(u,d),Promise.resolve()),reload:()=>(this.reloadFor(u),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),u}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(t,n){const r=this.usersByUid.get(t.uid),s=r?this.toRecord(r):void 0;r&&(n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL)),this.applyProfileToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t.uid,auth:{uid:t.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(t,n){const r=t;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=t.providerData?.[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(t,n){const r=this.usersByUid.get(t);if(!r)throw Y("auth/user-not-found",`updateProfile: no identity with uid ${t}.`);const s=this.toRecord(r);n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL),this.cachedUser&&this.cachedUser.uid===t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:{uid:t},before:s,after:i,detail:{displayName:n.displayName,photoURL:n.photoURL}}),i}recordAuthentication(t){this.authenticatedAtByUid.set(t,this.now().getTime())}assertRecentLogin(t){if(this.usersByUid.get(t)?.isAnonymous===!0)return;const r=this.authenticatedAtByUid.get(t);if(r===void 0)return;if(this.now().getTime()-r>lE)throw Y("auth/requires-recent-login","Error")}deleteFor(t){this.assertRecentLogin(t.uid),this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.assertRecentLogin(t.uid),this.updateUser(t.uid,{email:n}),this.applyEmailToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(t,n){t.email=n;const r=t.providerData?.[0];r&&(r.email=n)}updatePasswordFor(t,n){this.assertRecentLogin(t.uid),this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw Y("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=en(n,this.photoOriginByUid),r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}assertUserEnabled(t){if(t.disabled)throw Y("auth/user-disabled","The user account has been disabled by an administrator.")}validatePassword(t,n){if(Xt(t),typeof n!="string"||n.length===0)throw Y("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw Y("auth/user-not-found",`No user found for ${t}.`);if(this.assertUserEnabled(r),r.password!==n)throw Y("auth/wrong-password","Invalid password.");return r}}function uE(e,t){if(t!==null)return t;const n=e.providerUserInfo[0];return n===void 0?null:n.providerId}function dE(e,t){return e.photoUrl!==null||e.isAnonymous||t===null?!1:t.includes(".")}function en(e,t){return Fp(e.photoUrl,t.get(e.uid)??qp())}function Au(e,t){return t===null||e.photoUrl===t?!1:(e.photoUrl=t,!0)}function fE(){return`provider-${globalThis.crypto.randomUUID()}`}const Ou=new WeakSet,xs=new WeakMap;function Wp(e,t,n,r="[DEFAULT]"){return hE(e,t),pE(e,t,n,r)}function hE(e,t){Ou.has(e)||(Ou.add(e),e.registerPersistableService("auth",{snapshot:()=>({users:t.exportUsers(),providers:t.exportProviderConfig()}),restore:n=>{const r=n;t.clearUsers(),Array.isArray(r?.users)&&r.users.length>0&&t.seedUsers(r.users),t.restoreProviderConfig(r?.providers)},reset:()=>{t.clearUsers(),t.restoreProviderConfig(void 0)},subscribe:n=>{const r=t.subscribeUsers(n),s=t.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function $u(e){return{snapshot:()=>null,restore:()=>{},session:{currentUid:()=>e.session.currentUser?.uid??null,restore:(t,n)=>{e.backend.setPersistenceMode(n),e.backend.restoreSession(t)},mode:()=>e.backend.getPersistenceMode(),subscribe:t=>(e.subscribers.add(t),e.unsubscribeBackend||(e.unsubscribeBackend=e.backend.subscribeSession(()=>{for(const n of e.subscribers)n()})),()=>{e.subscribers.delete(t),e.subscribers.size===0&&(e.unsubscribeBackend?.(),e.unsubscribeBackend=void 0)})}}}function pE(e,t,n,r){let s=xs.get(e);s||(s=new Map,xs.set(e,s));const i=`auth-session:${r}`,o=s.get(i);if(o){const u=++o.generation;return o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.backend=t,o.session=n,o.unregisterService=e.registerPersistableService(i,$u(o)),()=>{o.generation===u&&(o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.subscribers.clear(),s.get(i)===o&&s.delete(i),s.size===0&&xs.delete(e))}}const a={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,a),a.unregisterService=e.registerPersistableService(i,$u(a));const l=a.generation;return()=>{a.generation===l&&(a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.subscribers.clear(),s.get(i)===a&&s.delete(i),s.size===0&&xs.delete(e))}}async function hq(e){const{backend:t}=Oc(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 mE(e){const t=Oc(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const Pu=new WeakMap,Du=new WeakMap,Tu=new WeakMap;function zp(e){let t=Du.get(e);return t||(t=pp(),Du.set(e,t)),t}function yE(e){let t=Pu.get(e);return t||(t=new Vp(e,e,zp(e)),Pu.set(e,t),Wp(e,t,e)),t}function gE(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new Vp(n,r,zp(n),i=>{t.onDelete(i)});return t.onDelete(Wp(n,s,r,e.name)),s})}function Fc(e){if(e===void 0)return Fc(gv());const t=bv(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:gE(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return Mu(n,e)});if(bE(e)){let n=Tu.get(e);return n||(n=Mu({kind:"sandbox",sandbox:e,backend:yE(e)}),Tu.set(e,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric sandbox or @pyric/cli/register before importing to select the sandbox.")}function bE(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function Mu(e,t){const n={[dp]:e,...t?{app:t}:{},signOut(){return mE(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}}),Object.defineProperty(n,"tenantId",{enumerable:!0,get(){return e.backend.getTenantId()},set(r){e.backend.setTenantId(r)}})}function X(e){return Oc(e)}const xe={setUser(e,t){X(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){X(e).backend.setResolver(t)},setAuthMailResolver(e,t){X(e).backend.setMailResolver(t)},takeAuthMail(e,t){return X(e).backend.takeMail(t)},listAuthMail(e){return X(e).backend.listMail()},mockActionCode(e,t,n){X(e).backend.stageActionCode(t,n)},listIdentities(e){return X(e).backend.listIdentities()},createSignInCredential(e,t){return X(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new Ch("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");X(e).backend.setMockResult(n,t)},seedUsers(e,t){X(e).backend.seedUsers(t)},exportUsers(e){return X(e).backend.exportUsers()},restoreSession(e,t){return X(e).backend.restoreSession(t)},getTenantId(e){return X(e).backend.getTenantId()},setTenantId(e,t){X(e).backend.setTenantId(t)},mintSession(e,t){return X(e).backend.mintDetachedSession(t)},signInProvider(e){return X(e).backend.getCurrentSignInProvider()},listUsers(e){return X(e).backend.listUsers()},createUser(e,t){return X(e).backend.createUser(t)},updateUser(e,t,n){return X(e).backend.updateUser(t,n)},updateProfile(e,t,n){return X(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){X(e).backend.deleteUser(t)},clearUsers(e){X(e).backend.clearUsers()},subscribeUsers(e,t){return X(e).backend.subscribeUsers(t)},exportProviderConfig(e){return X(e).backend.exportProviderConfig()},restoreProviderConfig(e,t){X(e).backend.restoreProviderConfig(t)},getAuthProviderConfig(e){return X(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){X(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){X(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){X(e).backend.setProviderEnforcementDelegated(t)},setAvatarMint(e,t){X(e).backend.setAvatarMint(t)},subscribeAuthProviderConfig(e,t){return X(e).backend.subscribeProviderConfig(t)}};function ba(e){return e!==void 0&&/^[0-9]+$/.test(e)?BigInt(e):0n}function wE(e,t){return e>t?e:t}function qc(e,t){return e===void 0?t:t===void 0||ba(e)>=ba(t)?e:t}function Hp(e,t){return qc(e,t)??t}function Kp(e){return BigInt(Math.floor(e*1e3))}function vE(e){return t=>String(wE(Kp(e),ba(t)+1n))}const wa="pyric-storage",te="pyric-default";function ae(e,t){return`${e}/${t}`}function fi(e){const t=e.indexOf("/");return t===-1?null:{bucket:e.slice(0,t),path:e.slice(t+1)}}function xE(e){return e?`${wa}:${e}`:wa}const _E=2,ke="blobs",le="metadata",_r="generations";function Gp(e,t,n){if(e.metadata.bucket!==t||e.metadata.fullPath!==n)throw new Error("A prior Storage object can only be put back at its own bucket and path.");Vc(e.blob,e.metadata)}function Vc(e,t){if(t.size!==e.size)throw new Error("Storage metadata does not match its object.")}async function SE(e=wa,t){try{const n=await IE(e);return new CE(n,t)}catch(n){return typeof indexedDB<"u"&&Jp(e,EE(n),"other tabs reload"),new jE(t)}}class kE extends Error{name="OpenBlockedError"}function EE(e){return e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?`${e.name}: ${e.message}`:String(e)}function Jp(e,t,n){console.warn(`[pyric] Storage could not use the IndexedDB store "${e}" (${t}). Storage will not persist until ${n}.`)}class Yp{uploads=new Map;beginUpload(t,n,r,s,i){const o=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`upl-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return this.uploads.set(o,{uploadId:o,bucket:t,path:n,size:r,contentType:s,customMetadata:i,parts:new Map,createdAt:Date.now()}),o}putPart(t,n,r){const s=this.uploads.get(t);if(!s){const o=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw o.code="storage/object-not-found",o}s.parts.set(n,r);let i=0;for(const o of s.parts.values())i+=o.byteLength;return{bytesReceived:i}}readUpload(t){const n=this.uploads.get(t);if(!n){const i=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw i.code="storage/object-not-found",i}let r=0;const s=Array.from(n.parts.keys()).sort((i,o)=>i-o);for(const i of s)r+=n.parts.get(i).byteLength;if(r!==n.size){const i=new Error(`storage/invalid-argument: Uploaded bytes (${r}) did not match declared size (${n.size}).`);throw i.code="storage/invalid-argument",i}return new Blob(s.map(i=>n.parts.get(i)),{type:n.contentType})}abortUpload(t){this.uploads.delete(t)}}class jE{blobs=new Map;metadata=new Map;highWater=new Map;staging=new Yp;_defaultBucket;constructor(t){this._defaultBucket=t}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),Vc(n,r),r.bucket||(r.bucket=i);const o=ae(i,t),a=this.objectAt(o),l=this.highWater.get(o);return s!==void 0&&(r.generation=s(qc(a?.metadata.generation,l))),this.blobs.set(o,n),this.metadata.set(o,r),this.highWater.set(o,Hp(l,r.generation)),a}objectAt(t){const n=this.blobs.get(t),r=this.metadata.get(t);if(!(n===void 0||r===void 0))return{blob:n,metadata:r}}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&Gp(r,i,t);const o=ae(i,t);return this.metadata.get(o)?.generation!==n?!1:(this.blobs.delete(o),this.metadata.delete(o),r===void 0||(this.blobs.set(o,r.blob),this.metadata.set(o,r.metadata)),!0)}async getBlob(t,n){if(n)return this.blobs.get(ae(n,t));const r=this._defaultBucket??te,s=this.blobs.get(ae(r,t));if(s!==void 0)return s;if(r!==te){const i=this.blobs.get(ae(te,t));if(i!==void 0)return i}for(const[i,o]of this.blobs.entries()){const a=fi(i);if(a&&a.path===t)return o}}async getMetadata(t,n){if(n)return this.metadata.get(ae(n,t));const r=this._defaultBucket??te,s=this.metadata.get(ae(r,t));if(s!==void 0)return s;if(r!==te){const i=this.metadata.get(ae(te,t));if(i!==void 0)return i}for(const[i,o]of this.metadata.entries()){const a=fi(i);if(a&&a.path===t)return o}}async getObject(t,n){return this.objectAt(ae(n??this._defaultBucket??te,t))}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s),this.metadata.set(ae(s,t),n)}async delete(t,n){const r=n??this._defaultBucket??te;this.blobs.delete(ae(r,t)),this.metadata.delete(ae(r,t))}async listByPrefix(t,n){const s=`${n??this._defaultBucket??te}/${t}`,i=[],o=Array.from(this.metadata.keys()).sort();for(const a of o)if(a.startsWith(s)){const l=this.metadata.get(a);l&&i.push(l)}return i}async reset(t){if(!t){this.blobs.clear(),this.metadata.clear(),this._defaultBucket=void 0;return}const n=`${t}/`;for(const r of Array.from(this.blobs.keys()))r.startsWith(n)&&this.blobs.delete(r);for(const r of Array.from(this.metadata.keys()))r.startsWith(n)&&this.metadata.delete(r)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){}scoped(t){return new Ui(this,t)}}class CE{db;staging=new Yp;_defaultBucket;closedReason;constructor(t,n){this.db=t,this._defaultBucket=n,t.addEventListener("versionchange",()=>{t.close(),this.closedReason="a newer pyric build opened it in another tab",Jp(t.name,this.closedReason,"this tab reloads")})}transaction(t,n){if(this.closedReason!==void 0)throw new Error(`The IndexedDB store "${this.db.name}" closed because ${this.closedReason}. Reload this tab to use Storage.`);return this.db.transaction(t,n)}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),Vc(n,r),r.bucket||(r.bucket=i);const o=ae(i,t),a=this.transaction([ke,le,_r],"readwrite"),l=RE(a,o),u=a.objectStore(_r).get(o);let d;u.addEventListener("success",()=>{const h=u.result;try{s!==void 0&&(r.generation=s(qc(l.object()?.metadata.generation,h))),a.objectStore(ke).put(n,o),a.objectStore(le).put(r,o),a.objectStore(_r).put(Hp(h,r.generation),o)}catch(f){d={error:f},a.abort()}});try{await rr(a)}catch(h){throw d!==void 0?d.error:h}return l.object()}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&Gp(r,i,t);const o=ae(i,t),a=this.transaction([ke,le],"readwrite");let l=!1;const u=a.objectStore(le).get(o);return u.addEventListener("success",()=>{if(u.result?.generation===n){if(l=!0,r===void 0){a.objectStore(ke).delete(o),a.objectStore(le).delete(o);return}a.objectStore(ke).put(r.blob,o),a.objectStore(le).put(r.metadata,o)}}),await rr(a),l}async getBlob(t,n){const s=this.transaction(ke,"readonly").objectStore(ke);if(n)return vt(s.get(ae(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(ae(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(ae(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=fi(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getMetadata(t,n){const s=this.transaction(le,"readonly").objectStore(le);if(n)return vt(s.get(ae(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(ae(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(ae(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=fi(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getObject(t,n){const r=ae(n??this._defaultBucket??te,t),s=this.transaction([ke,le],"readonly"),[i,o]=await Promise.all([vt(s.objectStore(ke).get(r)),vt(s.objectStore(le).get(r))]);if(!(i===void 0||o===void 0))return{blob:i,metadata:o}}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s);const i=ae(s,t),o=this.transaction(le,"readwrite");o.objectStore(le).put(n,i),await rr(o)}async delete(t,n){const r=n??this._defaultBucket??te,s=ae(r,t),i=this.transaction([ke,le],"readwrite");i.objectStore(ke).delete(s),i.objectStore(le).delete(s),await rr(i)}async listByPrefix(t,n){const r=n??this._defaultBucket??te,s=this.transaction(le,"readonly"),i=`${r}/${t}`,o=IDBKeyRange.bound(i,i+"�",!1,!1);return vt(s.objectStore(le).getAll(o))}async reset(t){const n=this.transaction([ke,le],"readwrite");if(!t)n.objectStore(ke).clear(),n.objectStore(le).clear(),this._defaultBucket=void 0;else{const r=`${t}/`,s=IDBKeyRange.bound(r,r+"�",!1,!1);n.objectStore(ke).delete(s),n.objectStore(le).delete(s)}await rr(n)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){this.db.close()}scoped(t){return new Ui(this,t)}}class Ui{underlying;bucket;constructor(t,n){this.underlying=t,this.bucket=n}get replacedObjectsOnDisk(){return this.underlying.replacedObjectsOnDisk}async put(t,n,r,s){const i=r.bucket?r:{...r,bucket:this.bucket},o=await this.underlying.put(t,n,i,s);return r.generation=i.generation,o}deleteIfGeneration(t,n,r){return this.underlying.deleteIfGeneration(t,n,r??this.bucket)}replaceIfGeneration(t,n,r,s){return this.underlying.replaceIfGeneration(t,n,r,s??this.bucket)}references(t){if(this.underlying.references)return this.underlying.references(t??this.bucket);throw new Error("The underlying storage backend keeps no object files to refer to.")}putReference(t,n,r,s){const i=s.bucket?s:{...s,bucket:this.bucket};if(this.underlying.putReference)return this.underlying.putReference(t,n,r,i);throw new Error("The underlying storage backend keeps no object files to refer to.")}getBlob(t,n){return this.underlying.getBlob(t,n??this.bucket)}getMetadata(t,n){return this.underlying.getMetadata(t,n??this.bucket)}getObject(t,n){return this.underlying.getObject(t,n??this.bucket)}putMetadata(t,n,r){const s=n.bucket?n:{...n,bucket:this.bucket};return this.underlying.putMetadata(t,s,r??this.bucket)}delete(t,n){return this.underlying.delete(t,n??this.bucket)}listByPrefix(t,n){return this.underlying.listByPrefix(t,n??this.bucket)}reset(t){return this.underlying.reset(t??this.bucket)}beginUpload(t,n,r,s,i){const o=t??this.bucket;if(this.underlying.beginUpload)return this.underlying.beginUpload(o,n,r,s,i);throw new Error("Chunked upload not supported by underlying storage backend")}putPart(t,n,r){if(this.underlying.putPart)return this.underlying.putPart(t,n,r);throw new Error("Chunked upload not supported by underlying storage backend")}readUpload(t){if(this.underlying.readUpload)return this.underlying.readUpload(t);throw new Error("Chunked upload not supported by underlying storage backend")}abortUpload(t){return this.underlying.abortUpload?this.underlying.abortUpload(t):Promise.resolve()}close(){this.underlying.close()}scoped(t){return t===this.bucket?this:this.underlying.scoped?this.underlying.scoped(t):new Ui(this.underlying,t)}}function IE(e){return new Promise((t,n)=>{try{if(typeof indexedDB>"u"||!indexedDB.open)return n(new Error("IndexedDB not available"));const r=indexedDB.open(e,_E);r.addEventListener("upgradeneeded",()=>{const i=r.result;i.objectStoreNames.contains(ke)||i.createObjectStore(ke),i.objectStoreNames.contains(le)||i.createObjectStore(le),i.objectStoreNames.contains(_r)||i.createObjectStore(_r)});let s=!1;r.addEventListener("success",()=>{if(s){r.result.close();return}t(r.result)}),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>{s=!0,n(new kE("another tab holds it open on an older pyric build"))})}catch(r){n(r)}})}function RE(e,t){const n=e.objectStore(ke).get(t),r=e.objectStore(le).get(t);return{object(){const s=n.result,i=r.result;if(!(s===void 0||i===void 0))return{blob:s,metadata:i}}}}function vt(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function rr(e){return new Promise((t,n)=>{e.addEventListener("complete",()=>t()),e.addEventListener("error",()=>n(e.error)),e.addEventListener("abort",()=>n(e.error??new Error("IndexedDB transaction aborted")))})}class Qp{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}function Lu(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const NE=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function Xp(e){return{segments:e.path.segments.map(AE),children:e.children.map(Xp),allows:e.allows.map(t=>({verbs:t.operations,condition:re(t.condition)})),functions:e.functions.map(va)}}function AE(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 va(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>{const n={name:t.name,value:re(t.value)};return Ih(t,n),n}),body:re(e.body)}}function re(e){const t=OE(e);return Ih(e,t),t}function OE(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Me(e.value)}:e.value instanceof Uint8Array?{kind:"literal",value:new $i(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:re(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:re(e.object),method:e.method,args:e.args.map(re)};case"bracketAccess":return{kind:"index",target:re(e.object),index:re(e.index)};case"sliceAccess":return{kind:"slice",target:re(e.object),start:re(e.start),end:re(e.end)};case"binaryOp":if(!NE.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:re(e.left),right:re(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:re(e.operand)};case"ternary":return{kind:"ternary",cond:re(e.condition),then:re(e.consequent),else:re(e.alternate)};case"inExpr":return{kind:"in",element:re(e.element),collection:re(e.collection)};case"isExpr":return{kind:"is",value:re(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(re)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:re(t.key),value:re(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:re(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(re)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function xa(e){const t=fw(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: ${hw(t.error,e)}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r=pw(n);if(r.length>0)throw new SyntaxError(`Storage rules do not compile: ${mw(r)}`);const s=(n.imports??[]).flatMap(d=>d.functions.map(h=>({name:h,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:d.module,scopeKind:"global",declCaptures:new Set}))),i=(n.functions??[]).map(d=>{const h=va(d);return h.scopeKind="global",h.declCaptures=new Set,h}),o=new Map;for(const d of s)o.set(d.name,d);for(const d of i)o.set(d.name,d);for(const d of o.values())d.declScope=o;const a=(n.service.functions??[]).map(d=>{const h=va(d);return h.scopeKind="service",h.declCaptures=new Set,h}),l=new Map(o);for(const d of a)l.set(d.name,d);for(const d of a)d.declScope=l;const u={segments:[],children:[Xp(n.service.match)],allows:[],functions:[...s,...i,...a],visibleFuncs:l};for(const d of u.children)Zp(d,l,new Set);return{_root:u,_version:n.version}}function Zp(e,t,n){const r=new Set(n);for(const i of e.segments)(i.kind==="param"||i.kind==="wildcard")&&r.add(i.name);const s=new Map(t);for(const i of e.functions)s.set(i.name,i);e.visibleFuncs=s;for(const i of e.functions)i.declScope=s,i.scopeKind="match",i.declCaptures=r;for(const i of e.children)Zp(i,s,r)}function pe(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 pe(e.target,t);case"index":return pe(e.target,t)||pe(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>pe(n,t));case"unary":return pe(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>pe(n,t));case"in":return pe(e.element,t)||pe(e.collection,t);case"is":return pe(e.value,t);case"list":return e.elements.some(n=>pe(n,t));case"map":return e.entries.some(({key:n,value:r})=>pe(n,t)||pe(r,t));case"binary":return pe(e.left,t)||pe(e.right,t);case"call":return e.args.some(n=>pe(n,t));case"methodcall":return pe(e.target,t)||e.args.some(n=>pe(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&pe(n.expr,t));case"ident":case"literal":return!1}}function em(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&&pe(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(pe(i.value,s))return!0;s.add(i.name)}if(pe(r.body,s))return!0}return e.children.some(r=>em(r,n))}function $E(e){if(/\\[1-9]/.test(e)||/\(\?<?[=!]/.test(e))return!1;try{return new RegExp(`^(?:${Rh(e)})$`),!0}catch{return!1}}function se(e){if(e.kind==="methodcall"&&e.method==="matches"&&e.args.length===1){const t=e.args[0];if(t?.kind==="literal"&&typeof t.value=="string"&&!$E(t.value))throw new SyntaxError(`Storage rules do not compile: Invalid regular expression pattern. Pattern: ${t.value}.`)}switch(e.kind){case"member":se(e.target);return;case"index":se(e.target),se(e.index);return;case"slice":se(e.target),se(e.start),se(e.end);return;case"unary":se(e.arg);return;case"ternary":se(e.cond),se(e.then),se(e.else);return;case"in":se(e.element),se(e.collection);return;case"is":se(e.value);return;case"list":for(const t of e.elements)se(t);return;case"map":for(const{key:t,value:n}of e.entries)se(t),se(n);return;case"binary":se(e.left),se(e.right);return;case"call":for(const t of e.args)se(t);return;case"methodcall":se(e.target);for(const t of e.args)se(t);return;case"path":for(const t of e.segments)t.kind==="interp"&&se(t.expr);return;case"ident":case"literal":return}}function tm(e){for(const{condition:t}of e.allows)t&&se(t);for(const t of e.functions){for(const n of t.lets)se(n.value);se(t.body)}for(const t of e.children)tm(t)}function PE(e){let t=e,n=[],r=[],s=[],i=xa(t);if(i._version!=="2+modules"){if(i._root.functions.some(a=>a.unresolvedImport!==void 0))throw new SyntaxError("Import statements require rules_version = '2+modules'.")}else{const a=_h(t);if(!a.success)throw new SyntaxError(`Storage rules module resolution failed (${a.error.code}): ${a.error.message}`);t=a.data.resolved,n=a.data.modules,r=a.data.bundledModules,s=a.data.evidenceIds,i=xa(t)}tm(i._root);const o=DE(t,n,r,s,i);return{rules:i,resolution:o}}function DE(e,t,n,r,s){const i=new Set;for(const o of r)o.startsWith("storage-rules#")&&i.add(o);return em(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 nm="pyric-default",Bi=Symbol.for("pyric/storage/target");function Wt(e){return e.currentAuth?.()??e.context.auth}const TE=Symbol.for("pyric.storage.service-caches"),ME=globalThis,gn=ME[TE]??={openServices:new WeakMap,hostBackends:new WeakMap,scopedServices:new WeakMap,sandboxHandles:new WeakMap,bareSandboxHandles:new WeakMap,adminContextHandles:new WeakMap,bareAdminHandles:new WeakMap},Uu=gn.openServices,LE=gn.hostBackends,Bu=gn.scopedServices;function UE(e,t,n){let r=Bu.get(e);r||(r=new Map,Bu.set(e,r));let s=r.get(t);return s||(s=n.then(i=>{const o=i.backend.scoped?i.backend.scoped(t):i.backend;return new Qp(o,i.rules,i.crossServiceIam)}),r.set(t,s)),s}gn.sandboxHandles;gn.bareSandboxHandles;function Fu(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 BE(e,t,n){const r=Uu.get(e);if(r!==void 0)return Fu("rules","rules source",t.rules,r.rulesSource,n),Fu("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let i=null,o=null;const a=t.rules;if(typeof a=="string"&&a.length>0){const m=PE(a);i=m.rules,o=m.resolution}const u=t.crossServiceIam??"granted",d=LE.get(e);let h;d!==void 0?h=Promise.resolve(d):h=SE(t.dbName??xE(t.projectId),t.bucket??nm);const p=h.then(m=>new Qp(m,i,u));return Uu.set(e,{service:p,rulesSource:t.rules??null,rulesResolution:o,crossServiceIam:u}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await p).backend.reset()}}),p}function wo(e){return e instanceof yw||"sandbox"in e&&e.sandbox!==void 0}const vo=gn.adminContextHandles,xo=gn.bareAdminHandles;function FE(e,t={}){const n=!wo(e),r=wo(e)?e.sandbox:e,s=BE(r,t,"getAdminStorageSandbox"),i=t.bucket??nm;if(n){const p=xo.get(r)?.get(i);if(p)return p}const o=wo(e)?e:r.withAuth(null),a=o.operationContext.authLens.mode==="admin"?o:Nh(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),l=vo.get(o)?.get(i);if(l)return l;const u=UE(r,i,s),d={kind:"sandbox",sandbox:r,context:a,bucket:i,servicePromise:u,admin:!0},h=Object.freeze({[Bi]:d});let f=vo.get(o);if(f||(f=new Map,vo.set(o,f)),f.set(i,h),n){let p=xo.get(r);p||(p=new Map,xo.set(r,p)),p.set(i,h)}return h}function Ht(e,t){const n=gw(t,na(e.context.operationContext));return{...t,...na(n),service:"storage"}}function Le(e){const t=e[Bi];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Kt(e){return Le(e).servicePromise}function qE(e){return`storage/${e}`}class Rt extends Error{code;constructor(t,n){const r=qE(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,Rt.prototype)}}function rm(e){return new Rt("object-not-found",`no object at "${e}".`)}function qu(e,t,n){return new Rt("unauthorized",sE(`${e} "${t}" denied by rules${n}`))}function Fi(e){return new Rt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Vu(){return new Rt("canceled","User canceled the upload/download.")}const _s="([A-Za-z0-9.\\-_]+)",VE=e=>e,WE=[{pattern:new RegExp(`^gs://${_s}(?:/(.*))?$`,"i"),path:VE},{pattern:new RegExp(`^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/${_s}/o(?:/([^?#]*).*)?$`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://(?:storage\\.googleapis\\.com|storage\\.cloud\\.google\\.com)/${_s}/([^?#]*)`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://[^/?#]+/__pyric/storage/v0/b/${_s}/o/([^?#]+)`),path:decodeURIComponent}];function zE(e){for(const t of WE){const n=t.pattern.exec(e);if(n!==null)return{bucket:n[1],path:t.path(n[2]??"")}}}const HE=/^[A-Za-z]+:\/\//,Wc=/^data:[^,]*,/i;function Wu(e,t){return new Rt("invalid-url",`Invalid URL '${e}'. ${t}`)}function KE(e){return HE.test(e)||Wc.test(e)}function GE(e){if(Wc.test(e))throw Wu(e.length>64?`${e.slice(0,64)}...`:e,"A data: URI carries an object's bytes, not its location. Reference the object by its path or its gs:// URL.");const n=zE(e);if(n!==void 0)return n;throw Wu(e,"Expected a gs:// URL or a Storage download URL.")}function _a(e,t){const n=e??"";if(!KE(n))return n;const s=Wc.test(n);if(!t&&!s)throw new Rt("invalid-argument","To use ref(service, url), the first argument must be a Storage instance.");return GE(n).path}function Mr(e,t){return YE(e)?(Le(e.storage),new Lr(e.storage,JE(e.fullPath,_a(t,!1)))):(Le(e),new Lr(e,sm(_a(t,!0))))}class Lr{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Le(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 Lr(this.storage,n)}get root(){return this.fullPath===""?this:new Lr(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function sm(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function JE(e,t){const n=sm(t);return e===""?n:n===""?e:`${e}/${n}`}function YE(e){if(e===null||typeof e!="object"||Bi in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}const hi=new WeakMap;function Bt(e){hi.get(e)?.progress()}function pi(e){const t=hi.get(e);t?.delivered(void 0,{}),t?.progress()}function Hn(e,t){return(n,...r)=>{const s=Zr.begin({app:n.storage??n.port??n,method:e,kind:"operation",source:{service:"storage",target:`${n.bucket}/${n.fullPath}`,key:`storage:${n.bucket}/${n.fullPath}`}});try{const i=t(n,...r);return e==="uploadBytesResumable"&&hi.set(i,s),i.then(o=>{const a=QE(e,o);s.delivered(void 0,e.startsWith("get")||e==="listAll"?a:{}),e==="uploadBytesResumable"&&s.progress(),s.complete(e.startsWith("get")||e==="listAll"?void 0:a)},()=>{s.fail(),hi.delete(i)}),i}catch(i){throw s.fail(),i}}}function QE(e,t){if(e==="getBytes"&&t instanceof ArrayBuffer)return{downloadedBytes:t.byteLength};if(e==="getBlob"&&t&&typeof t=="object"&&"size"in t&&typeof t.size=="number")return{downloadedBytes:t.size};if(e.startsWith("upload")&&t&&typeof t=="object"&&"metadata"in t){const n=t.metadata;if(typeof n.size=="number")return{uploadedBytes:n.size}}return{}}class z{message;constructor(t){this.message=t}}function K(e){return e instanceof z}function mi(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}class B extends Error{}class cs extends B{}class ls extends B{}class zu extends ls{position;constructor(t,n){super(t),this.position=n}}function XE(e){return e instanceof B&&!(e instanceof cs)&&!(e instanceof ls)}function Ue(e){return new B(bw(e))}function bn(e){if(e.args.length!==0)throw new B(`${e.method}() expects no arguments`)}function Ze(e,t){return dt(e.args,t)}function us(e,t){const n=Ze(e,t);return K(n)||t.expressionBudget?.node(e),n}function Oe(e,t){if(bn(t),e instanceof ct){const n=e.callMethod(t.method,[]);if(n!==ra)return n}throw Ue(t.method)}const ZE=/^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|\$\(([A-Za-z_][A-Za-z0-9_]*)\))$/;class He extends ct{path;typeName="path";bindings;constructor(t,n={}){super(),this.path=t,this.bindings=n}get segments(){return this.path.split("/").filter(Boolean)}bind(t){const n=[],r={...this.bindings};for(const s of this.segments){const i=ZE.exec(s);if(!i){n.push(s);continue}const o=i[1]??i[2];if(Object.hasOwn(t,o)){const a=t[o];if(a==null||typeof a!="string"&&typeof a!="number")throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const l=String(a);n.push(l),r[o]=l}else n.push(s)}return new He("/"+n.join("/"),r)}valueOf(){return NaN}toJSON(){return{__type:"path",path:this.toString()}}equals(t){return(t instanceof He||t instanceof ct&&t.typeName==="path")&&String(t)===this.toString()}toString(){return this.path.startsWith("/")?this.path:`/${this.path}`}}function ej(e,t,n){if(!(e instanceof He))throw Ue("bind");const r=Ze(t,n);if(K(r))return r;if(r.length!==1)throw new B(`Incorrect number of arguments. Received: ${r.length}. Expected: path.bind(map).`);const[s]=r;if(!qt(s))return new z("path.bind() requires a map argument");try{return e.bind(s)}catch(i){return new z(i.message)}}const tj={bind:ej};function im(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function nj(e){return im({size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Hu(e.timeCreated),updated:Hu(e.updated)})}function Hu(e){if(e===void 0)return;const t=Date.parse(e);if(!Number.isNaN(t))return Rr.fromMillis(t)}function rj(e,t){const n=e.request.auth;let r;return n==null?r=new z("Property auth is undefined on object."):r=Oi(n),{auth:r,resource:e.request.resource!==void 0?im(e.request.resource):new z("Property resource is undefined on object."),method:e.request.method,path:new He(e.request.path),time:Rr.fromMillis(t)}}const sj=["addedKeys","affectedKeys","changedKeys","removedKeys","unchangedKeys"];function ij(e,t,n){return e instanceof es?zc(e,t,n):(bn(t),typeof e=="string"||Array.isArray(e)?e.length:qt(e)?Object.keys(e).length:Oe(e,t))}function Ku(e,t,n){if(!qt(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=vw(t.method,e,r);if(s instanceof xw)throw new B(s.message);return s}function zc(e,t,n){const r=Ze(t,n);if(K(r))return r;const s=Sw(e,t.method,r);if(s instanceof kw)throw new B(s.message);return s}const oj={concat:(e,t)=>Cw(e,t),join:(e,t)=>jw(e,t),removeAll:(e,t)=>Ew(e,t)};function _o(e,t,n){if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=oj[t.method](e,r);if(s instanceof Ah)throw new B(s.message);return s}function aj(e,t,n){if(!qt(e))throw Ue(t.method);if(t.args.length!==2)throw new B("get() expects a key and default value");const r=Ze(t,n);if(K(r))return r;const[s,i]=r;if(typeof s=="string")return Object.hasOwn(e,s)&&e[s]!==void 0?e[s]:i;if(Array.isArray(s)){for(const a of s)if(typeof a!="string")throw new B("get() key list elements must be strings");let o=e;for(const a of s){if(!qt(o)||!Object.hasOwn(o,a)||o[a]===void 0)return i;o=o[a]}return o}throw new B("get() key must be a string or list of strings")}function So(e,t,n){if(e instanceof es)return zc(e,t,n);if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=_w(t.method,e,r);if(s instanceof Ah)throw new B(s.message);return s}function cj(e,t){if(!Array.isArray(e))throw Ue(t.method);if(t.args.length!==0)throw new B(`Incorrect number of arguments. Received: ${t.args.length}. Expected: list.toSet().`);return new es(e)}function lj(e,t,n){if(!(e instanceof es))throw Ue(t.method);return zc(e,t,n)}function uj(e,t,n){if(!qt(e))throw Ue(t.method);if(t.args.length!==1)throw new B("diff() expects one map argument");const r=Ze(t,n);if(K(r))return r;const[s]=r;if(!qt(s))throw new B(`diff() argument must be a map, got ${De(s)}`);return new Oh(s,e)}function dj(e,t){if(bn(t),!(e instanceof Oh))throw Ue(t.method);return e[t.method]()}function Gu(e,t){return Object.fromEntries(e.map(n=>[n,t]))}const fj={concat:_o,diff:uj,get:aj,hasAll:So,hasAny:So,hasOnly:So,join:_o,keys:Ku,removeAll:_o,size:ij,toSet:cj,values:Ku,...Gu([...ww],lj),...Gu(sj,dj)};function hj(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}function pj(e,t,n,r){const i=f=>f*Math.PI/180,o=i(e),a=i(n),l=i(n-e),u=i(r-t),d=Math.sin(l/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}function Ur(e){return e instanceof yi?{latitude:e.latitude,longitude:e.longitude}:e instanceof $h?{latitude:e.lat,longitude:e.lng}:null}function mj(e,t){const n=us(e,t);if(K(n))return n;if(e.method!=="value")return new z(`unsupported latlng.${e.method}()`);const[r,s]=n.map(hj);return n.length!==2||r===void 0||s===void 0||!Number.isFinite(r)||!Number.isFinite(s)?new z("latlng.value() expects (latitude: number, longitude: number)"):r<-90||r>90?new z(`Latitude must be in the range [-90, 90], got ${r}.`):s<-180||s>180?new z(`Longitude must be in the range [-180, 180], got ${s}.`):new yi(r,s)}class yi extends ct{latitude;longitude;typeName="latlng";constructor(t,n){super(),this.latitude=t,this.longitude=n}valueOf(){return NaN}toJSON(){return{__type:"latlng",latitude:this.latitude,longitude:this.longitude}}equals(t){const n=Ur(t);return n!==null?n.latitude===this.latitude&&n.longitude===this.longitude:t instanceof ct&&t.typeName==="latlng"&&t.latitude===this.latitude&&t.longitude===this.longitude}toString(){return`[${this.latitude}, ${this.longitude}]`}}function yj(e,t){const n=Ur(e);if(n===null)throw Ue("latitude");return bn(t),new Me(n.latitude)}function gj(e,t){const n=Ur(e);if(n===null)throw Ue("longitude");return bn(t),new Me(n.longitude)}function bj(e,t,n){const r=Ur(e);if(r===null)throw Ue("distance");const s=Ze(t,n);if(K(s))return s;if(s.length!==1)throw new B(`Incorrect number of arguments. Received: ${s.length}. Expected: latlng.distance(latlng).`);const i=Ur(s[0]);return i===null?new z("latlng.distance() requires a latlng argument"):new Me(pj(r.latitude,r.longitude,i.latitude,i.longitude))}const wj={distance:bj,latitude:yj,longitude:gj};function Sa(e){if(e==null)return e;if(typeof e=="number")return Number.isInteger(e)?e:new Me(e);if(e instanceof Date)return Rr.fromMillis(e.getTime());if(e instanceof Uint8Array)return new $i(e);if(e instanceof $h)return new yi(e.lat,e.lng);if(e instanceof Iw)return new He(e.toString());if(e instanceof ct)return e;if(typeof e=="object"){if(Array.isArray(e))return e.map(Sa);const t=e,n=Object.keys(t),r=t.latitude??t._latitude,s=t.longitude??t._longitude;if(t.__type==="latlng"||n.length===2&&typeof r=="number"&&typeof s=="number")return new yi(r,s);if(t.__type==="path"||n.length===1&&typeof t.path=="string"&&t.path.startsWith("/databases/"))return new He(t.path);const i={};for(const[o,a]of Object.entries(t))i[o]=Sa(a);return i}return e}function vj(e,t){if(t.expressionBudget?.node(e),e.method!=="get"&&e.method!=="exists")throw new cs(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new B(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new B(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];let r;if(n.kind==="path"){t.expressionBudget?.node(n);for(const i of n.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(n);r=Ju(n,t)}else{const i=rt(n,t);if(K(i))return i;if(i instanceof He||i instanceof ct&&i.typeName==="path"){const a=(i instanceof He?i.path:String(i)).split("/").filter(Boolean).map(l=>({kind:"literal",value:l}));r=Ju({segments:a},t)}else return new z(`Function not found error: Name: [${e.method}].`)}if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new ls("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:Sa(s)}}function Ju(e,t){const n=dt(e.segments.flatMap(o=>o.kind==="literal"?[]:[o.expr]),t);if(K(n))throw new B(n.message);let r=0;const s=e.segments.map(o=>{if(o.kind==="literal")return o.value;const a=n[r++];if(typeof a=="string")return a;if(typeof a=="number")return String(a);throw new B(`Firestore path interpolation resolved to ${De(a)} (expected a string)`)});if(s.length<4||s[0]!=="databases"||s[2]!=="documents")throw new B(`malformed Firestore path — expected /databases/<db>/documents/... , got /${s.join("/")}`);if(s[1]!=="(default)")throw new B(`Storage rules may access only the default Firestore database, got ${s[1]}`);const i=s.slice(3);if(i.length===0||i.length%2!==0)throw new B(`Firestore path does not point at a document (needs an even segment count): ${i.join("/")}`);return i.join("/")}const xj=new Set(["crc32","crc32c","md5","sha256"]);function _j(e,t){if(!xj.has(e.method))throw new cs(`unsupported method hashing.${e.method}()`);const n=us(e,t);if(K(n))return n;if(n.length!==1)throw new B(`hashing.${e.method}() expects a single string or bytes argument`);const[r]=n;if(typeof r!="string"&&!(r instanceof $i))throw new B(`Unsupported operation error. Received: hashing.${e.method}(${De(r)}). Expected: hashing.${e.method}(bytes), hashing.${e.method}(string).`);return Rw(e.method,[r])}const Sj={toBase64:Oe,toHexString:Oe};function kj(e,t){const n=us(e,t);if(K(n))return n;const r=Nw(e.method,n);return r instanceof Aw?new z(r.message):r}function ds(e,t){if(typeof e!="string")throw Ue(t.method);return e}function om(e,t){if(e.args.length!==1)throw new B(`${e.method}() expects a single pattern argument`);const n=Ze(e,t);if(K(n))return n;const[r]=n;if(typeof r!="string")throw new B(`${e.method}() pattern must be a string`);return r}function Ej(e,t,n){const r=ds(e,t),s=om(t,n);if(typeof s!="string")return s;try{return Ow(s,r)}catch(i){throw new B(i.message)}}function jj(e,t,n){const r=ds(e,t),s=om(t,n);return typeof s!="string"?s:r.split(am("split",s,s))}function Cj(e,t,n){const r=ds(e,t),s=Ze(t,n);if(K(s))return s;const[i,o]=s;if(s.length!==2||typeof i!="string"||typeof o!="string")throw new B("replace() expects (pattern: string, replacement: string)");const a=am("replace",i,i,"g"),l=Rj(a);return r.replace(a,(...u)=>{const d=u.slice(0,l+1);return Nj(o,d,Ij(u[u.length-1]))})}function Ij(e){return typeof e=="object"&&e!==null?e:{}}function Rj(e){const t=new RegExp(`${e.source}|`).exec("");return t===null?0:t.length-1}function Nj(e,t,n){const r=t.length-1;let s="",i=0;for(;i<e.length;){const o=e[i];if(o==="\\"){if(i+1>=e.length)throw new B("replace() replacement ends with an escape character");s+=e[i+1],i+=2;continue}if(o!=="$"){s+=o,i+=1;continue}const a=e[i+1];if(a==="{"){const d=e.indexOf("}",i+2);if(d===-1)throw new B(`replace() replacement has an unclosed group name: ${e.slice(i)}`);const h=e.slice(i+2,d);if(!Object.hasOwn(n,h))throw new B(`replace() replacement names no group: ${e.slice(i,d+1)}`);s+=n[h]??"",i=d+1;continue}if(a===void 0||a<"0"||a>"9")throw new B(`replace() replacement has an illegal group reference: ${e.slice(i)}`);let l=Number(a),u=i+2;for(;u<e.length&&e[u]>="0"&&e[u]<="9";){const d=l*10+Number(e[u]);if(d>r)break;l=d,u+=1}if(l>r)throw new B(`replace() replacement names group ${l}, but the pattern has ${r}`);s+=t[l]??"",i=u}return s}function ko(e,t){const n=ds(e,t);return bn(t),t.method==="lower"?n.toLowerCase():t.method==="upper"?n.toUpperCase():n.trim()}function Aj(e,t){const n=ds(e,t);return bn(t),$i.fromUtf8(n)}function Oj(e){let t=!1,n=!1,r=!1,s=!1,i=!1,o=0;for(;o<e.length;){const l=e[o];if(l==="\\"){const u=e[o+1];if(!t&&u!==void 0&&u>="1"&&u<="9")return{unsupported:"backreference",inlineFlags:""};o+=2,n=!1;continue}if(t){l==="]"&&!n&&(t=!1),n=!1,o++;continue}if(l==="["){t=!0,o++,e[o]==="^"&&o++,n=!0;continue}if(l==="("&&e[o+1]==="?"){const u=e.slice(o+2);if(u.startsWith("=")||u.startsWith("!")||u.startsWith("<=")||u.startsWith("<!"))return{unsupported:"lookaround",inlineFlags:""};const d=/^([imsU-]+)[):]/.exec(u);if(d){let h=!1;for(const f of d[1])f==="-"?h=!0:f==="i"?r=!h:f==="m"?s=!h:f==="s"&&(i=!h)}}o++}return{unsupported:null,inlineFlags:`${r?"i":""}${s?"m":""}${i?"s":""}`}}function am(e,t,n,r=""){const{unsupported:s,inlineFlags:i}=Oj(t);if(s!==null)throw new B(`${e}() pattern uses an RE2-unsupported construct (${s}) that production would reject`);const o=Array.from(new Set((r+i).split(""))).join("");try{return new RegExp(Rh(n),o)}catch(a){throw new B(`${e}() invalid regex pattern: ${a.message}`)}}const $j={lower:ko,matches:Ej,replace:Cj,split:jj,toUtf8:Aj,trim:ko,upper:ko},Yu=["w","d","h","m","s","ms","ns"],Pj=-621355968e5,Dj=0xe677d21fdbff,Qu=315576e6;function Tj(e,t){const n=us(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==1||typeof n[0]!="number"||!Number.isInteger(n[0]))throw new B("timestamp.value() expects (epochMillis: number)");const r=n[0];if(r<Pj||r>Dj)throw new B("timestamp.value() out of range [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999Z]");return Rr.fromMillis(r)}if(e.method==="date"){if(n.length!==3||!n.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new B("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;try{return Rr.fromYMD(r,s,i)}catch(o){throw new B(o.message)}}throw new B(`unsupported timestamp.${e.method}()`)}function Mj(e,t){const n=us(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==2||typeof n[0]!="number"||!Number.isInteger(n[0])||typeof n[1]!="string")throw new B("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n;if(!Yu.includes(s))throw new B(`duration.value() got unknown unit "${s}", expected one of ${Yu.join(", ")}`);const i=bs.fromValue(r,s);if(!Number.isFinite(i.seconds)||Math.abs(i.seconds)>Qu)throw new B("duration.value() exceeds maximum range of +/-10000 years");return i}if(e.method==="time"){if(n.length!==4||!n.every(l=>typeof l=="number"&&Number.isInteger(l)))throw new B("duration.time() expects (hours, minutes, seconds, nanos) numbers");const[r,s,i,o]=n,a=bs.fromTime(r,s,i,o);if(!Number.isFinite(a.seconds)||Math.abs(a.seconds)>Qu)throw new B("duration.time() exceeds maximum range of +/-10000 years");return a}if(e.method==="abs"){if(n.length!==1||!(n[0]instanceof bs))throw new B("duration.abs() expects a single duration");return bs.abs(n[0])}throw new B(`unsupported duration.${e.method}()`)}const Lj={date:Oe,day:Oe,dayOfWeek:Oe,dayOfYear:Oe,hours:Oe,minutes:Oe,month:Oe,nanos:Oe,seconds:Oe,time:Oe,toMillis:Oe,year:Oe},Uj=new Map([["duration",Mj],["firestore",vj],["hashing",_j],["latlng",mj],["math",kj],["timestamp",Tj]]),Bj=Vj([Sj,fj,wj,tj,$j,Lj]);function Fj(e,t){const n=qj(e,t);if(n!==void 0)return n(e,t);const r=Bj.get(e.method);if(r===void 0)throw new cs(`unsupported method .${e.method}()`);const s=Br(e.target,t);return K(s)?(Ze(e,t),s):r(s,e,t)}function qj(e,t){if(e.target.kind!=="ident")return;const n=e.target.name;if(!(Object.hasOwn(t.locals,n)||Object.hasOwn(t.params,n)))return Uj.get(n)}function Vj(e){const t=new Map;for(const n of e)for(const[r,s]of Object.entries(n)){if(t.has(r))throw new Error(`storage rules method .${r}() has two evaluators`);t.set(r,s)}return t}const Wj=new Set(["timestamp","duration","bytes","latlng","path"]);function zj(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 Me||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Me||typeof e=="number";case"list":return Array.isArray(e);case"set":return e instanceof es;case"map":return qt(e);case"null":return e===null}return Wj.has(t)?e instanceof ct&&e.typeName===t:new z(`'is ${t}' is not supported by the storage evaluator.`)}function Xu(e){return e instanceof ct&&!(e instanceof Me)}function Hj(e,t,n){if(t instanceof ct){const r=t.binaryOp(e,n);if(r!==ra)return r}if(e==="+"&&n instanceof ct){const r=n.binaryOp(e,t);if(r!==ra)return r}return Hc(e,t,n)}function Hc(e,t,n){return new z(`Unsupported operation error. Received: ${De(t)} ${e} ${De(n)}.`)}function Zu(e){return e instanceof Me}function Kj(e,t,n){if(e==="+"&&typeof t=="string"&&typeof n=="string")return t+n;const r=mi(t),s=mi(n);if(r===void 0||s===void 0)return Hc(e,t,n);const i=Zu(t)||Zu(n);let o;switch(e){case"+":o=r+s;break;case"-":o=r-s;break;case"*":o=r*s;break;case"/":if(!i&&s===0)return new z(Ol);o=i?r/s:Math.trunc(r/s);break;case"%":if(!i&&s===0)return new z(Ol);o=r%s;break}return i?new Me(o):o}function Gj(e,t,n){const r=mi(t),s=mi(n);return r!==void 0&&s!==void 0?ed(e,r,s):typeof t=="string"&&typeof n=="string"?ed(e,t,n):Hc(e,t,n)}function ed(e,t,n){switch(e){case"<":return t<n;case">":return t>n;case"<=":return t<=n;case">=":return t>=n}}function Jj(e){return e.split("/").filter(t=>t.length>0)}function vn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function td(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const o=e[i];if(o.kind==="wildcard"){const a=e.length-1-i,l=t.length-r-a;if(l<0)return null;const u=t.slice(r,r+l);s[o.name]=new He("/"+u.join("/")),r+=l;continue}if(r>=t.length)return null;if(o.kind==="literal"){if(t[r]!==o.value)return null;r++}else s[o.name]=t[r],r++}return{left:t.slice(r),params:s}}function cm(e,t,n=new Date,r){const s=n.getTime(),i=Jj(t.request.path),o=[],a=new Set,l=new $w((g,b)=>new zu(g,b));let u,d=!1,h;const f=new Set(Lu(t.request.method));function p(g,b,w){if(d)return!1;const x=td(g.segments,b,w);if(!x)return!1;const v=x.params,_=x.left;if(_.length===0)for(const k of g.allows){const I=new Set(k.verbs.flatMap(Lu));if(![...f].some(R=>I.has(R)))continue;let P;try{let R=!0;if(k.condition&&(R=rt(k.condition,{input:t,now:s,params:v,matchParams:v,scopeKind:"match",locals:{},funcs:g.visibleFuncs??new Map,firestoreLookup:r,firestoreAccesses:a,expressionBudget:l})),typeof R=="boolean")P=R;else{let E;K(R)?E=R:E=new z(`Allow condition expected bool, got ${De(R)}.`),h??=E.message,o.push(`match ${vn(g.segments)} ${t.request.method}: ${E.message}`);continue}}catch(R){if(R instanceof zu)return d=!0,h===void 0?(u={message:R.message,position:R.position},o.push(`match ${vn(g.segments)} ${t.request.method}: ${Dw(R.message,R.position)}`)):o.push(`match ${vn(g.segments)} ${t.request.method}: ${R.message} Reached after an earlier allow rule raised an error; production reports that earlier error: ${h}`),!1;if(R instanceof ls)return d=!0,o.push(`match ${vn(g.segments)} ${t.request.method}: ${R.message}`),!1;if(R instanceof B){h??=R.message,o.push(`match ${vn(g.segments)} ${t.request.method}: ${R.message}`);continue}throw R}if(P)return!0;o.push(`match ${vn(g.segments)} ${t.request.method}: condition false`)}const S=g.segments[g.segments.length-1];if(g.children.length>0&&S!==void 0&&S.kind==="wildcard"){const k=g.segments.slice(0,-1),I=td(k,b,w);if(I){const O=I.left;for(let P=O.length;P>=0;P--){const R=O.slice(0,P),E=O.slice(P),j={...I.params,[S.name]:new He("/"+R.join("/"))};for(const $ of g.children)if(p($,E,j))return!0}return!1}}for(const k of g.children)if(p(k,_,v))return!0;return!1}const m=p(e._root,i,{});return!m&&o.length===0&&o.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:m,reasons:o,evaluatedExpressions:l.evaluated,...u!==void 0?{resourceLimit:{kind:"expressions",limit:Pw,message:u.message,...u.position===void 0?{}:{line:u.position.line,column:u.position.column}}}:{}}}function Yj(e,t){const n=Fw(e,t);return n instanceof Ph?new z(n.message):n}function rt(e,t){const n=t.expressionBudget;if(!n)return Eo(e,t);if(e.kind==="call")return n.call(e),Eo(e,t);let r;try{r=Eo(e,t)}catch(s){throw s instanceof ls||n.node(e),s}return n.node(e),r}function Eo(e,t){switch(e.kind){case"literal":return e.value;case"ident":{if(Object.hasOwn(t.locals,e.name))return t.locals[e.name];if(t.scopeKind!=="global"){if(e.name==="request")return rj(t.input,t.now);if(e.name==="resource")return t.input.resource===null?new z("Null value error."):nj(t.input.resource)}return Object.hasOwn(t.params,e.name)?t.params[e.name]:new z(`Identifier ${e.name} is undefined.`)}case"member":{const n=rt(e.target,t);return K(n)?n:n==null?new z("Null value error."):Yj(n,e.name)}case"index":{const n=dt([e.index,e.target],t);if(K(n))return n;const[r,s]=n;if(s==null)return new z("Null value error.");const i=Bw(s,r);return i instanceof Ph?new z(i.message):i}case"call":return Qj(e,t);case"methodcall":return Fj(e,t);case"path":{t.expressionBudget?.node(e);for(const i of e.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(e);const n=dt(e.segments.flatMap(i=>i.kind==="literal"?[]:[i.expr]),t);if(K(n))return n;let r=0;const s=[];for(const i of e.segments){if(i.kind==="literal"){s.push(i.value);continue}const o=n[r++];if(typeof o!="string"&&typeof o!="number")return new z(`Path interpolation resolved to ${De(o)} (expected a string)`);s.push(String(o))}return new He(`/${s.join("/")}`)}case"unary":{const n=rt(e.arg,t);if(e.op==="!"){if(K(n))throw new B(n.message);if(typeof n!="boolean")throw new B(`Unary '!' expects a boolean, got ${De(n)}.`);return!n}return K(n)?n:e.op==="-"?n instanceof Me?new Me(-n.value):typeof n!="number"?new z(`Unary '-' applied to ${De(n)}.`):-n:void 0}case"ternary":{t.expressionBudget?.ternary(e);const n=rt(e.cond,t);return K(n)?n:typeof n!="boolean"?new z(`Ternary condition expected bool, got ${De(n)}.`):n?rt(e.then,t):(t.expressionBudget?.ternaryElse(e),rt(e.else,t))}case"in":{const n=dt([e.collection,e.element],t);if(K(n))return n;const[r,s]=n,i=Lw(s,r);return i instanceof Uw?new z(i.message):i}case"is":{const n=rt(e.value,t);return K(n)?n:zj(n,e.typeName)}case"list":return dt(e.elements,t);case"map":{const n=dt(e.entries.flatMap(s=>[s.key,s.value]),t);if(K(n))return n;const r=[];for(let s=0;s<n.length;s+=2){const i=n[s];if(typeof i!="string")return new z(`Map literal key is ${De(i)} (expected a string).`);r.push([i,n[s+1]])}return Mw(r)}case"slice":{const n=dt([e.target,e.start,e.end],t);if(K(n))return n;const[r,s,i]=n;if(typeof s!="number"||typeof i!="number"||!Number.isInteger(s)||!Number.isInteger(i))return new z("Slice bounds must be integers.");if(Array.isArray(r)||typeof r=="string"){const o=Tw(s,i,r.length);return o?new z(o):r.slice(s,i)}return new z(`Slice applied to ${De(r)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return nd(e,!1,t);if(e.op==="||")return nd(e,!0,t);const n=dt([e.left,e.right],t);if(K(n))return n;const[r,s]=n;if(e.op!=="=="&&e.op!=="!="&&(Xu(r)||Xu(s)))return Hj(e.op,r,s);switch(e.op){case"==":return $l(r,s);case"!=":return!$l(r,s);case"<":case">":case"<=":case">=":return Gj(e.op,r,s);case"+":case"-":case"*":case"/":case"%":return Kj(e.op,r,s)}}}}function nd(e,t,n){const{left:r,right:s}=e,i=rd(r,n);if(i===t)return t;n.expressionBudget?.logicalRight(e);const o=rd(s,n);return o===t?t:K(i)?i:o}function rd(e,t){const n=Br(e,t);return K(n)?n:typeof n!="boolean"?new z(`Expected a boolean '&&'/'||' operand, got ${De(n)}.`):n}function Br(e,t){try{return rt(e,t)}catch(n){if(XE(n))return new z(n.message);throw n}}function dt(e,t){const n=[];let r;for(const s of e){const i=Br(s,t);K(i)&&(r??=i),n.push(i)}return r??n}function Qj(e,t){const n=t.funcs.get(e.name);if(!n)return Xj(e,t);if(n.unresolvedImport!==void 0)throw new cs(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)return new z(`Incorrect number of arguments. Received: ${e.args.length}. Expected: ${e.name}(${n.params.join(", ")}).`);const r=e.args.map(l=>Br(l,t)),s={};n.params.forEach((l,u)=>{s[l]=r[u]});const i=t.matchParams??t.params,o={};if(n.declCaptures)for(const l of n.declCaptures)Object.hasOwn(i,l)&&(o[l]=i[l]);const a={input:t.input,now:t.now,params:o,matchParams:i,scopeKind:n.scopeKind??"match",locals:s,funcs:n.declScope??new Map,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses,expressionBudget:t.expressionBudget};for(const l of n.lets)s[l.name]=Br(l.value,a),a.expressionBudget?.letBinding(l);return rt(n.body,a)}function Xj(e,t){if(e.name==="path"&&e.args.length===1){const i=rt(e.args[0],t);return K(i)?i:typeof i=="string"?i.includes("//")?new z("Invalid argument error in path(): empty path segment."):new He(i):new z(`path() expects a string, got ${De(i)}.`)}const n=qw(e.name);if(!n)return new z(`Function not found error: Name: [${e.name}].`);const r=dt(e.args,t);if(K(r))return r;const s=Vw(n,r);return s instanceof Ww?new z(s.message):s}function fs(e,t,n,r){const s=n?.kind==="sandbox"?Ht(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Ss(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules)throw Ss(n,t,"deny",["No Storage rules configured; default deny."],"user",!1,s),qu(t.request.method,t.request.path," — No Storage rules configured; default deny.");const i=n?Zj(t,n.bucket):t,o=n?Te(n.sandbox).date():void 0,a=cm(e.rules,i,o,eC(n,e.crossServiceIam));if(!a.allowed){Ss(n,t,"deny",a.reasons,"user",!0,s);const l=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw qu(t.request.method,t.request.path,l)}Ss(n,t,"allow",a.reasons,"user",!0,s)}function Zj(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Ss(e,t,n,r,s,i,o){if(e)try{pt(e.sandbox,Sh({at:Te(e.sandbox).now(),service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,detail:{bucket:e.bucket},rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:i?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:i?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...o,service:"storage"})}catch{}}function eC(e,t){if(e)return tC(e.sandbox,t)}function tC(e,t){if(t==="denied")return nC();const n=e.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function nC(){const e=t=>{throw new B(`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 Fr(e){return e.admin===!0?"admin":"client"}const rC="identity";function lm(e,t){return e??`inline; filename*=utf-8''${iC(t.split("/").pop()??"")}`}function um(e){return e??rC}const sC=/[A-Za-z0-9!#$&+\-.^_`|~]/;function iC(e){let t="";for(const n of e){if(sC.test(n)){t+=n;continue}for(const r of new TextEncoder().encode(n))t+=`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}function dm(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function qi(e){return e?dm({size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:fm(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:sd(e.generation),metageneration:sd(e.metageneration)}):null}function fm(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 sd(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function oC(e,t){const n=fm(e.fullPath,e.bucket),r={name:n,bucket:e.bucket,size:e.size,contentType:e.contentType,contentDisposition:lm(e.contentDisposition,n??""),contentEncoding:um(e.contentEncoding),contentLanguage:e.contentLanguage??null,cacheControl:e.cacheControl??null,metadata:e.customMetadata??null};return r.generation=null,r.metageneration=null,r.etag=null,dm(r)}function Kc(e,t){return t==="admin"?{...e}:{...e,contentEncoding:um(e.contentEncoding)}}async function aC(e){cC(e,"getMetadata");const t=Le(e.storage),n=Ht(t),r=await Kt(e.storage),s=await r.backend.getMetadata(e.fullPath);if(fs(r,{request:{auth:Wt(t),method:"get",path:e.fullPath},resource:qi(s)},t,n),!s)throw rm(e.fullPath);return Kc(s,Fr(t))}function cC(e,t){if(e.fullPath==="")throw Fi(t)}const lC="application/octet-stream";async function uC(e,t,n,r){return dC(e,t,n,{provenance:r})}async function dC(e,t,n,r={}){const{result:s}=await hm(e,t,n,r);return s}async function hm(e,t,n,{provenance:r,downloadTokens:s}={}){hC(e,"uploadBytes");const i=Le(e.storage),o=s!==void 0;if(o&&Fr(i)!=="admin")throw new Rt("unauthorized","Only the admin plane sets download tokens on upload.");const a=Ht(i,r),l=fC(t,n?.contentType),u=Te(i.sandbox).date(),d=pm({ref:e,blob:l,settable:n,now:u});o&&(d.downloadTokens=s);const h=await Kt(e.storage),f=await h.backend.getMetadata(e.fullPath);fs(h,{request:{auth:Wt(i),method:"create",path:e.fullPath,resource:oC(d)},resource:qi(f)},i,a);const p=await h.backend.put(e.fullPath,l,d,vE(u.getTime()));try{pt(i.sandbox,qn({at:Te(i.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:Wt(i),before:p?.metadata,after:d,detail:{bucket:e.bucket,size:d.size,contentType:d.contentType,overwrite:p!==void 0}}),a)}catch{}return{result:{ref:e,metadata:Kc(d,Fr(i))},replaced:p}}function pm(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=String(Kp((e.now??new Date).getTime())),o=t.name,a=Fr(Le(t.storage))==="client";return{fullPath:t.fullPath,name:o,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||lC,cacheControl:r?.cacheControl,contentDisposition:a?lm(r?.contentDisposition,t.fullPath):r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function fC(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function hC(e,t){if(e.fullPath==="")throw Fi(t)}async function pC(e,t){return Gc(e,"getBlob"),gC(e,t)}async function mC(e,t){Gc(e,"deleteObject");const n=Le(e.storage),r=Ht(n,t),s=await Kt(e.storage),i=await s.backend.getMetadata(e.fullPath);fs(s,{request:{auth:Wt(n),method:"delete",path:e.fullPath},resource:qi(i)},n,r),await s.backend.delete(e.fullPath),mm(e,i,r)}async function yC(e,t,n){Gc(e,"deleteObject");const r=Le(e.storage),s=await Kt(e.storage),i=await s.backend.getMetadata(e.fullPath),o=await s.backend.deleteIfGeneration(e.fullPath,t);return o&&mm(e,i,Ht(r,n)),o}function mm(e,t,n){const r=Le(e.storage);try{pt(r.sandbox,qn({at:Te(r.sandbox).now(),service:"storage",op:"object_delete",path:e.fullPath,auth:Wt(r),before:t??void 0,detail:{bucket:e.bucket}}),n)}catch{}}async function gC(e,t){const n=Le(e.storage),r=Ht(n),s=await Kt(e.storage),i=await s.backend.getMetadata(e.fullPath);fs(s,{request:{auth:Wt(n),method:"get",path:e.fullPath},resource:qi(i)},n,r);const o=await s.backend.getBlob(e.fullPath);if(!o)throw rm(e.fullPath);return typeof t=="number"&&o.size>t?o.slice(0,t):o}function Gc(e,t){if(e.fullPath==="")throw Fi(t)}async function bC(e,t,n,r){const s=(await Kt(e.storage)).backend,i=await s.getMetadata(e.fullPath),o=await s.replaceIfGeneration(e.fullPath,t,n);return o&&wC(e,i,n.metadata,r),o}function wC(e,t,n,r){const s=Le(e.storage);try{pt(s.sandbox,qn({at:Te(s.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:Wt(s),before:t,after:n,detail:{bucket:e.bucket,size:n.size,contentType:n.contentType,overwrite:!0}}),Ht(s,r))}catch{}}async function vC(e,t,n){const r=t.prior;return r!==void 0?bC(e,t.generation,r,n).then(s=>({deleted:!1,restored:s}),s=>({deleted:!1,restored:!1,error:ka(e.fullPath,s,"restore")})):yC(e,t.generation,n).then(s=>({deleted:s,restored:!1}),s=>({deleted:!1,restored:!1,error:ka(e.fullPath,s,"remove")}))}async function xC(e,t,n){return(await vC(e,t,n)).error}const _C={remove:"removing it failed",restore:"restoring the object it replaced failed"};function SC(e){const t=e?.code;if(typeof t=="string")return t}function ka(e,t,n="remove"){const r=SC(t)??"storage/unknown",s=t instanceof Error?t.message:String(t),i=_C[n],o=`${r}: The upload to '${e}' was canceled after it was stored, and ${i}: ${s}`,a=new Error(o,{cause:t});return a.code=r,a}function kC(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 EC{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_sentCommit;_heldOutcome;_error;_ref;_blob;_metadata;_provenance;constructor(t,n,r,s){this._ref=t,this._metadata=r,this._provenance=s;let i;r!==void 0&&(i=r.contentType),this._blob=kC(n,i);const a=pm({ref:t,blob:this._blob,settable:r}),l=Kc(a,Fr(Le(t.storage)));this._promise=new Promise((u,d)=>{this._resolve=u,this._reject=d}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:this._blob.size,state:"running",metadata:l,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{if(!(this._snapshot.state==="running"))return;this._releaseHeldOutcome()||this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._rollBackCanceled().then(r=>this._settleCanceled(r)),!0):!1}on(t,n,r,s){let i,o,a,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Bt(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Bt(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Bt(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{pi(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const a=i.next;try{Bt(this),a(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const a=i.complete;try{pi(this),a()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=this._storeUpload();this._sentCommit=r;const s=await r;this._committing=!1,this._settleCommit(s)}async _storeUpload(){try{if(await Kt(this._ref.storage),this._snapshot.state!=="running")return;const{result:n,replaced:r}=await hm(this._ref,this._blob,this._metadata,{provenance:this._provenance});return{stored:{result:n,prior:r}}}catch(t){return{error:t}}}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){this._report(t);return}n==="paused"&&(this._heldOutcome=t)}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,this._report(t),!0)}_report(t){if(t===void 0){queueMicrotask(()=>this._runStep());return}if("stored"in t){this._updateSnapshot("success",this._snapshot.totalBytes,t.stored.result.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);return}this._fail(t.error)}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}_fail(t){let n;t instanceof Error?n=t:n=new Error(String(t)),this._error=n,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=t??await this._sentCommit;if(!(n!==void 0&&"stored"in n))return Vu();const s={generation:n.stored.result.metadata.generation,prior:n.stored.prior};return await xC(this._ref,s,this._provenance)??Vu()}}function jC(e,t,n,r){if(e.fullPath==="")throw Fi("uploadBytesResumable");return new EC(e,t,n,r)}async function CC(e){const t=e.storage,n=Le(t),r=Ht(n),s=await Kt(t);fs(s,{request:{auth:Wt(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,o=await s.backend.listByPrefix(i),a=[],l=new Set,u=[];for(const d of o){if(!d.fullPath.startsWith(i))continue;const h=d.fullPath.slice(i.length);if(h==="")continue;const f=h.indexOf("/");if(f===-1)a.push(Mr(t,d.fullPath));else{const p=h.slice(0,f),m=`${i}${p}`;l.has(m)||(l.add(m),u.push(Mr(t,m)))}}return u.sort((d,h)=>d.fullPath<h.fullPath?-1:d.fullPath>h.fullPath?1:0),{items:a,prefixes:u}}const IC=Hn("uploadBytes",uC),RC=Hn("uploadBytesResumable",jC),NC=Hn("getBlob",pC),ym=Hn("deleteObject",mC),AC=Hn("getMetadata",aC),Jc=Hn("listAll",CC),OC="/__pyric/storage/v0/b/";function $C(e,t,n){const r=new URLSearchParams({alt:"media"});return`${OC}${encodeURIComponent(e)}/o/${encodeURIComponent(t)}?${r}`}function PC(e){let t="",n=!1,r=!1,s=!1,i=0;for(;i<e.length;){const o=e[i],a=i+1<e.length?e[i+1]:"";if(r){(o===`
|
|
128
|
+
`||o==="\r")&&(r=!1,t+=o),i++;continue}if(s){o==="*"&&a==="/"?(s=!1,i+=2):((o===`
|
|
129
|
+
`||o==="\r")&&(t+=o),i++);continue}if(n){if(o==="\\"){t+=o,a!==""&&(t+=a,i++),i++;continue}o==='"'&&(n=!1),t+=o,i++;continue}if(o==='"'){n=!0,t+=o,i++;continue}if(o==="/"&&a==="/"){r=!0,i+=2;continue}if(o==="/"&&a==="*"){s=!0,i+=2;continue}t+=o,i++}return t}const DC={"\n":"\\n","\r":"\\r"," ":"\\t"};function TC(e){const t=DC[e];return t!==void 0?t:`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}function gm(e){return e===" "||e===" "||e===`
|
|
130
|
+
`||e==="\r"}function MC(e,t){let n=t+1;for(;n<e.length&&gm(e[n]);)n++;const r=e[n];return r==="}"||r==="]"}function LC(e){const t=PC(e);let n="",r=!1,s="",i=0;for(;i<t.length;){const o=t[i];if(r){if(o==="\\"){n+=t.slice(i,i+2),i+=2;continue}o==='"'&&(r=!1);const f=o.charCodeAt(0)<32;n+=f?TC(o):o,i++;continue}o==='"'&&(r=!0);const u=o===","&&(s!==""&&s!=="{"&&s!=="["&&s!==",")&&MC(t,i);u||(n+=o),!u&&!gm(o)&&(s=o),i++}return n}function Ea(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=Array.isArray(e),r=Array.isArray(t);if(n!==r)return!1;if(n&&r){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(!Ea(e[a],t[a]))return!1;return!0}const s=e,i=t,o=Object.keys(s);if(o.length!==Object.keys(i).length)return!1;for(const a of o)if(!Object.prototype.hasOwnProperty.call(i,a)||!Ea(s[a],i[a]))return!1;return!0}const In=Symbol("pyric/firestore/followsCurrentUser"),Sr=Symbol("pyric/firestore/authSessionScope");function mr(e){const t=e.keys().next().value;t!==void 0&&e.delete(t)}const $e=Object.freeze({readThreshold:5,readWindowMs:1e3,duplicateListenerThreshold:3,churnAttachThreshold:4,churnDetachThreshold:3,listenerWindowMs:2e3,maxEventsPerFingerprint:32,criticalReadThreshold:20,criticalDuplicateListenerThreshold:10,criticalChurnThreshold:12});function UC(e,t){for(const n of e.keys())t.delete(n)}function BC(e,t){const n=e.keys().next().value;return n===void 0?!1:(e.delete(n),t.delete(n),!0)}const id=1800;function FC(e){const t=new Map,n=new Map;let r=1;const s=(i,o)=>{const a=i.get(o);if(a!==void 0)return a;i.size>=e&&mr(i);const l=r++;return i.set(o,l),l};return{incidentFingerprint:i=>`activity:#${s(n,i)}`,readTarget:(i,o)=>yr(o===i?i:`${i}|query:#${s(t,o)}`),listenerTarget:i=>{try{const o=JSON.parse(i);if(o.kind==="query"){const a=typeof o.collection=="string"?o.collection:typeof o.path=="string"?o.path:"<unknown>";return yr(JSON.stringify({collection:a,kind:"query",query:`#${s(t,i)}`}))}if(o.kind==="doc"&&typeof o.path=="string")return yr(JSON.stringify({kind:"doc",path:o.path}))}catch{}return JSON.stringify({kind:"unknown",target:`#${s(t,i)}`})},clear:()=>{t.clear(),n.clear()}}}function yr(e){if(e.length<=id)return e;const t=`…#${qC(e)}`;return e.slice(0,id-t.length)+t}function qC(e){let t=2166136261,n=2654435769;for(let r=0;r<e.length;r+=1){const s=e.charCodeAt(r);t=Math.imul(t^s,16777619),n=Math.imul(n^s,2246822507)}return(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}const ks=256,VC=64,WC=8192;function zC(e,t){const n=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Set,l=FC(ks);let u=0,d=!1;const h=_=>{try{t(_)}catch{}},f=(_,S)=>{!i.has(_)&&i.size>=VC&&mr(i),i.set(_,S)},p=(_,S)=>{const k=o.get(_);return k!==void 0?(o.delete(_),k==="critical"||k===S?(o.set(_,k),!1):(o.set(_,S),!0)):(o.size>=ks&&mr(o),o.set(_,S),!0)},m=()=>{n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),u+=1},g=(_,S)=>{if(a.has(_.id))return;if(a.size>=WC&&mr(a),a.add(_.id),_.kind==="session_boundary"){m();return}const k=KC(_);if(!k){const $=HC(_,s);$&&b(_,$,S);return}const I=`segment:${u}|read:${k.method}:${k.targetFingerprint}|actor:${k.actorAuthFingerprint}`;let O=n.get(I);O||(n.size>=ks&&mr(n),O={events:[]},n.set(I,O)),O.events.push({id:_.id,at:_.at});const P=_.at-$e.readWindowMs;for(;O.events.length>0&&O.events[0].at<P;)O.events.shift();if(O.events.length>$e.maxEventsPerFingerprint&&O.events.splice(0,O.events.length-$e.maxEventsPerFingerprint),O.events.length<$e.readThreshold)return;const R=O.events[0],E=O.events[O.events.length-1],j=Object.freeze({fingerprint:l.incidentFingerprint(I),pattern:"repeated-read",confidence:"high",severity:od("repeated-read",O.events.length),service:"firestore",method:k.method,targetFingerprint:l.readTarget(k.path,k.targetFingerprint),actor:k.actor,authLens:gi(k.authLens),authUid:k.authUid,count:O.events.length,windowMs:E.at-R.at,usage:Object.freeze({unit:"document-reads",lowerBound:O.events.length,limitations:Object.freeze(["Observed sandbox reads are a lower bound; production cache and billing behavior are not measured."])}),evidenceEventIds:Object.freeze(O.events.slice(-8).map($=>$.id)),sourceAttribution:ad(k.actor)});f(I,j),!S&&p(I,j.severity)&&h(j)},b=(_,S,k)=>{const I=Ar(S.target),O=l.listenerTarget(I),P=`segment:${u}|listener:${I}|actor:${S.actorAuthFingerprint}`;let R=r.get(P);if(!R){if(r.size>=ks){const N=r.keys().next().value;N!==void 0&&(UC(r.get(N).active,s),r.delete(N))}R={active:new Map,lifecycle:[],saturated:!1},r.set(P,R)}if(S.phase==="attach"){if(R.active.has(S.physicalListenerId))return;R.active.size>=$e.maxEventsPerFingerprint&&BC(R.active,s)&&(R.saturated=!0),R.active.set(S.physicalListenerId,{id:_.id,at:_.at}),s.set(S.physicalListenerId,{listenerId:S.listenerId,target:S.target,actor:S.actor,authLens:S.authLens,authUid:S.authUid,actorAuthFingerprint:S.actorAuthFingerprint})}else R.active.delete(S.physicalListenerId),s.delete(S.physicalListenerId);if(S.phase==="errored"||S.reauthorization)return;R.lifecycle.push({id:_.id,at:_.at,phase:S.phase});const E=_.at-$e.listenerWindowMs;for(;R.lifecycle.length>0&&R.lifecycle[0].at<E;)R.lifecycle.shift();R.lifecycle.length>$e.maxEventsPerFingerprint&&(R.lifecycle.splice(0,R.lifecycle.length-$e.maxEventsPerFingerprint),R.saturated=!0);const j=R.lifecycle.filter(N=>N.phase==="attach").length,$=R.lifecycle.length-j,C=Object.freeze({attaches:j,detaches:$,active:R.active.size,...R.saturated?{isLowerBound:!0}:{}});if(R.active.size>=$e.duplicateListenerThreshold){const N=[...R.active.values()],A=N[0],D=`${P}|duplicate`;w(D,"duplicate-listener",N.length,_.at-A.at,N.map(T=>T.id),k,S,O,C)}if(j>=$e.churnAttachThreshold&&$>=$e.churnDetachThreshold){const N=R.lifecycle[0],A=`${P}|churn`;w(A,"listener-churn",j,_.at-N.at,R.lifecycle.map(D=>D.id),k,S,O,C)}},w=(_,S,k,I,O,P,R,E,j)=>{const $=Object.freeze({fingerprint:l.incidentFingerprint(_),pattern:S,confidence:S==="duplicate-listener"&&k<$e.criticalDuplicateListenerThreshold?"medium":"high",severity:od(S,k),service:"firestore",method:"listen",targetFingerprint:yr(E),actor:R.actor,authLens:gi(R.authLens),authUid:R.authUid,count:k,windowMs:I,listenerBalance:j,usage:Object.freeze({unit:"listener-attaches",lowerBound:k,limitations:Object.freeze(["Listener lifecycle events count attachments; document deliveries and production billing are not measured.",...j.isLowerBound?["Listener retention saturated; reported counts are observed lower bounds."]:[]])}),evidenceEventIds:Object.freeze(O.slice(-8)),sourceAttribution:ad(R.actor)});f(_,$),!P&&p(_,$.severity)&&h($)},x=e.history();for(const _ of x)g(_,!0);x.length>0&&m();const v=e.subscribe(_=>{d||g(_,!1)});return{report:()=>Object.freeze({incidents:Object.freeze([...i.values()])}),dispose:()=>{d||(d=!0,v(),n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),l.clear())}}}function od(e,t){const n=e==="repeated-read"?$e.criticalReadThreshold:e==="duplicate-listener"?$e.criticalDuplicateListenerThreshold:$e.criticalChurnThreshold;return t>=n?"critical":"warning"}function HC(e,t){const n=e.kind==="listener_attach"||e.kind==="listener_detach"||e.kind==="listener_errored",r=e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored");if(!n&&!r||(e.service??"firestore")!=="firestore"||e.planId)return null;let s;if(e.kind==="listener_attach")s="attach";else if(e.kind==="listener_detach")s="detach";else if(e.kind==="listener_errored")s="errored";else if(e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored"))s=e.phase;else return null;const i=vc(e),o=s!=="attach"?t.get(e.listenerId):void 0;if(!(o!==void 0)&&(i.source.kind!=="app"||i.authLens.mode==="admin"))return null;const l=e.activity?.listenerId??o?.listenerId??e.listenerId,u=o??{listenerId:l,target:e.target,actor:i.source,authLens:i.authLens,authUid:e.auth?.uid??null,actorAuthFingerprint:Ar({actor:i.source,authLens:gi(i.authLens),uid:e.auth?.uid??null})};return{phase:s,physicalListenerId:e.listenerId,reauthorization:e.activity?.listenerLifecycle==="reauthorize",...u}}function ad(e){return e.kind==="app"&&e.journeyId!==void 0?`app ${e.journeyId}`:"app"}function gi(e){return e.mode==="as"?{mode:"as",uid:e.uid}:{mode:e.mode}}function KC(e){if(e.kind!=="request"&&e.kind!=="operation"||(e.kind==="request"?e.service??"firestore":e.service)!=="firestore"||e.method!=="get"&&e.method!=="list"||e.origin!=="user"||e.result!=="allow"||e.groupId||e.groupKind||e.activity?.groupKind||e.planId||e.detail?.admin===!0)return null;const n=vc(e);if(n.source.kind!=="app"||n.authLens.mode==="admin")return null;const r=e.path??"<unknown>",s=e.kind==="request"?e.detail?.activityQuery??e.detail?.query:e.request?.query,i=s===void 0?void 0:Ar(s);return{method:e.method,path:r,targetFingerprint:i===void 0?r:`${r}|query:${i}`,actorAuthFingerprint:Ar({actor:n.source,authLens:gi(n.authLens),uid:e.auth?.uid??null}),actor:n.source,authLens:n.authLens,authUid:e.auth?.uid??null}}const bm=new WeakMap;function GC(e){return bm.get(e)?.raw??e}const JC=new WeakMap,cd=new WeakMap;function bi(e,t,n,r,s){bm.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function ld(e){return typeof e.exists=="function"?e.exists():e.exists===!0}function YC(e,t){const n=sa(e),r=sa(t);return n.isStructurallyEqual?.(r)??n===r}function QC(e,t,n,r){const s=e,i=(cd.get(s)??[]).filter(a=>a.query.deref()!==void 0),o=i.find(a=>{const l=a.query.deref();return l!==void 0&&YC(l,t)});if(o!==void 0){const a=XC(o.docs,n)&&o.metadata.fromCache===r.fromCache&&o.metadata.hasPendingWrites===r.hasPendingWrites;return o.docs=n,o.metadata=r,a?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),cd.set(s,i),"initial"}function XC(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&wv(n.data,s.data)})}function ja(e,t,n,r,s){const i=t,o=d=>({path:d.ref?.path??"",data:Sc(d.data?.(),n)}),a=Object.freeze((i.docs??[]).map(o)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...o(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),u=Object.freeze({fromCache:i.metadata?.fromCache===!0,hasPendingWrites:i.metadata?.hasPendingWrites===!0});JC.set(e,{target:n,query:r,converter:ns(r)??null,source:s,...s==="read"?{readPhase:QC(n,r,a,u)}:{},metadata:u,docs:a,changes:l})}function wi(e,t){const n=e;Ia(n);const r=n.data.bind(e),s=t!==void 0;let i;if(s&&(i={create:o=>st({[Xs]:t},o)}),Object.defineProperty(n,"data",{value:()=>Fh(r(),i),configurable:!0,writable:!0}),s){const o=n.ref?.path;o!==void 0&&o.length>0&&Object.defineProperty(n,"metadata",{value:Ct(t).snapshotMetadata(o),configurable:!0})}return e}function wm(e,t,n,r){const s=st({[Xs]:n},e.ref.path),i=s.withConverter(t),o={create:l=>st({[Xs]:n},l)},a={id:e.id,ref:i,exists:()=>ld(e),metadata:Ct(n).snapshotMetadata(e.ref.path),data:()=>{if(!ld(e))return;const u=Fh(e.data(),o),d={id:e.id,ref:s,exists:()=>!0,metadata:Ct(n).snapshotMetadata(e.ref.path),data:()=>u};return t.fromFirestore(d)}};return sn(a,n),sn(e.ref,n),Ca(e.ref,n),bi(a,e,n,t,r),a}function ud(e,t,n,r){const s=e,i=s.ref?.path??"",o=s.data.bind(e),a=st({[Xs]:n},i),l=a.withConverter(t);Object.defineProperty(s,"ref",{value:l,configurable:!0,writable:!0}),Object.defineProperty(s,"data",{value:()=>{const d=o();if(d===void 0)return;const f={id:s.id,ref:a,exists:()=>!0,metadata:Ct(n).snapshotMetadata(i),data:()=>d};return t.fromFirestore(f)},configurable:!0,writable:!0});const u={ref:{path:i},exists:s.exists,data:o};bi(e,u,n,t,r)}function Vi(e,t){if(!e||typeof e!="object")return e;sn(e,t);const n=e;if(n.ref&&(sn(n.ref,t),Ca(n.ref,t)),Ia(n),Array.isArray(n.docs))for(const r of n.docs)r&&(sn(r,t),bi(r,r,t,null,"query-child")),r?.ref&&(sn(r.ref,t),Ca(r.ref,t)),r&&Ia(r);else n.ref&&bi(e,e,t,null,"document");return e}function Ca(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Dl.get(e),s=r??_c(t).doc(n);r===void 0&&Dl.set(e,s),Dh(e,n,t,s),t.kind==="sandbox-live"&&qh.set(s,i=>i.doc(n))}catch{}}function Ia(e){const t=e.exists;if(typeof t=="function")return;const n=t===!0;try{Object.defineProperty(e,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}function vm(e){return ZC(e,"getDoc")}async function ZC(e,t){return eI(e,kc(Vn(e),e,t,"operation"))}async function eI(e,t){const n=Vn(e),r=Ct(n);r.markStarted();try{const s=ns(e),i=await Vh(()=>xv(n,e).get());return r.cachePath(e.path),s?Tn(t,wm(i,s,n,"document")):(Vi(i,n),Tn(t,wi(i,n)))}catch(s){throw t.fail(),s}}function vi(e){return tI(e,"getDocs")}async function tI(e,t){return nI(e,kc(Vn(e),e,t,"operation"))}async function nI(e,t){const n=Vn(e),r=Ct(n);r.markStarted();try{const s=ns(e),i=await Vh(()=>vv(n,e).get());if(r.cacheQuery(e),s){const a=s,l=i.docs.map(d=>wm(d,a,n,"query-child")),u=sn({size:l.length,empty:l.length===0,docs:l,forEach:Th(l),metadata:r.querySnapshotMetadata()},n);for(const d of l)r.cachePath(d.ref.path);return ja(u,i,n,e,"read"),Tn(t,u)}Vi(i,n);const o=i.docs;for(const a of o)r.cachePath(a.ref.path),wi(a,n);return Object.defineProperty(i,"metadata",{value:r.querySnapshotMetadata(),configurable:!0}),ja(i,i,n,e,"read"),Tn(t,i)}catch(s){throw t.fail(),s}}function rI(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.path=="string"&&t.path.length>0?t.path:typeof t.collectionPath=="string"&&t.collectionPath.length>0?t.collectionPath:null}function dd(e){if(e!==null&&typeof e=="object"){const t=e.snapshotConstraints;if(typeof t=="function")return t.call(e)}}function sI(e){if(e!==null&&typeof e=="object"){const t=e.snapshotScope;if(typeof t=="function")return t.call(e)}}function fd(e){if(e===null||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&t.path.length>0&&t.parent!==void 0&&t.parent!==null}function xm(e,t,n,r,s){let i={},o,a;if(typeof t=="object"&&t!==null&&typeof t.next!="function"&&typeof t.error!="function"&&typeof t.complete!="function"){if(i=t,typeof n=="function")o=n,a=r;else if(typeof n=="object"&&n!==null){const v=n;o=v.next,a=v.error}}else if(typeof t=="function")o=t,a=n;else if(typeof t=="object"&&t!==null){const v=t;o=v.next,a=v.error}if(!o&&!a)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=kv(e);if(u){if(i[In]===!0)throw new Ch("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,o,a)}const d=iI(e),h=ts(d.sandbox);let f;const p=fd(e)?void 0:sI(e);if(fd(e))f={kind:"doc",path:e.path};else if(p?.kind==="collection-group")f={kind:"query",collection:p.collectionId,collectionGroup:!0,constraints:dd(e)};else{const v=rI(e);if(v===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const _=dd(e);f={kind:"query",collection:v,constraints:_}}const m=i[In]===!0,g=i[Sr],b=e[Ev]===!0;if(In in i){const{[In]:v,..._}=i;i=_}if(Sr in i){const{[Sr]:v,..._}=i;i=_}const w=()=>h.addSnapshotListener(f,o??(()=>{}),i,d.auth,a?v=>a(aI(v,d)):void 0,m,b,g);return typeof d.sandbox.runWithProvenance=="function"?d.sandbox.runWithProvenance(na(d.operationContext),w):w()}function iI(e){if(e===null||typeof e!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const t=e[jv];if(!t)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return t}_v(xm);Sv(xm);function oI(e){return typeof e=="object"&&e!==null&&"code"in e&&Hw.some(t=>t===e.code)&&"message"in e&&typeof e.message=="string"}function aI(e,t){if(!oI(e))return e;const n=Cv(new zw(e),{...t,auth:e.request?e.request.auth:t.auth});if(n instanceof Error)for(const r of["request","resource","query","rule","queryProof"])e[r]!==void 0&&Object.assign(n,{[r]:e[r]});return n}function _m(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function xi(e,...t){const n=Vn(e),r=ns(e),s=Iv(e);let i,o;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw ia(u)}const a=u=>{let d=s(u);for(const h of i)d=h.applySandbox(d);return d};try{o=a(_c(n))}catch(u){throw ia(u)}const l=Rv(Nv(o,n,u=>a(u)));return r?Av(l,r):l}function cI(e,t,n){return Sm(_m(e),t,n,!1)}function Sm(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const o=Sc(n,i,t==="in"||t==="not-in");return Sm(e,t,o.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function hd(e,t){const n=_m(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function _i(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function lI(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 uI(...e){return lI(e)?km(e[0],!1,!0):Em(e,!1,!0)}function km(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=GC(e),i=s.data(),o=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return km(o,t,n,!0)}}}function Em(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=>Em(e.map(i=>Sc(i,s).executionValue),t,n,!0)}}function dI(e,t,n,r){const s=Vn(e);Ct(s).markStarted();const i=hI(s,e),o=typeof t=="object"&&t!==null&&!Yc(t)?t:void 0,a=kc(s,e,"onSnapshot","subscription",o),l=pI(t,n,r,s,e,a),u=mI(l,s);let d;try{d=Zr.registering(a,()=>u.length===3?i.onSnapshot(u[0],u[1],u[2]):u.length===2?i.onSnapshot(u[0],u[1]):i.onSnapshot(u[0]))}catch(g){throw a.fail(),g}if(!s.own)return()=>{a.close(),d()};let h=!1;const f=()=>{h||(h=!0,a.close(),d())},p=()=>{h||(a.fail(),f(),fI(u)?.(new H("aborted","The operation was aborted.")))},m=s.own(p);return()=>{m(),f()}}function fI(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 hI(e,t){const n=sa(t);if(e.kind==="sandbox")return n;const r=qh.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(_c(e))}function Yc(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 pI(e,t,n,r,s,i){if(typeof e=="object"&&e!==null&&!Yc(e)){const a=t;return typeof a=="function"?[e,pd(a,r,s,i),Na(n??Ra,i)]:a&&typeof a=="object"?[e,md(a,r,s,i)]:[e]}return typeof e=="function"?[pd(e,r,s,i),Na(t??Ra,i)]:e&&typeof e=="object"?[md(e,r,s,i)]:[e]}function mI(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Yc(n)?[{...n,[In]:!0,...t.authScope?{[Sr]:t.authScope}:{}},...e.slice(1)]:[{[In]:!0,...t.authScope?{[Sr]:t.authScope}:{}},...e]}function jm(e,t,n){if(!e||typeof e!="object")return e;const r=e,s=ns(n)??null,i=s!==null;if(typeof r.data=="function"&&(wi(e,t),i&&ud(e,s,t,"document")),Array.isArray(r.docs)){for(const o of r.docs)wi(o,t),i&&ud(o,s,t,"query-child");ja(e,e,t,n,"listener")}return e}function Ra(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function pd(e,t,n,r){return s=>{const i=jm(Vi(s,t),t,n);r.delivered(i),e(i),Ct(t).notifySnapshotDelivered()}}function md(e,t,n,r){return{...e,next:e.next?s=>{const i=jm(Vi(s,t),t,n);r.delivered(i),e.next(i),Ct(t).notifySnapshotDelivered()}:void 0,error:Na(e.error??Ra,r)}}function Na(e,t){return n=>{t.fail(),e(ia(n))}}const Ot={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string",description:"Tenant id, visible to rules as request.auth.token.firebase.tenant."},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},yI={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Ov]},value:{}},required:["field","op","value"]};function gI(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:Ot},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=st(s,r.path),o=await vm(i),a=typeof o.exists=="function"?o.exists():o.exists;return{ok:!0,summary:a?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:a,data:a?o.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:Ot},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=br(s,r.collection),o=[];r.orderBy&&o.push(hd(r.orderBy)),r.limit&&o.push(_i(r.limit));const a=await vi(xi(i,...o));return{ok:!0,summary:`${a.size} docs in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Ot},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Zs(st(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:Ot},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await Wh(br(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:Ot},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Tl(st(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:Ot},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await oa(st(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:Ot},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const o=st(s,i.path);i.op==="set"?await Zs(o,i.data??{}):i.op==="update"?await Tl(o,i.data??{}):await oa(o)}return{ok:!0,summary:`Applied ${r.operations.length} write(s)`,data:{count:r.operations.length}}}},{name:"firestore_query_where",description:"Query a collection with one or more where clauses (AND-semantics) + optional orderBy + limit. For OR semantics use a single where clause with the `in` / `array-contains-any` op. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},where:{type:"array",description:"One or more where clauses. AND across clauses.",items:yI,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ot},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=br(s,r.collection),o=r.where.map(l=>cI(l.field,l.op,l.value));r.orderBy&&o.push(hd(r.orderBy)),r.limit&&o.push(_i(r.limit));const a=await vi(xi(i,...o));return{ok:!0,summary:`${a.size} matches in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function bI(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=Kw(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 wI="modulepreload",vI=function(e){return"/__pyric/ui/"+e},yd={},Cm=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=o(n.map(u=>{if(u=vI(u),u in yd)return;yd[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":wI,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,m)=>{f.addEventListener("load",p),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};function Im(e){return e.kind==="session_boundary"&&e.phase==="reset"}function xI(e,t){return Im(t)?[t]:[...e,t]}const Rm=y.createContext(null),Nm={status:"disabled",handles:null,events:[]};function _I({children:e}){return c.jsx(Rm.Provider,{value:Nm,children:e})}function Gt(){return y.useContext(Rm)??Nm}function Pt(e,t){return`${e.replace(/\/$/,"")}${t}`}const jo=new Map;let Co=null;function SI(e){return e||(Co||(Co=`studio-writer-${Math.random().toString(36).slice(2)}`),Co)}function Am(e){return{token:e?.token,writerId:e?.writerId}}async function Wi(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=jo.get(n);if(r)return r;const s=fetch(Pt(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||jo.delete(n),i));return jo.set(n,s),s}async function Om(e,t,n=!1){const r={},{token:s,writerId:i}=Am(t);n&&(r["x-pyric-writer"]=SI(i));const o=await Wi(e,s);return o&&(r["x-pyric-session-token"]=o),r}function $m(e,t){const n=e,{token:r}=Am(t),s=(i=!1)=>Om(n,t,i);return{async read(i){const o=await s(!1),a=await fetch(Pt(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:o});if(a.status===404)return null;if(!a.ok)throw new Error(`workspace.read(${i}) → ${a.status}`);return a.text()},async write(i,o){const a=await s(!0),l=await fetch(Pt(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:a,body:o});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const o=await s(!1),a=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch(Pt(n,`/__pyric/workspace/list${a}`),{headers:o});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async branches(){const i=await s(!1),o=await fetch(Pt(n,"/__pyric/workspace/branches"),{headers:i});if(!o.ok)throw new Error(`workspace.branches() → ${o.status}`);return await o.json()},async remove(i){const o=await s(!0),a=await fetch(Pt(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:o});if(!a.ok)throw new Error(`workspace.remove(${i}) → ${a.status}`)},watch(i){let o=null,a=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Wi(n,r).then(u=>{if(a)return;const d=u?Pt(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):Pt(n,"/__pyric/workspace/watch");o=new EventSource(d),o.addEventListener("change",l)}),()=>{a=!0,o&&(o.removeEventListener("change",l),o.close())}}}}function sr(e,t){return`${e.replace(/\/$/,"")}${t}`}function kI(e,t){const n=e,r=(s=!1)=>Om(n,t,s);return{async list(){const s=await r(!1),i=await fetch(sr(n,"/__pyric/projects"),{headers:s});if(!i.ok)throw new Error(`projects.list() → ${i.status}`);return await i.json()},async open(s){const i=await r(!1),o=await fetch(sr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!o.ok)throw new Error(`projects.open(${s}) → ${o.status}`);return{meta:await o.json(),workspace:$m(n,t)}},async create(s){const o={...await r(!0),"content-type":"application/json"},a=await fetch(sr(n,"/__pyric/projects"),{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok)throw new Error(`projects.create() → ${a.status}`);return await a.json()},async update(s,i){const a={...await r(!0),"content-type":"application/json"},l=await fetch(sr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:a,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),o=await fetch(sr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!o.ok)throw new Error(`projects.remove(${s}) → ${o.status}`)}}}function EI(e,t){return`${e.replace(/\/$/,"")}${t}`}function Io(e){return/auth/i.test(e)?"auth":"firestore"}function jI(e){const t=e,n=`studio-${Math.random().toString(36).slice(2)}`,r=async()=>{const u=await Wi(t);return u!==null?{"x-pyric-session-token":u}:{}},s=async()=>({"content-type":"application/json","x-pyric-writer":n,...await r()}),i=new Map,o=u=>EI(t,`/__pyric/state?section=${Io(u)}`),a=async u=>{const d=Io(u),h=i.get(d);if(h)return h;const f=await fetch(o(u),{headers:await r()});let p=new Map;if(f.ok){const m=await f.text();m&&m!=="null"&&(p=Gw(m))}else if(f.status!==404)throw new Error(`persistence.read(${u}) → ${f.status}`);return i.set(d,p),p},l=async(u,d)=>{const h=await fetch(o(u),{method:"POST",headers:await s(),body:Jw(d)});if(h.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!h.ok)throw new Error(`persistence.write(${u}) → ${h.status}`)};return{async getRecord(u,d){return(await a(u)).get(d)??null},async listRecords(u){return[...(await a(u)).keys()]},async putRecords(u,d){const h=await a(u);for(const[f,p]of d)h.set(f,p);await l(u,h)},async deleteRecords(u,d){const h=await a(u);for(const f of d)h.delete(f);await l(u,h)},async clear(u){i.set(Io(u),new Map);const d=await fetch(o(u),{method:"POST",headers:await s(),body:"null"});if(!d.ok&&d.status!==423)throw new Error(`persistence.clear(${u}) → ${d.status}`)}}}const CI="local";function II(){const e=new Map,t=new Set,n=r=>{for(const s of t)s(r)};return{async read(r){return e.has(r)?e.get(r):null},async write(r,s){const i=e.has(r)?"update":"create";e.set(r,s),n({path:r,type:i})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",i=[];for(const o of e.keys())s&&!o.startsWith(s)||i.push({path:o,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},async branches(){return[]},watch(r){return t.add(r),()=>t.delete(r)}}}function RI(){const e=II();let t={id:CI,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[t]},async open(n){if(n!==t.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:t,workspace:e}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===t.id&&(t={...t,...r,updatedAt:Date.now()})},async remove(){}}}var Ro={};const NI="/__pyric/sdk/worker.js",Dt="pyric-shared-worker",AI="/__pyric/ui/studio";function OI(e,t){if(typeof process<"u"&&Ro){const s=Ro.NEXT_PUBLIC_PYRIC_STUDIO_URL||Ro.PYRIC_STUDIO_URL;if(typeof s=="string"&&s.trim().length>0)return s.trim()}const n=globalThis.__PYRIC_WORKER_INIT__;if(typeof n?.studioUrl=="string"&&n.studioUrl.trim().length>0)return n.studioUrl.trim();if(typeof n?.bridgeUrl=="string"&&n.bridgeUrl.trim().length>0)try{const s=t?.href||(typeof location<"u"?location.href:""),i=new URL(n.bridgeUrl,s||"http://localhost"),o=t?.host||(typeof location<"u"?location.host:"")||(s?new URL(s).host:"");if(i.host&&(!o||i.host!==o))return`${i.protocol==="wss:"||i.protocol==="https:"?"https:":"http:"}//${i.host}/__pyric/ui/studio`}catch{}const r=e?.querySelector('meta[name="pyric-studio-url"]')?.getAttribute("content")?.trim()||e?.querySelector('meta[name="pyric-runtime-chip"]')?.getAttribute("data-studio-url")?.trim();return r||AI}function Pm(e=typeof document>"u"?void 0:document,t=typeof location>"u"?void 0:location){const n=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:OI(e,t),worker:{url:NI,name:Dt,servedEpoch:n}}}const Si="pyric:worker-generation",ir="pyric:worker-generation-probe";function $I(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Dt}:${n}`:Dt;try{const r=t.getItem(Si);return r&&/^[a-f0-9]{16}$/.test(r)?`${Dt}:${r}`:n?(t.setItem(Si,n),`${Dt}:${n}`):Dt}catch{return n?`${Dt}:${n}`:Dt}}function PI(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(Si,e),t.getItem(Si)!==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 DI(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(ir);if(e.setItem(ir,"ok"),e.getItem(ir)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(ir):e.setItem(ir,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 TI(e){const t=e.schedule??(s=>{setTimeout(s,100)});let n=!1;const r=e.subscribeReload(s=>{if(!n){try{e.commitGeneration(s)}catch(i){e.onPreparationError?.(i);return}n=!0,t(e.reload)}});return{async request(){e.preflight(),await e.retire()},dispose:r}}const MI=Symbol.for("pyric.ai-evidence"),LI=globalThis,UI=LI[MI]??=new WeakMap;function gd(e,t){return UI.set(e,Object.freeze({...t})),e}function BI(){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 Dm=new WeakMap;let Aa;function FI(e,t,n=BI()){const r=e.name,s=n===t?void 0:{},i=new Map,o=new Set,a={app:e,sandbox:t,session:n,services:i,cleanups:o,assertAlive(){if(a.deleted)throw new H("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(l,u){const d=i.get(l);if(d!==void 0)return d;a.assertAlive();const h=u();return i.set(l,h),h},onDelete(l){return a.deleted?(l(),()=>{}):(o.add(l),()=>o.delete(l))},deleted:!1};return Dm.set(e,a),a}function qI(e){Aa=e}$v({resolve(e,t){const n=typeof e=="object"&&e!==null?Dm.get(e):void 0;if(n)return n},defaultApp(){if(!Aa)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Aa()}});const VI="[DEFAULT]",WI=new Map;function zI(e,t){return new H(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function HI(e){return zI("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function KI(e=VI){const t=WI.get(e);if(!t)throw HI(e);return t.app}qI(KI);const GI={mode:"wall",fixedAt:0,offsetMs:0};let gr=GI;function JI(e){gr=e}function YI(){return gr.mode==="fixed"?gr.fixedAt:gr.mode==="offset"?Date.now()+gr.offsetMs:Date.now()}const bd=5174,qr=12*1024*1024,QI=256,XI=24*1024*1024,wd="/sandbox",ZI=4001,eR="worker-relay",tR="storage-byte-route",nR="worker-port",rR=6e4,Tm=15e3,vd=3*Tm,sR=4004;function Mm(e){if(e===null||typeof e!="object")return!1;const n=e.type;return n==="hello"||n==="hello-ack"||n==="attach"||n==="attach-ack"||n==="tool-call"||n==="tool-result"||n==="worker-op"||n==="worker-res"||n==="worker-sub"||n==="worker-unsub"||n==="worker-snap"||n==="worker-client-disconnect"||n==="worker-client-interrupted"||n==="consumer-presence"||n==="remote-set-lens"||n==="remote-set-lens-ack"||n==="worker-event"||n==="worker-message"||n==="worker-message-result"||n==="ping"||n==="pong"}function Oa(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=Oa(t);if(n)return n}return null}for(const t of Object.values(e)){const n=Oa(t);if(n)return n}return null}function xd(e,t){const n=Oa(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 iR=new TextEncoder;function oR(){let e=0,t=0;return{reserve(n){if(e>=QI)return{accepted:!1,error:{code:"resource-exhausted",message:"This client already has 256 pending operations."}};let s;try{s=iR.encode(JSON.stringify(n)).byteLength}catch{return{accepted:!1,error:{code:"invalid-argument",message:"The operation must have a JSON-serializable encoding."}}}return t+s>XI?{accepted:!1,error:{code:"resource-exhausted",message:"This client exceeds the 24 MiB queued operation byte limit."}}:(e+=1,t+=s,{accepted:!0,release(){e-=1,t-=s}})}}}function Lm(e){if(e===null||typeof e!="object")return;const t=e,n=t.target,s=typeof n=="object"&&n!==null?n.instance:t.instance;return typeof s=="string"&&s.length>0?s:void 0}function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function aR(e){return Pn(e)?(e.mode==="wall"||e.mode==="fixed"||e.mode==="offset")&&Number.isFinite(e.fixedAt)&&Number.isFinite(e.offsetMs):!1}function Um(e){if(e.ok===!0)return!0;const n=e.error,r=Pn(n);return e.ok===!1&&r&&typeof n.code=="string"&&typeof n.message=="string"}function Bm(e){if(!Pn(e)||e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return!1;switch(e.t){case"res":return typeof e.id=="string";case"snap":return typeof e.subId=="string";case"event":return typeof e.subId=="string"&&Array.isArray(e.events);case"runtime-reload":return typeof e.epoch=="string";case"clock":return aR(e.state);default:return!1}}function _d(e){const t={code:"unavailable",message:"The sandbox sent a malformed subscription reply."};if(!Object.hasOwn(e,"value"))return t;const r=e.value;if(!(Pn(r)&&Object.hasOwn(r,"__error")))return;const o=r.__error;if(!Pn(o))return t;const u=o.code,d=o.message;if(typeof u!="string"||typeof d!="string")return t;const f=o.aiEvidence,p=Pn(f),m=o.codeless===!0?{codeless:!0}:{};return{code:u,...m,message:d,denialContext:o.denialContext,aiEnvelope:o.aiEnvelope,aiEvidence:p?f:void 0,envelope:o.envelope}}const Vr=new WeakMap;function Fm(e){let t=Vr.get(e);return t===void 0&&(t={entries:[],closed:!1},Vr.set(e,t)),t}function cR(){return new H("app/app-deleted","Firebase App was deleted")}function qm(e,t){try{e.postMessage(t.message)}catch(n){t.failed?.(n)}}function lR(e,t){for(;t.entries.length>0;){const n=t.entries[0],r=n.frames.splice(0);for(const i of r)qm(e,i);if(!n.released)return;t.entries.shift()}}const uR=()=>performance.now();let dR=uR;function Qc(){return dR()}function zi(e,t,n){const r=Vr.get(e);if(!(r!==void 0&&r.entries.length>0)){e.postMessage(t);return}r.entries.push({frames:[{message:t,failed:n}],released:!0})}function Vm(e){const t=Fm(e),n={frames:[],released:!1};return t.closed||t.entries.push(n),{issuedAt:Qc(),send(s,i){const o=t.entries[0]===n;if(t.closed){i(cR());return}if(o){qm(e,{message:s,failed:i});return}n.frames.push({message:s,failed:i})},release(){if(n.released)return;n.released=!0,t.entries[0]===n&&lR(e,t)}}}function Wm(e,t){const n=Vr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>"id"in i.message&&i.message.id===t);if(s>=0)return{entry:r,index:s}}}function zm(e,t){return Wm(e,t)!==void 0}function fR(e,t){const n=Wm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function Hm(e,t){const n=Vr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>i.message.t==="sub"&&i.message.subId===t);if(s>=0)return{entry:r,index:s}}}function hR(e,t){return Hm(e,t)!==void 0}function pR(e,t){const n=Hm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function Km(e){const t=Fm(e);t.closed=!0,t.entries.length=0}let mR=0,yR=0;function L(){return`op-${++mR}`}function hn(){return`sub-${++yR}`}const Qe=new Map,ze=new Map,ot=new Map,Kn=new WeakSet,$a=new Set;function gR(e){return $a.add(e),()=>$a.delete(e)}function Wr(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function bR(e,t,n){if(Kn.has(e))return;const s={...n,message:void 0};ze.set(t,s);const i=()=>ze.get(t)===s,o=a=>{i()&&ze.delete(t)&&n.error?.(a)};return{send(a,l){if(i()){s.message=a;try{l!==void 0?l.send(a,o):zi(e,a,o)}catch(d){queueMicrotask(()=>o(d))}}}}}function hs(e,t,n,r,s){const i=bR(e,t,n);return i===void 0?!1:(i.send(r,s),!0)}function wR(e,t,n,r,s,i){if(Kn.has(e))return s?.(Wr()),!1;ot.set(t,{port:e,next:n,error:s,message:r,restored:i});const a=l=>{ot.get(t)?.message===r&&ot.delete(t)&&s?.(l instanceof H?l:Wr())};try{zi(e,r,a)}catch(l){queueMicrotask(()=>a(l))}return!0}function vR(e,t){const n=e.messagingVisibility;n&&t({...n,id:L()});for(const[r,s]of ze){const i=s.message;!(s.port===e&&i?.t==="sub")||!(i.target==="messaging.foreground"||i.target==="messaging.background")||(t({t:"unsub",subId:r}),t(i))}}function xR(e,t=n=>e.postMessage(n)){for(const[n,r]of ze){const s=r.message;if(!(r.port===e&&s?.t==="sub"))continue;const o=typeof s.target=="object"&&"service"in s.target&&s.target.service==="rtdb",a=r.service==="firestore"||o,l=s.target==="presence";(a||l)&&(t({t:"unsub",subId:n}),t(s))}for(const[n,r]of ot)r.port===e&&(r.restored?.(),t({t:"unsub",subId:n}),t(r.message))}function _R(e,t){for(const n of ze.values()){const r=n.message;n.port===e&&r?.t==="sub"&&(r.target==="authState"||r.target==="idToken")&&t(r)}}function it(e,t,n){const r=ze.get(t)??ot.get(t);if(!(r!==void 0)||(ze.delete(t),ot.delete(t),Kn.has(e))||r.message===void 0||pR(e,t)||e.withdrawSubscription?.(t)===!0)return;const a={t:"unsub",subId:t};n!==void 0&&n!==""&&(a.clientSessionId=n);const u=()=>{};try{zi(e,a,u)}catch{}}function zr(e,t,n=()=>!0){for(const[r,s]of[...Qe])s.port===e&&n(r)&&(Gn(r),s.reject(t))}function SR(e,t){const n=[];for(const[r,s]of Qe)s.port===e&&t(r)&&n.push({id:r,message:s.message});return n}function kR(e){const t=[];for(const n of e){const r=Qe.get(n),s=r?.message;if(!(r!==void 0&&s?.t==="op"))continue;const o={...s,id:L()};Qe.delete(n),Qe.set(o.id,{...r,message:o}),t.push(o)}return t}function Sd(e,t){Gn(e)?.reject(t)}function ER(e){Gn(e)}function jR(e){Kn.add(e),zr(e,Wr()),Gm(e,new H("aborted","The operation was aborted."),Wr()),e.onmessage=null}function Gm(e,t,n=t){for(const[r,s]of[...ze]){if(s.port!==e)continue;ze.delete(r),s.service==="firestore"?s.error?.(t):Jm(s.message)&&s.error?.(n),s.close?.()}for(const[r,s]of[...ot])s.port===e&&(ot.delete(r),s.error?.(n))}function Jm(e){if(!(e?.t==="sub"))return!1;const n=e.target;return typeof n=="object"&&n!==null&&"service"in n&&n.service==="ai"}function CR(e,t,n){for(const[r,s]of[...ze])!(s.port===e&&Jm(s.message))||!(!n(r)&&!hR(e,r))||(it(e,r),s.error?.(t))}function kd(e,t,n,r){if(t.denialContext===void 0||typeof fetch!="function")return;const s={kind:e,code:t.code??"unknown",message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{},...n===void 0?{}:{instance:n},...r!==void 0?{owners:r}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}).catch(()=>{})}catch{}}function Hi(e){e.onmessage=t=>{const n=t.data;if(!Bm(n)){const u=new H("unavailable","The sandbox sent a malformed reply envelope. The operation may have completed; check state before retrying.");zr(e,u);for(const[d,h]of ze)h.port===e&&(it(e,d),h.error?.(u));for(const[d,h]of ot)h.port===e&&(it(e,d),h.error?.(u));return}const s=n.t==="res",i=n.t==="snap",o=n.t==="event",a=n.t==="runtime-reload",l=n.t==="clock";if(s){const u=Qe.get(n.id);if(u===void 0||u.port!==e)return;if(Gn(n.id),!Um(n)){u.reject(new H("unavailable","The sandbox sent a malformed operation reply. The operation may have completed; check state before retrying."));return}if(n.ok)u.resolve(n.value);else{const p=n.error.codeless!==!0;let m;p?m=new H(n.error.code,n.error.message):m=new Error(n.error.message),n.error.denialContext!==void 0&&(m.denialContext=n.error.denialContext);const b=n.error.aiEvidence;b!==void 0&&gd(m,b),n.error.aiEnvelope!==void 0&&(m.aiEnvelope=n.error.aiEnvelope),kd("read",m,u.instance),u.reject(m)}}else if(i){const u=ze.get(n.subId);if(u===void 0){const p=ot.get(n.subId),m=_d(n);if(p!==void 0&&p.port===e&&m!==void 0){it(e,n.subId,p.message.clientSessionId);const g=m.codeless!==!0?new H(m.code,m.message):Object.assign(new Error(m.message),{code:"unavailable"});p.error?.(g)}return}if(u.port!==e)return;const h=_d(n);if(h!==void 0){it(e,n.subId,u.message?.clientSessionId);const p=h.codeless!==!0;let m;p?m=new H(h.code,h.message):m=new Error(h.message),h.denialContext!==void 0&&(m.denialContext=h.denialContext);const b=h.aiEvidence;b!==void 0&&gd(m,b),h.aiEnvelope!==void 0&&(m.aiEnvelope=h.aiEnvelope);const v=u.message,_=v!==void 0&&"owners"in v?v.owners:void 0;kd("listener",m,Lm(v),_);const S=u.error;S!==void 0?S.call(u,m):console.error("pyric/firestore: Uncaught Error in snapshot listener:",m);return}u.next(n.value)}else if(o){const u=ot.get(n.subId);u!==void 0&&u.port===e&&u.next(n.events)}else if(a)for(const u of $a)u(n);else l&&JI(n.state)},e.postMessage({t:"clock-subscribe"})}const kr="pyric:auth-lens";function IR(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"||t.mode==="anon"?!0:t.mode==="as"&&typeof t.uid=="string"}function Ym(e){if(IR(e))return e}function RR(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(kr);if(!e)return;const t=JSON.parse(e),n=Ym(t);if(n)return n;sessionStorage.removeItem(kr);return}catch{try{sessionStorage.removeItem(kr)}catch{}return}}let jt=RR();const Pa=new Set;function NR(e){return Pa.add(e),()=>{Pa.delete(e)}}function Ed(e){if(jt=Ym(e),typeof sessionStorage<"u")try{jt?sessionStorage.setItem(kr,JSON.stringify(jt)):sessionStorage.removeItem(kr)}catch{}for(const t of[...Pa])try{t(jt)}catch(n){console.error("Error in subscribeLens listener:",n)}}function AR(){return jt}let Da;function OR(e){Da=e}function Xc(e){return Da&&(e.t==="op"||e.t==="sub")?{...e,issuer:Da}:e}function Ki(e,t,n,r){if(Kn.has(e))return Promise.reject(Wr());const o=t.t==="op"||t.t==="tool"?$R(e,t.clientSessionId):void 0,a=o?.reserve(t);return a?.accepted===!1?Promise.reject(new H(a.error.code,a.error.message)):(t.t==="disconnect"&&Km(e),new Promise((d,h)=>{const f=t;Qe.set(f.id,{port:e,clientSessionId:t.clientSessionId,instance:Lm(t),budget:o,release:a?.release,issuedAt:r?.issuedAt??Qc(),message:t,resolve:d,reject:h});const p=m=>{Gn(f.id)!==void 0&&h(m)};try{n!==void 0?n(t):r!==void 0?r.send(t,p):zi(e,t,p)}catch(m){p(m)}}))}function $R(e,t){for(const n of Qe.values()){const r=n.port===e&&n.clientSessionId===t,s=n.budget;if(r&&s!==void 0)return s}return oR()}function Gn(e){const t=Qe.get(e);return Qe.delete(e),t!==void 0&&fR(t.port,e),t?.release?.(),t}function Q(e,t,n){return Ki(e,Xc(t),void 0,n)}function Qm(e,t,n,r){const s=t.id;let i;const o=new Promise((a,l)=>{i=setTimeout(()=>{Gn(s)!==void 0&&l(new Error(r))},n)});return Promise.race([Q(e,t),o]).finally(()=>{i!==void 0&&clearTimeout(i)})}function ye(e,t,n){if(Kn.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new H("failed-precondition","The client has already been terminated."));const r=jt?{...t,actAs:jt}:t;return Q(e,r,n)}async function PR(e,t,n={}){const r=n.timeoutMs??12e3;await Qm(e.port,{t:"op",id:L(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function DR(e){return gR(t=>e(t.epoch))}const Ta=Symbol("pyric/database/target"),TR=new WeakMap;function MR(e){let t;if(Ta in e?t=e[Ta]:t=TR.get(e),!t)throw new TypeError("pyric/database: unrecognized reference — was it produced by a factory in this package?");return t.kind==="sandbox-live"&&t.assertUsable?.(),t}const jd=LR();function LR(){let e;try{const n=import.meta.url;typeof n=="string"&&(e=n)}catch{e=void 0}if(e===void 0)return"";const t=e.slice(0,e.lastIndexOf("/"));return t.startsWith("file://")?t.slice(7):t}function UR(e){return jd.length===0?e:e.split(`
|
|
131
|
+
`).filter(t=>!t.includes(jd)).join(`
|
|
132
|
+
`)}function Xm(e){const t=[],n=BR();n!==void 0&&t.push(n);const r=Yw(e?.owner);if(r!==void 0&&t.push(r),t.length!==0)return t}function BR(){if(!Qw())return;const e=Xw();if(e!==void 0)return Zw(UR(e))}function FR(e){const t=new Map,n=new Set,r=()=>{for(const i of[...n])try{i()}catch{}},s=e.subscribe(i=>{i.phase==="remove"&&t.delete(i.record.id)});return{record(i,o){const a=Qs(o);a===void 0||a.kind!=="regions"||(t.set(i,Object.freeze([...a.selectors])),r())},regions:i=>t.get(i)??[],subscribe(i){return n.add(i),()=>{n.delete(i)}},dispose(){s(),t.clear(),n.clear()}}}const Cd=Symbol.for("pyric.delivered-regions"),Id=globalThis,qR=Id[Cd]??(Id[Cd]=FR(Zr));function VR(e,t){qR.record(e,t)}function WR(e,t,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(e,{type:"classic",name:t??"pyric-shared-worker"});n.onError&&r.addEventListener("error",i=>{const o=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${o}`))});const s=r.port;return Hi(s),s.start(),{__kind:"client-db",port:s}}async function zR(e,t={}){const n=L(),r=t.timeoutMs??2e3;return(await Qm(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function HR(e){return(await Q(e.port,{t:"op",id:L(),method:"getVersion"})).instanceId??""}async function KR(e){return(await Q(e.port,{t:"op",id:L(),method:"exportState"})).bundle}async function GR(e,t){await Q(e.port,{t:"op",id:L(),method:"importState",bundle:t})}async function JR(e,t){await Q(e.port,{t:"op",id:L(),method:"checkpoint",name:t})}async function YR(e){return(await Q(e.port,{t:"op",id:L(),method:"listCheckpoints"})).checkpoints??[]}async function QR(e,t){await Q(e.port,{t:"op",id:L(),method:"restore",name:t})}async function XR(e,t){await Q(e.port,{t:"op",id:L(),method:"deleteCheckpoint",name:t})}async function ZR(e,t,n,r,s){return await Q(e.port,{t:"tool",id:L(),name:t,args:n,clientSessionId:s,actAs:r})}function eN(e,t,n){return Ki(e.port,{...t,issuer:void 0,relaySource:"remote",clientSessionId:n,t:"op",id:L()})}function tN(e,t,n,r){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const s=hn();return hs(e.port,s,{port:e.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...t,issuer:void 0,relaySource:"remote",clientSessionId:r,t:"sub",subId:s})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{it(e.port,s,r)}}function nN(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}function Zm(e){return e.kind==="where"?{...e,value:Mh(e.value)}:{kind:e.kind,filters:e.filters.map(Zm)}}function rN(e){return e.kind==="where"||e.kind==="and"||e.kind==="or"?Zm(e):"values"in e?{...e,values:e.values.map(Mh)}:e}function Jn(e,t,n,r=Xm(void 0)){const s=e.descriptor,i=s.__ref==="query"?s.source:s,o=i.__ref==="group"?i.collectionId:i.path,a=s.__ref==="query"?s.constraints:[];return Zr.begin({app:e.port,method:t,kind:n,owners:r,source:{service:"firestore",target:o,isQuery:s.__ref!=="doc",...s.__ref==="doc"?{}:{indexQuery:Pv(o,i.__ref==="group",a.filter(l=>["where","and","or"].includes(l.kind)),a.filter(l=>l.kind==="orderBy").map(l=>({...l,direction:l.direction??"asc"})))},key:Ar({base:i,constraints:s.__ref==="query"?s.constraints.map(rN):[]})}})}const sN=[];function ey(e){for(const t of[...sN])t.port===e&&t.close()}const iN=5e3;function oN(){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 aN(e,t={}){let n;try{const r=Ki(e.port,{t:"disconnect",id:L()}),s=new Promise((i,o)=>{n=setTimeout(()=>o(oN()),t.ackTimeoutMs??iN)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),ey(e.port),jR(e.port),e.port.close()}}function cN(e,t){Gm(e,t),ey(e)}function Zc(e){return e.split("/").at(-1)??e}function zt(e,t,n=null){function r(i){return zt(e,t,i)}const s={__kind:"doc-ref",descriptor:{__ref:"doc",path:t},port:e,id:Zc(t),path:t,converter:n,withConverter:r};return Dh(s,t,e),s}function lN(e,t){const n=JSON.parse(e.json);return t!==void 0?ev(n,t,e.valueEncoding):xc(n,e.valueEncoding)}const Ma=4*1024*1024,Gi=512*1024*1024;function el(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Gi/1048576} MiB maximum storage object cap (MAX_STORAGE_OBJECT_BYTES).`);return n.code="storage/quota-exceeded",n}function Rd(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 Nd(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function uN(e,t){return lN(e,{create:r=>zt(t,r)})}const ty=Object.freeze({fromCache:!1,hasPendingWrites:!1}),dN=Object.freeze({fromCache:!1,hasPendingWrites:!0});function ny(e){return e.hasPendingWrites===!0?dN:ty}const ry=new WeakMap;function fN(e){return ry.get(e)}function tl(e,t,n,r=ty){if(!nl(e))throw new H("invalid-argument","The sandbox sent a malformed document result.");let i;const o=e.data;e.exists&&o!==void 0&&(i=uN(o,t));const l=e.path??e.id,u=n??zt(t,l),d=()=>{const f=i;if(f===void 0)return;const m=u.converter;if(m!==null){const b={id:e.id,ref:zt(t,l),exists:()=>!0,metadata:r,data:()=>f};return m.fromFirestore(b)}return f},h={id:e.id,path:l,ref:u,exists:()=>e.exists,metadata:r,data:d,get:f=>hN(i,f)};return ry.set(h,{id:e.id,path:l,exists:e.exists,data:i}),h}function hN(e,t){try{return rv(e,t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new H("invalid-argument",`Function DocumentSnapshot.get() called with invalid data. ${r}`)}}function La(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nl(e){if(!La(e))return!1;const r=e.data,s=r===void 0||La(r)&&typeof r.json=="string",i=e.path===void 0||typeof e.path=="string";return typeof e.id=="string"&&typeof e.exists=="boolean"&&i&&s&&sy(e)}function sy(e){return e.hasPendingWrites===void 0||typeof e.hasPendingWrites=="boolean"}function iy(e){return La(e)&&Array.isArray(e.docs)&&e.docs.every(nl)&&sy(e)}function pN(e,t,n,r){if(iy(e)){const o=oy(e,t,n,r);return r.previous!==void 0&&o.docChanges().length===0&&(r.excludesMetadataChanges||o.metadata.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previous=e.docs,r.previousHasPendingWrites=o.metadata.hasPendingWrites,o)}if(nl(e)){const o=ny(e),a=r.previousDocument;return a!==void 0&&a.exists===e.exists&&(!e.exists||a.data?.json===e.data?.json)&&(r.excludesMetadataChanges||o.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previousDocument=e,r.previousHasPendingWrites=o.hasPendingWrites,tl(e,t,zt(t,e.path??e.id,n),o))}throw new H("invalid-argument","The sandbox sent a malformed Firestore snapshot.")}function oy(e,t,n=null,r={excludesMetadataChanges:!1}){if(!iy(e))throw new H("invalid-argument","The sandbox sent a malformed query result.");const i=ny(e),o=h=>tl(h,t,zt(t,h.path??h.id,n),i),a=e.docs.map(o),l=e.docs.map(h=>({path:h.path??h.id,doc:h})),u=r.previous?.map(h=>({path:h.path??h.id,doc:h})),d=tv(u,l,a,(h,f)=>h.doc.data?.json===f.doc.data?.json,h=>o(h.doc));return{metadata:i,size:a.length,empty:a.length===0,docs:a,forEach:Th(a),docChanges:nv(d,r.excludesMetadataChanges)}}function mN(e,...t){const n=e.port;let r,s=null;const i=e.__kind==="client-db",o=t.length>0;if(i){if(!o)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const a=e.descriptor.path;s=e.converter,o?r=`${a}/${t.join("/")}`:r=`${a}/${sv()}`}return zt(n,r,s)}function yN(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("/")}`,ay(n,r,null)}function ay(e,t,n){function r(i){return ay(e,t,i)}return{__kind:"coll-ref",descriptor:{__ref:"collection",path:t},port:e,id:Zc(t),path:t,converter:n,withConverter:r}}function cy(e,t,n){function r(s){return cy(e,t,s)}return{__kind:"query",descriptor:t,port:e,converter:n,withConverter:r}}const Es="__name__",gN=new Set(["<","<=",">",">=","!=","not-in"]),ly=new WeakMap,Ad=new WeakMap;function bN(e,t){if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n}function uy(e,t){if(e.kind==="where"){gN.has(e.op)&&t.push(e.field);return}for(const n of e.filters)uy(n,t)}function wN(e){return e.length===1&&e[0]!==null&&typeof e[0]=="object"&&"data"in e[0]&&typeof e[0].data=="function"}function vN(e,t){if(!wN(t))return{type:e,_descriptor:{kind:e,values:t.map(Nr),valueEncoding:un}};const n=t[0],r=fN(n)??(()=>{const i=n.data(),o=typeof n.id=="string"?n.id:"",a=typeof n.path=="string"?n.path:typeof n.ref?.path=="string"?n.ref.path:o,l=typeof n.exists=="function"?!!n.exists():i!==void 0;return{id:o,path:a,exists:l,data:i}})(),s={type:e,_descriptor:{kind:e,values:[],valueEncoding:un}};return ly.set(s,{__snapshotCursor:!0,kind:e,snapshot:r}),s}function No(e){return"__snapshotCursor"in e}function xN(e){if(!e.some(No))return e;const n=[],r=[];for(const l of e)No(l)||(l.kind==="orderBy"?n.push({field:l.field,direction:l.direction??"asc"}):(l.kind==="where"||l.kind==="and"||l.kind==="or")&&uy(l,r));const s=[...n],i=new Set(s.map(l=>l.field)),o=n.length>0?n[n.length-1].direction:"asc";for(const l of r)l!==Es&&!i.has(l)&&(i.add(l),s.push({field:l,direction:o}));i.has(Es)||s.push({field:Es,direction:o});const a=s.map(l=>({kind:"orderBy",field:l.field,direction:l.direction}));for(const l of e){if(No(l)){const{snapshot:u}=l;if(!u.exists||u.data===void 0)throw new H("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${u.id||"<unknown>"}.`);const d=s.map(h=>h.field===Es?Nr(u.path):Nr(bN(u.data,h.field)));a.push({kind:l.kind,values:d,valueEncoding:un});continue}l.kind!=="orderBy"&&a.push(l)}return a}function _N(e){return{type:"limit",_descriptor:{kind:"limit",n:e}}}function SN(...e){return vN("startAfter",e)}function kN(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),s=[...e.__kind==="query"?Ad.get(e)??e.descriptor.constraints:[],...t.map(a=>ly.get(a)??a._descriptor)],i={__ref:"query",source:n.__ref==="query"?n.source:n,constraints:xN(s)},o=cy(e.port,i,e.converter);return Ad.set(o,s),o}function EN(e){return jN(e,"getDoc")}async function jN(e,t){const n=Jn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDoc",path:e.descriptor.path});return Tn(n,tl(r,e.port,e))}catch(r){throw n.fail(),r}}function CN(e){return IN(e,"getDocs")}async function IN(e,t){const n=Jn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return Tn(n,oy(r,e.port,e.converter))}catch(r){throw n.fail(),r}}async function RN(e){return(await ye(e.port,{t:"op",id:L(),method:"listRootCollections"})).ids}async function NN(e,t){return(await ye(e.port,{t:"op",id:L(),method:"listSubcollections",docPath:t})).ids}function AN(e,t,n,r){const s=typeof t=="function",i=s?void 0:t,o=Xm(i),a=i?.includeMetadataChanges===!0,l={excludesMetadataChanges:!a},u=s?t:n,d=s?n:r;let h=hn();const f=e.port,p=Jn(e,"onSnapshot","subscription",o);p.transport(h);const m={port:f,service:"firestore",next:_=>{let S;try{S=pN(_,f,e.converter,l)}catch(O){v(),d!==void 0?d(O):console.error("pyric/firestore: Uncaught Error in snapshot listener:",O);return}if(S===null)return;const k=S,I=_;p.delivered(k,I.usage),VR(p.id,()=>u(k))},error:_=>{p.fail(),d?.(_)},close:()=>p.close()},g=e.descriptor;function b(){const _={t:"sub",subId:h,target:g};jt!==void 0&&(_.actAs=jt),o!==void 0&&(_.owners=o),a&&(_.includeMetadataChanges=!0);const I=hs(f,h,m,Xc(_));return!I&&p.fail(),!I&&d!==void 0&&queueMicrotask(()=>d(new Error("Firebase App was deleted"))),I}b();let w=!1;const x=NR(()=>{w||(it(f,h),h=hn(),p.transport(h),b())});function v(){w=!0,p.close(),x(),it(f,h)}return v}function dy(e,t){const n=e.converter,r=n!==null;let s=t;return r&&(s=n.toFirestore(t)),iv(s)}async function ON(e,t,n){return Ec(Jn(e,"setDoc","operation"),async()=>{const r=dy(e,t);await ye(e.port,{t:"op",id:L(),method:"setDoc",path:e.descriptor.path,data:Nr(r),valueEncoding:un,options:n})})}async function $N(e){return Ec(Jn(e,"deleteDoc","operation"),async()=>{await ye(e.port,{t:"op",id:L(),method:"deleteDoc",path:e.descriptor.path})})}async function PN(e,t){return Ec(Jn(e,"addDoc","operation"),async()=>{const n=dy(e,t),r=await ye(e.port,{t:"op",id:L(),method:"addDoc",collectionPath:e.descriptor.path,data:Nr(n),valueEncoding:un});return zt(e.port,r.path,e.converter)})}async function DN(e,t){return await Q(e.port,{t:"op",id:L(),method:"admin.listDocuments",path:t})}const TN=xc({__type:"path",segments:[]},un).constructor;class MN{port;subId=hn();subscribers=new Set;history=new Lh(Uh);isAwaitingHistory=!0;hasReceivedHistory=!1;constructor(t){this.port=t}open(t){this.subscribers.add(t),Rn.set(this.port,this);const n={t:"sub",subId:this.subId,target:"events"};wR(this.port,this.subId,r=>this.receive(r),n,r=>this.fail(r),()=>{this.isAwaitingHistory=!0})}join(t){this.subscribers.add(t),this.hasReceivedHistory&&queueMicrotask(()=>{this.subscribers.has(t)&&Od(t,this.history.snapshot())})}leave(t){this.subscribers.delete(t)&&this.subscribers.size===0&&(Rn.delete(this.port),it(this.port,this.subId))}receive(t){const n=this.isAwaitingHistory;n&&this.history.clear();for(const s of t)this.record(s);this.isAwaitingHistory=!1;const r=n&&!this.hasReceivedHistory;this.hasReceivedHistory=!0;for(const s of[...this.subscribers])this.subscribers.has(s)&&(r?Od(s,t):s.isPrimed&&fy(s,t,n))}record(t){t.kind==="session_boundary"&&t.phase==="reset"?this.history.clear():this.history.append(t)}fail(t){Rn.get(this.port)===this&&Rn.delete(this.port);const n=[...this.subscribers];this.subscribers.clear();for(const r of n)try{r.onError?.(t)}catch(s){console.error("pyric: Uncaught Error in event subscriber error handler:",s)}}}const Rn=new WeakMap;function fy(e,t,n){try{e.callback(t,{history:n})}catch(r){console.error("pyric: Uncaught Error in event subscriber:",r)}}function Od(e,t){e.isPrimed=!0,fy(e,t,!0)}function LN(e,t,n){const r=e.port,s={callback:t,onError:n,isPrimed:!1},i=Rn.get(r);return i?i.join(s):new MN(r).open(s),()=>{Rn.get(r)?.leave(s)}}function UN(e){return e.__type__==="__vector__"&&Array.isArray(e.value)?!0:typeof e.__type=="string"?e.__type==="timestamp"||e.__type==="bytes"||e.__type==="latlng"||e.__type==="duration"||e.__type==="reference":typeof e.type=="string"?e.type==="firestore/timestamp/1.0"||e.type==="firestore/bytes/1.0"||e.type==="firestore/geoPoint/1.0"||e.type==="firestore/vectorValue/1.0":!1}function zs(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(zs);const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;const n=e;if(n.type==="pyric/map/1.0"){const s=n.fields;if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError("Invalid encoded map fields.");const i={};for(const[o,a]of Object.entries(s))i[o]=zs(a);return i}if(n.__type==="number"){if(n.value==="NaN")return Number.NaN;if(n.value==="Infinity")return 1/0;if(n.value==="-Infinity")return-1/0;if(n.value==="-0")return-0}if(n.__type==="path"&&Array.isArray(n.segments)){const s=n.bindings,i=s!==null&&typeof s=="object"&&!Array.isArray(s)?s:void 0;return new TN(n.segments,i)}if(UN(n))return xc(n,un);const r={};for(const[s,i]of Object.entries(n))r[s]=zs(i);return r}async function BN(e){const t=await Q(e.port,{t:"op",id:L(),method:"getSnapshot"}),n={};for(const[r,s]of Object.entries(t.firestore??{}))n[r]=zs(s);return{firestore:n,services:t.services}}async function FN(e){return await Q(e.port,{t:"op",id:L(),method:"resetAll"})??{errors:[]}}const qN=15e3;function VN(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function $d(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function Pd(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function WN(){return VN()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Dd(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Td(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function zN(e){const{db:t,kind:n}=e,r=e.clientId??WN(),s=e.heartbeatIntervalMs??qN;let i=!1,o=null;const a=()=>{Q(t.port,{t:"op",id:L(),method:"presence.register",clientId:r,kind:n,route:Dd(),visibility:Td()}).catch(()=>{})},l=()=>{Q(t.port,{t:"op",id:L(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{Q(t.port,{t:"op",id:L(),method:"presence.update",clientId:r,route:Dd(),visibility:Td()}).catch(()=>{})},d=()=>{Q(t.port,{t:"op",id:L(),method:"presence.disconnect",clientId:r}).catch(()=>{})};a(),$d()&&document.addEventListener("visibilitychange",u),Pd()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",h),o=setInterval(()=>{i||l()},s));function h(){f()}function f(){i||(i=!0,o!=null&&(clearInterval(o),o=null),$d()&&document.removeEventListener("visibilitychange",u),Pd()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",h)),d())}return{clientId:r,kind:n,stop:f}}function HN(e,t){const n=hn();return hs(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{it(e.port,n)}}async function KN(e){return await Q(e.port,{t:"op",id:L(),method:"auth.listUsers"})}async function GN(e,t){return await Q(e.port,{t:"op",id:L(),method:"auth.adminCreateUser",request:t})}async function JN(e,t,n){return await Q(e.port,{t:"op",id:L(),method:"auth.adminUpdateUser",uid:t,request:n})}async function YN(e,t){await Q(e.port,{t:"op",id:L(),method:"auth.adminDeleteUser",uid:t})}async function QN(e){await Q(e.port,{t:"op",id:L(),method:"auth.adminClearUsers"})}async function XN(e){return await Q(e.port,{t:"op",id:L(),method:"auth.getProviderConfig"})}async function ZN(e,t,n){await Q(e.port,{t:"op",id:L(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const eA=Symbol("pyric.clientUser.port");function tA(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:Fp(t.photoURL,qp()),phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,eA,{value:e,enumerable:!1}),n}function hy(e,t){return t?tA(e,t):null}function nA(e,t){let n;if(typeof e=="string"||e instanceof URL){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),Hi(n)}else n=e.port;let s=null;const i={__kind:"client-auth",port:n,currentUser:null,get tenantId(){return s},set tenantId(a){s=a,Q(n,{t:"op",id:L(),method:"auth.setTenantId",tenantId:a})}};n.restoreAuth=async a=>{await a({t:"op",id:L(),method:"auth.setTenantId",tenantId:i.tenantId});const l=i.currentUser;l!==null&&await rA(i,l.uid,a,l.tenantId)};const o=hn();return hs(n,o,{port:n,next:a=>{i.currentUser=hy(n,a)}},{t:"sub",subId:o,target:"idToken"}),i}async function rA(e,t,n=s=>Q(e.port,s),r=e.tenantId){const s=await n({t:"op",id:L(),method:"auth.restorePortSession",uid:t,tenantId:r}),i=hy(e.port,s);return e.currentUser=i,i}const sA=1e4,py="The hosted sandbox connection was not restored within 10 seconds. The request was not sent.";let my=sA;function iA(e){let t;const n=new Promise((r,s)=>{t=setTimeout(()=>s(new H("unavailable",py)),my)});return Promise.race([e,n]).finally(()=>clearTimeout(t))}function Ao(e){if("id"in e&&typeof e.id=="string")return e.id}function Md(e){if(e.t==="sub"||e.t==="unsub")return e.subId}function oA(e){const t=[];function n(s,i){const o=t.indexOf(s);o<0||(t.splice(o,1),zr(e,new H("unavailable",py),l=>l===i))}function r(){const s=t.splice(0);for(const i of s)clearTimeout(i.deadline);return s}return{hold(s){const i={message:s},o=Ao(s);if(t.push(i),o===void 0)return;const l=Qe.get(o);if(!(l!==void 0&&l.port===e))return;const d=l.issuedAt+my-Qc();if(d<=0){n(i,o);return}i.deadline=setTimeout(()=>n(i,o),d)},holdAgain(s){t.unshift(...s.map(i=>({message:i})))},holdsRequest(s){return t.some(i=>Ao(i.message)===s)},holdsSubscription(s){const i=Md(s);return i!==void 0?t.some(a=>a.message.t==="sub"&&a.message.subId===i):!1},forgetSubscription(s){const i=t.findIndex(a=>a.message.t==="sub"&&a.message.subId===s),o=i>=0;return o&&t.splice(i,1),o},flush(s){const i=r(),o=a=>Md(a.message)!==void 0;for(const a of i.filter(o))s(a.message);for(const a of i.filter(l=>!o(l)))s(a.message)},drop(){r()},fail(s){const i=new Set(r().map(o=>Ao(o.message)));zr(e,s,o=>i.has(o))}}}function aA(e){return e.then(t=>({result:t}),t=>({error:t}))}function cA(e){return e!==void 0&&"result"in e?e.result:void 0}function yy(e){const t=e?.code;if(typeof t=="string")return t}async function lA(e,t){if(!(t!==void 0))return!1;try{return await CA(e,t),!0}catch(r){if(yy(r)==="storage/unauthorized")return!1;throw r}}async function uA(e,t){if(t.replacedObject===!0)throw new H("storage/unknown","The host no longer holds the object this upload replaced, so it cannot be restored.");try{await Iy(e)}catch(n){if(!(yy(n)==="storage/object-not-found"))throw n}}function dA(e){return e.replacedObject===!0?"restore":"remove"}async function fA(e,t){try{await lA(e,t.rollbackToken)||await uA(e,t)}catch(n){throw ka(e.fullPath,n,dA(t))}}function hA(e){return e instanceof Error?e:new Error(String(e))}function pA(e){return e instanceof Blob?e.size:e.byteLength}function mA(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function yA(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class gA{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_heldOutcome;_sentCommit;_error;_ref;_data;_metadata;_upload;_inFlight;_sending=!1;_resyncs=!1;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=pA(n),i=new Date(YI()).toISOString();let o="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(o=n.type),r!==void 0&&r.contentType!==void 0){const h=r.contentType;h!==void 0&&(o=h)}const u={fullPath:t.fullPath,name:t.name,bucket:t.bucket||"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:o};this._promise=new Promise((d,h)=>{this._resolve=d,this._reject=h}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},this._start(),queueMicrotask(()=>{this._runStep()})}_start(){!(this._ref.port.byteRouteSettled?.()!==void 0)&&Er(this._ref)!==void 0?this._sendOverRoute():this._commitUpload()}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._resyncs=!0,this._inFlight?.abort(),this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;if((this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t){const r=mA();return this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._inFlight?.abort(),this._rollBackCanceled().then(()=>this._settleCanceled(r),s=>this._settleCanceled(hA(s))),!0}return!1}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=this._sentCommit,r=t??(n===void 0?void 0:await n),s=this._upload;s!==void 0&&await Hs(s);const i=cA(r);i!==void 0&&await fA(this._ref,i)}_sendCommit(t){const n=aA(t);return this._sentCommit=n,n}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,"result"in t?this._succeed(t.result.metadata):this._fail(t.error),!0)}on(t,n,r,s){let i,o,a,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Bt(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Bt(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Bt(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{pi(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const a=i.next;try{Bt(this),a(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const a=i.complete;try{pi(this),a()}catch{}}}}async _sendOverRoute(){if(this._sending)return;this._sending=!0;const t=Ey(this._data),n=()=>this._snapshot.state==="running";try{const r=Er(this._ref);let s=this._upload;if(s===void 0){const l=this._metadata?.contentType??(t.type!==""?t.type:void 0);if(s=await xy(this._ref,r,t.size,l,this._metadata),this._upload=s,this._snapshot.state==="canceled"&&await Hs(s),!n())return}let i=this._snapshot.bytesTransferred;for(this._resyncs&&(i=await jA(s),this._resyncs=!1);n()&&i<s.size;){const l=new AbortController;if(this._inFlight=l,i=await Sy(s,t,i,l.signal),this._inFlight=void 0,!n())return;this._updateSnapshot("running",i),this._notifyObservers("next")}if(!n())return;const o=await this._sendCommit(ky(s,!0));if("error"in o&&n())throw o.error;this._settleCommit(o)}catch(r){if(this._inFlight=void 0,!n())return;this._error=r instanceof Error?r:new Error(String(r)),this._updateSnapshot("error",this._snapshot.bytesTransferred);const s=this._upload;s!==void 0&&await Hs(s),this._notifyObservers("error"),this._reject(this._error)}finally{this._sending=!1,n()&&queueMicrotask(()=>this._runStep())}}_runStep(){if(this._snapshot.state!=="running")return;if(Er(this._ref)!==void 0&&!this._committing){this._releaseHeldOutcome()||this._sendOverRoute();return}if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let i=0;this._snapshot.totalBytes>0&&(i=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",i),this._notifyObservers("next")}this._releaseHeldOutcome()||this._commitUpload()}_succeed(t){this._updateSnapshot("success",this._snapshot.totalBytes,t),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot)}_fail(t){this._error=t instanceof Error?t:new Error(String(t)),this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=await this._sendCommit(jy(this._ref,this._data,this._metadata,!0));this._committing=!1,this._settleCommit(r)}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){"result"in t?this._succeed(t.result.metadata):this._fail(t.error);return}n==="paused"&&(this._heldOutcome=t)}}function bA(e,t,n){if(e.fullPath==="")throw yA();return new gA(e,t,n)}class Hr{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=Zc(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 Hr(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Hr(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function wA(e){return e.replace(/^\/+|\/+$/g,"").replace(/\/+/g,"/")}function vA(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(),Hi(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function xA(e,t){const n=wA(_a(t,e.__kind==="client-storage"));let r,s,i="pyric-default",o;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,o=e;else{const a=e.fullPath;r=n?a?`${a}/${n}`:n:a,s=e.port,i=e.bucket,o=e.storage}return new Hr(s,i,r,o)}async function _A(e){const t=await ye(e.port,{t:"op",id:L(),method:"storage.listAll",path:e.fullPath}),n=r=>new Hr(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}function gy(e,t){return e.bucket?{...t,bucket:e.bucket}:t}async function by(e){return await ye(e.port,{t:"op",id:L(),method:"storage.getMetadata",path:e.fullPath})}async function wy(e){return gy(e,await by(e))}const SA=4*1024*1024;async function kA(e){const t=await e.sessionToken();if(t===null||t==="")throw new H("unavailable","The page has no session token for the hosted byte route. Reload the page.");return t}function rl(e,t){return e===401||e===403?new H("storage/unauthorized",`The host refused bytes for '${t}' (HTTP ${e}).`):e===404?new H("storage/object-not-found",`Object '${t}' does not exist.`):new H("storage/unknown",`The host's byte route answered HTTP ${e} for '${t}'.`)}async function EA(e,t){for(let n=0;n<2;n++){const r=await by(t),s=new URL($C(r.bucket,t.fullPath),e.baseUrl);s.searchParams.set("generation",r.generation);const i=await fetch(s,{headers:{"x-pyric-session-token":await kA(e)}});if(i.status===412)continue;if(!i.ok)throw rl(i.status,t.fullPath);const a=new Uint8Array(await i.arrayBuffer());return{bytes:a,contentType:i.headers.get("content-type")??r.contentType,size:a.byteLength}}throw new H("storage/retry-limit-exceeded",`Object '${t.fullPath}' kept changing while it was read.`)}function Er(e){return e.port.byteRoute}async function vy(e,t){const n=e.port.byteRouteSettled?.();if(n===void 0)return t(Er(e),void 0);const s=Vm(e.port);try{return await iA(n),await t(Er(e),s)}finally{s.release()}}async function xy(e,t,n,r,s){const i=await ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:n,...r!==void 0?{contentType:r}:{},...s!==void 0?{metadata:s}:{}}),o=i.uploadUrl;if(o===void 0)throw new H("storage/unknown","The host began the upload without a byte route URL.");return{uploadId:i.uploadId,url:new URL(o,t.baseUrl).href,size:n,reference:e}}function _y(e,t){if(e.status===200)return t;const r=/^bytes=0-(\d+)$/.exec(e.headers.get("range")??"");return r===null?0:Number(r[1])+1}async function Sy(e,t,n,r){const s=Math.min(n+SA,e.size),i=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes ${n}-${s-1}/${e.size}`},body:t.slice(n,s),signal:r});if(!(i.status===200||i.status===308||i.status===409))throw rl(i.status,e.reference.fullPath);return _y(i,e.size)}async function jA(e,t){const n=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes */${e.size}`},signal:t});if(!(n.status===200||n.status===308))throw rl(n.status,e.reference.fullPath);return _y(n,e.size)}function Ua(e,t){const{rollbackToken:n,replacedObject:r,...s}=t,i=gy(e,s);return typeof n=="string"?{metadata:i,rollbackToken:n,replacedObject:r===!0}:{metadata:i}}function Ba(e){return e?{rollback:!0}:{}}async function ky(e,t=!1){const n=await ye(e.reference.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:e.uploadId,...Ba(t)});return Ua(e.reference,n)}async function CA(e,t){await ye(e.port,{t:"op",id:L(),method:"storage.rollbackUpload",rollbackToken:t})}async function Hs(e){try{await ye(e.reference.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:e.uploadId})}catch{}}function Ey(e){return e instanceof Blob?e:new Blob([e])}async function IA(e,t){const n=await RA(e),r=typeof t=="number"&&n.bytes.byteLength>t?n.bytes.subarray(0,Math.max(0,t)):n.bytes,s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return new Blob([s],{type:n.contentType??"application/octet-stream"})}async function RA(e){return vy(e,(t,n)=>t!==void 0?(n?.release(),EA(t,e)):NA(e,n))}async function NA(e,t){try{const n=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath},t);return{bytes:Nd(n.dataB64),contentType:n.contentType,size:n.size}}catch(n){if(n?.code==="payload-too-large"){const r=await wy(e),s=[];let i=0;for(;i<r.size;){const l=Math.min(Ma,r.size-i),u=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath,offset:i,length:l,expectedGeneration:r.generation});s.push(Nd(u.dataB64)),i+=l}const o=new Uint8Array(r.size);let a=0;for(const l of s)o.set(l,a),a+=l.byteLength;return{bytes:o,contentType:r.contentType,size:r.size}}throw n}}async function AA(e,t,n){const r=await jy(e,t,n,!1);return{ref:e,metadata:r.metadata}}async function jy(e,t,n,r){return vy(e,(s,i)=>{if(s!==void 0)return i?.release(),$A(e,s,Ey(t),n,r);if(t instanceof Blob)return OA(e,t,n,r,i);const l=t instanceof ArrayBuffer?new Uint8Array(t):t;return Cy(e,l,n?.contentType,n,r,i)})}async function OA(e,t,n,r,s){if(t.size>Gi)throw el(t.size,`uploadBytes payload for '${e.fullPath}'`);const o=n?.contentType??(t.type!==""?t.type:void 0),a=s??Vm(e.port);try{const l=new Uint8Array(await t.arrayBuffer());return await Cy(e,l,o,n,r,a)}finally{a.release()}}async function Cy(e,t,n,r,s,i){if(t.byteLength>Gi)throw el(t.byteLength,`uploadBytes payload for '${e.fullPath}'`);if(t.byteLength<=Ma){const u=ye(e.port,{t:"op",id:L(),method:"storage.putBytes",path:e.fullPath,dataB64:Rd(t),...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{},...Ba(s)},i);return i?.release(),Ua(e,await u)}const o=ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:t.byteLength,...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{}},i);i?.release();const l=(await o).uploadId;try{let u=0,d=0;for(;u<t.byteLength;){const f=Math.min(u+Ma,t.byteLength),p=t.subarray(u,f);await ye(e.port,{t:"op",id:L(),method:"storage.putPart",uploadId:l,partIndex:d,dataB64:Rd(p)}),u=f,d++}const h=await ye(e.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:l,...Ba(s)});return Ua(e,h)}catch(u){try{await ye(e.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:l})}catch{}throw u}}async function $A(e,t,n,r,s){if(n.size>Gi)throw el(n.size,`uploadBytes payload for '${e.fullPath}'`);const o=r?.contentType??(n.type!==""?n.type:void 0),a=await xy(e,t,n.size,o,r);try{let l=0;for(;l<a.size;)l=await Sy(a,n,l);return await ky(a,s)}catch(l){throw await Hs(a),l}}async function Iy(e){await ye(e.port,{t:"op",id:L(),method:"storage.deleteObject",path:e.fullPath})}function ps(e,t){return{instance:t??("instance"in e?e.instance?.name:void 0)}}async function PA(e,t){return Q(e.port,{t:"op",id:L(),method:"rtdb.adminSnapshot",...ps(e,t)})}async function DA(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"},...ps(e,r)})}async function TA(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"},...ps(e,r)})}async function MA(e,t,n){await Q(e.port,{t:"op",id:L(),method:"rtdb.remove",path:t,actAs:{mode:"admin"},...ps(e,n)})}function LA(e,t,n,r,s){const i=hn();return!hs(e.port,i,{port:e.port,next:a=>n(a?.value??null),error:r},Xc({t:"sub",subId:i,target:{service:"rtdb",...ps(e,s),path:nN(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>it(e.port,i)}const UA="/__pyric/diagnostics";function BA(e){const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))throw new Error("Unsupported diagnostic URL scheme.");const r=t.pathname==="/__pyric/sandbox"?t.pathname:"";return`${t.origin}${r}`}function FA(){if(globalThis.__pyricDiagnostics)return globalThis.__pyricDiagnostics;if(typeof location>"u"||!(location.protocol==="http:"||location.protocol==="https:"))return;const t={version:1,clientId:`browser-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,sequence:0,realm:typeof document>"u"?"service-worker":"page",pageOrigin:location.origin,events:[]};let n,r=!1;const s=()=>({...t,events:t.events.map(a=>({...a}))}),i=()=>{n!==void 0||r||(n=setTimeout(()=>{n=void 0,o.flush()},100))},o={getSnapshot:s,record(a){const l=a.endpoint?BA(a.endpoint):void 0;t.sequence+=1,t.events.push({...a,endpoint:l,at:Date.now()}),t.events=t.events.slice(-32),i()},async flush(){if(r)return;r=!0;const a=t.sequence,l=new AbortController,u=setTimeout(()=>l.abort(),2e3);try{await fetch(new URL(UA,location.href),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s()),signal:l.signal,credentials:"same-origin",keepalive:!0})}catch{}finally{clearTimeout(u),r=!1,t.sequence>a&&i()}}};return globalThis.__pyricDiagnostics=o,globalThis.addEventListener("online",i),globalThis.addEventListener("pagehide",()=>{clearTimeout(n),n=void 0,o.flush()}),o}function qA(e){try{FA()?.record(e)}catch{}}function VA(e){const t=typeof e.bridgeVersion=="string"&&typeof e.peerConnected=="boolean"&&typeof e.clientSessionId=="string",r=[e.projectKey,e.serveVersion,e.sessionId,e.resumeToken,e.hostInstanceId].every(a=>a===void 0||typeof a=="string"),s=e.capabilities,i=s===void 0||Array.isArray(s)&&s.every(a=>typeof a=="string"),o=e.sandboxConnected===void 0||typeof e.sandboxConnected=="boolean";return t&&r&&i&&o}const Kr="Bridge response exceeds the 12 MiB encoded frame limit.",Fa=4009,jr={code:"resource-exhausted",message:Kr},qa=new TextEncoder;function Ry(e){const t=JSON.stringify(e);if(qa.encode(t).byteLength<=qr)return t;const r=zA(e),s=JSON.stringify(r);return qa.encode(s).byteLength>qr?WA(r):s}function WA(e){if(e.type!=="worker-message-result")return;const n=e.message;if(n.t!=="event")return;const s=n.events[0],i=n.events.at(-1);if(s===void 0||i===void 0)return;const a={...e,message:{...n,events:[{kind:"observation_gap",id:`observation-gap:${s.id}:${i.id}`,at:s.at,reason:"frame-limit",omittedCount:n.events.length,firstEventId:s.id,lastEventId:i.id}]}},l=JSON.stringify(a);if(qa.encode(l).byteLength<=qr)return l}function zA(e){switch(e.type){case"tool-result":return{type:"tool-result",id:e.id,ok:!1,error:jr};case"worker-message-result":return{...e,message:HA(e.message)};case"worker-res":return{type:"worker-res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:jr};case"worker-snap":return{...e,value:{__error:jr}};default:return e}}function HA(e){switch(e.t){case"res":return{t:"res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:jr};case"snap":return{...e,value:{__error:jr}};case"event":{const t=e.events.map(n=>{if(n.kind==="snapshot_delivery"){const s={...n};return delete s.sample,s}return n});return{...e,events:t}}default:return e}}const Ld={"rtdb.set":"resend","rtdb.setPriority":"resend","rtdb.setWithPriority":"resend","rtdb.update":"resend","rtdb.remove":"resend","rtdb.push":"resend","rtdb.get":"resend","rtdb.onDisconnectSet":"forget","rtdb.onDisconnectUpdate":"forget","rtdb.onDisconnectRemove":"forget","rtdb.onDisconnectCancel":"forget","rtdb.transactionCommit":"disconnect"};function KA(e){return Object.hasOwn(Ld,e)?Ld[e]:"fail"}function GA(e){return e.t==="op"?KA(e.method):"fail"}function JA(e,t,n,r){const s=[];for(const{id:i,message:o}of SR(e,a=>r(a)&&!zm(e,a))){const a=GA(o);a==="resend"?s.push(i):a==="forget"?ER(i):a==="disconnect"?Sd(i,new Error("disconnect")):Sd(i,n)}t.holdAgain(kR(s))}function YA(e){const t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.origin}const Oo="The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying.",$o="The hosted sandbox connection is closed.",QA=new TextEncoder;function XA(e,t){const n=`socket-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=(M,ne)=>{qA({phase:M,connectionId:n,endpoint:e.url,code:ne})},s=new Set;let i="connecting",o,a,l=e.initialHostInstanceId,u=!1,d,h=!1,f=!1,p=0,m,g,b,w,x=0;const v=e.realm;let _=!1,S=()=>{};const k=new Promise(M=>{S=M}),I=()=>{_=!0,S()},O=M=>(v?.releaseTimer(M),M),P=M=>{v?.traffic(R,M)},R=Object.assign({},{onmessage:null,postMessage(M){if(i==="closed")throw new H("unavailable",$o);M.t==="appConfig"&&(d=M),P({sent:M});const ce=i==="attached";if(!ce&&M.t==="disconnect"){E.drop(),A({t:"res",id:M.id,ok:!0,value:void 0});return}if(!ce){if((M.t==="op"||M.t==="tool")&&!Qe.has(M.id))return;C({type:"worker-message",message:M}),E.hold(M);return}const fe=o;if(fe===void 0)throw new H("unavailable",$o);N(fe,{type:"worker-message",message:M})},start(){},withdrawSubscription(M){return E.forgetSubscription(M)},byteRouteSettled(){return _?void 0:k},observeConnection(M){return s.add(M),queueMicrotask(()=>{s.has(M)&&M(i==="attached")}),()=>{s.delete(M)}},close(){j(new H("unavailable",$o))}}),E=oA(R);function j(M){if(i==="closed")return;i="closed",$(),s.clear(),Km(R),E.fail(M),zr(R,M),cN(R,M),a=void 0,m=void 0,l=void 0,u=!1,d=void 0,R.restoreAuth=void 0,R.messagingVisibility=void 0,clearTimeout(g),clearTimeout(b),clearTimeout(w);const ge=o;o=void 0;const ce=ge?.readyState===WebSocket.OPEN;try{ce&&N(ge,{type:"worker-message",message:{t:"disconnect",id:L()}})}catch{}ge?.close(),R.onmessage=null,I(),P({closed:!0})}function $(){r(i),e.onConnection?.(i);const M=i==="attached";for(const ne of[...s])ne(M)}function C(M){const ne=Ry(M);if(ne===void 0)throw new H("resource-exhausted","Bridge request exceeds the 12 MiB encoded frame limit.");return ne}function N(M,ne){M.send(C(ne))}function A(M){R.onmessage?.(new MessageEvent("message",{data:M})),P({})}function D(M){if(i==="closed")return;const ge=new H("unavailable",M);j(ge),e.onError?.(ge)}function T(M){return o===M&&i!=="closed"}function W(M){if(!T(M))return;clearTimeout(g),clearTimeout(w),m??=performance.now(),i="interrupted",o=void 0,$();const ge=new H("unavailable",Oo);JA(R,E,ge,ve=>!E.holdsRequest(ve)&&!zm(R,ve)),CR(R,ge,ve=>E.holdsSubscription({t:"unsub",subId:ve})),P({}),M.close();const ce=Math.min(5e3,250*2**p);p+=1;const Z=Math.random()*Math.min(250,ce/10);b=O(setTimeout(Se,Math.min(5e3,ce+Z)))}function U(M){const ne=vd-(performance.now()-x),ge=Math.max(0,Math.min(Tm,ne));w=O(setTimeout(()=>{if(!T(M))return;if(performance.now()-x>=vd){W(M);return}try{N(M,{type:"ping",id:L()})}catch{W(M);return}U(M)},ge))}async function V(M,ne){const ge=ne||p>0,ce=ve=>{if(!T(M))throw new H("unavailable",Oo);N(M,{type:"worker-message",message:ve})},Z=ve=>{E.holdsSubscription(ve)||ce(ve)};if(h){i="restoring",r(i),e.onConnection?.(i);const ve=d;if(ve!==void 0&&ce(u?{...ve,fromPriorHost:!0}:ve),await R.restoreAuth?.(wt=>Ki(R,wt,ce)),!T(M))return;_R(R,Z),h=!1}clearTimeout(g),i="attached",f=!0,p=0,m=void 0,x=performance.now(),clearTimeout(w),U(M),ne&&(ce({t:"clock-subscribe"}),xR(R,Z)),ge&&vR(R,Z),E.flush(ce),$()}async function F(){const M=e.currentHostInstanceId;if(!(f&&M!==void 0))return l;try{return await M()??l}catch{return l}}function Se(){if(i==="closed")return;i="connecting",r("connecting");const ne=f?"interrupted":"connecting";e.onConnection?.(ne),m!==void 0&&performance.now()-m>=rR&&(a=void 0);const ce=a===void 0;let Z;try{Z=v?v.createSocket(e.url):new WebSocket(e.url)}catch(fe){throw r("socket-error"),fe}o=Z,g=O(setTimeout(()=>{if(!T(Z))return;r("timeout"),f||e.retryInitialConnection===!0?W(Z):D("Timed out connecting to the hosted sandbox.")},5e3)),Z.addEventListener("error",()=>{T(Z)&&r("socket-error")});let ve=l;Z.addEventListener("open",()=>{T(Z)&&(r("transport-open"),F().then(et=>{if(!T(Z))return;ve=et,et!==l&&(a=void 0),N(Z,{type:"attach",protocol:1,transport:"worker-port",resumeToken:a,hostInstanceId:et,clientInfo:{platform:v?.platform??"browser"}})}))}),Z.addEventListener("message",fe=>{if(!T(Z))return;if(QA.encode(fe.data).byteLength>qr){Z.close(Fa,Kr),D(Kr);return}let ut;try{ut=JSON.parse(fe.data)}catch{D("The hosted sandbox sent invalid JSON. Requests already sent may have completed; check state before retrying.");return}const oe=ut;if(!Mm(oe)){D("The hosted sandbox sent an invalid message. Requests already sent may have completed; check state before retrying.");return}switch(x=performance.now(),oe.type){case"attach-ack":{if(oe.protocol!==1){D("The hosted sandbox uses an unsupported bridge protocol. Expected version 1.");return}const Xn=oe.capabilities;if(!(Array.isArray(Xn)&&Xn.every(Al=>typeof Al=="string")&&Xn.includes(nR))){D("The selected host does not support browser worker ports. Upgrade @pyric/cli, restart with --hosted, and reload this page.");return}const nw=Xn.includes(tR),Nl=e.sessionToken;if(nw&&Nl!==void 0?R.byteRoute={baseUrl:YA(e.url),sessionToken:Nl}:delete R.byteRoute,I(),v?.attached?.(oe),oe.projectKey!==e.projectKey){D("The selected hosted sandbox belongs to a different project.");return}if(!VA(oe)){D("The hosted sandbox sent a malformed attachment acknowledgment.");return}const ys=f,oo=typeof oe.hostInstanceId=="string"&&oe.hostInstanceId.length>0,ao=ys&&l!==void 0&&oo&&oe.hostInstanceId!==l,rw=oo&&oe.hostInstanceId===ve;ao&&!rw&&(u=!0);const sw=ys&&!ce,iw=oe.resumeToken!==a;if(sw&&iw&&!ao){D("The hosted session could not be resumed.");return}a=typeof oe.resumeToken=="string"&&oe.resumeToken.length>0?oe.resumeToken:void 0,l=oo?oe.hostInstanceId:void 0,ys&&(ao||ce)&&(h=!0),V(Z,ys).catch(()=>{T(Z)&&D("Could not restore the hosted app session.")});return}case"worker-message-result":{const Ge=oe.message;Bm(Ge)&&Ge.t==="res"&&Um(Ge)&&Ge.ok===!1&&(Ge.error.code==="committed-but-not-durable"||Ge.error.code==="persistence-unhealthy")&&e.onError?.(new H(Ge.error.code,Ge.error.message)),A(Ge);return}}}),Z.addEventListener("close",fe=>{if(!T(Z))return;r("socket-close",fe.code),clearTimeout(g),f&&fe.code===sR&&(a=void 0),(f||e.retryInitialConnection===!0)&&fe.code!==1008?W(Z):D(Oo)})}const we={__kind:"client-db",port:R};return Hi(R),Se(),we}function ZA(){if(!(typeof document<"u"))return null;const n=document.querySelector('meta[name="pyric-sandbox-host"]');if(!(n?.getAttribute("content")==="node"))return null;const i=n.getAttribute("data-project-key");if(!(i!==null&&i.length>0))throw new Error("The hosted sandbox has no project identity. Restart the host and reload Studio.");return{url:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/__pyric/sandbox`,projectKey:i}}function e0(e){const t=new Set;let n={mode:"hosted",servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:"Connecting to the hosted sandbox."};function r(o){n={...n,error:o};for(const a of t)a()}return{db:XA({...e,sessionToken:()=>Wi(location.origin),onConnection(o){switch(o){case"attached":r(null);return;case"connecting":r("Connecting to the hosted sandbox.");return;case"restoring":r("Restoring the hosted session.");return;case"interrupted":r("Hosted connection lost; reconnecting.");return;case"closed":r("Hosted connection closed. Repair the host and reload Studio.");return}},onError:o=>r(o.message)}),runtime:{getSnapshot:()=>n,subscribe(o){return t.add(o),()=>{t.delete(o)}},async update(){throw new Error("Restart the hosted sandbox and reload Studio to update it.")},dispose(){t.clear()}}}}function t0(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=l=>{n={...n,...l};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let o=null;const a=()=>i?(o??=TI({targetEpoch:i,retire:()=>e.retire?e.retire(i):PR(e.db,i),subscribeReload:e.subscribeReload??DR,preflight:e.preflight??(()=>DI(s)),commitGeneration:e.remember??(l=>PI(l,s)),onPreparationError:l=>r({updating:!1,error:l instanceof Error?l.message:String(l)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),o):null;return(e.readVersion??(()=>zR(e.db)))().then(l=>r({runningEpoch:l,updateAvailable:!!(i&&l!=="dev"&&l!==i)})).catch(l=>r({error:l instanceof Error?l.message:String(l)})),{getSnapshot:()=>n,subscribe(l){return t.add(l),a(),()=>{t.delete(l),t.size===0&&(o?.dispose(),o=null)}},async update(){const l=a();if(!l||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await l.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),o?.dispose(),o=null}}}function n0(e={}){const t=Pm(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:$I(t.worker.servedEpoch,n)}}const r0="/__pyric/sdk/worker.js";function s0(e){const t=new Lh(Uh);let n=!1;const r=new Set;let s=null;function i(){s||(s=LN(e,o=>{const a=!n;n=!0,a&&t.clear();for(const l of o)Im(l)&&t.clear(),t.append(l);for(const l of o)for(const u of r)u(l)}))}return{history:()=>t.snapshot(),subscribe:o=>(r.add(o),i(),()=>{r.delete(o),r.size===0&&s&&(s(),s=null,n=!1,t.clear())})}}function Ud(e){let t=!1,n=null;const r=()=>{t=!0;const s=(async()=>e())(),i=()=>{t=!1;const o=n;n=null,o&&r().then(o.resolve,o.reject)};return s.then(i,i),s};return()=>{if(!t)return r();if(!n){let s,i;n={promise:new Promise((a,l)=>{s=a,i=l}),resolve:s,reject:i}}return n.promise}}function i0(e=r0){const t=ZA(),n=t!==null;if(!n&&typeof SharedWorker>"u")return null;OR("studio");const s=n?e0(t):null;let i;if(s!==null)i=s.db;else try{const m=n0({workerUrl:e});i=WR(m.url,m.name)}catch{return null}let a;try{a=typeof localStorage<"u"?localStorage:void 0}catch{a=void 0}const l=typeof document<"u",u=s?.runtime??t0({db:i,servedEpoch:Pm(l?document:void 0).worker.servedEpoch,storage:a});Ed({mode:"admin"});const d=zN({db:i,kind:"studio"}),h=s0(i),f=nA(i);let p=!1;return{db:i,runtime:u,dispose:async()=>{p||(p=!0,d.stop(),u.dispose(),await aN(i).catch(()=>{}))},presenceClientId:d.clientId,subscribePresence:m=>HN(i,m),instanceId:()=>HR(i),exportState:()=>KR(i),importState:m=>GR(i,m),saveState:m=>JR(i,m),listStates:()=>YR(i),restoreState:m=>QR(i,m),deleteState:m=>XR(i,m),feed:h,setLens:m=>Ed(m),getLens:()=>AR(),listRootCollections:Ud(()=>RN(i)),listSubcollections:m=>NN(i,m),listDocuments:async m=>(await DN(i,m)).map(({path:g,phantom:b})=>({path:g,phantom:b})),readRtdbState:()=>PA(i),setRtdbValue:(m,g)=>DA(i,m,g),updateRtdbValue:(m,g)=>TA(i,m,g),deleteRtdbValue:m=>MA(i,m),subscribeRtdbValue:(m,g,b)=>LA(i,m,g,b),firestoreApi:{collection:yN,doc:mN,getDoc:EN,getDocs:CN,onSnapshot:AN,setDoc:ON,deleteDoc:$N,addDoc:PN,query:kN,limit:_N,startAfter:SN},auth:f,authApi:{listUsers:Ud(()=>KN(f)),subscribeUsers:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.service==="auth"&&g()}),createUser:(m,g)=>GN(f,g),updateUser:(m,g,b)=>JN(f,g,b),deleteUser:(m,g)=>YN(f,g),clearUsers:()=>QN(f),getAuthProviderConfig:()=>XN(f),setAuthProviderConfig:(m,g,b)=>ZN(f,g,b),subscribeAuthProviderConfig:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.op==="provider_config_update"&&g()})},storage:vA(i),storageApi:{ref:xA,listAll:_A,getMetadata:wy,getBlob:IA,uploadBytes:AA,uploadBytesResumable:bA,deleteObject:Iy},getSnapshot:()=>BN(i),resetAll:()=>FN(i)}}function Ny(e,t,n,r){const s={uid:e};n!==void 0&&(s.token={...n}),t!==void 0&&(s.tenant=t);const i=Oi(s);if(i===null)throw new Error("projectIdentity requires a uid");const o={uid:i.uid,token:i.token??{}};return i.tenant!==void 0&&(o.tenant=i.tenant),o}const o0={transport:"in-process",order:80,tools:{auth_impersonate:"write",auth_reset:"write",auth_whoami:"read",auth_sessions:"read"}},a0={transport:"forwarded",order:70,tools:{auth_create_user:"write",auth_import_users:"write",auth_get_user:"read",auth_list_users:"read",auth_update_user:"write",auth_delete_user:"write",auth_set_claims:"write",auth_custom_token:"read"}},c0={transport:"in-process",order:90,tools:{sandbox_save_capture:"write",sandbox_list_captures:"read",sandbox_open_capture:"read",sandbox_rename_capture:"write",sandbox_delete_capture:"write"}},l0={transport:"in-process",order:60,tools:{pyric_can_i_use:"read"}},u0={transport:"forwarded",order:20,tools:{firestore_get_document:"read",firestore_list_documents:"read",firestore_create_document:"write",firestore_add_document:"write",firestore_update_document:"write",firestore_delete_document:"write",firestore_batch_write:"write",firestore_query_where:"read"}},d0={transport:"forwarded",order:30,tools:{sandbox_inspect:"read"}},f0={transport:"in-process",order:50,tools:{firestore_simulate_rules:"read",firestore_rules_stdlib_list:"read",firestore_rules_stdlib_get:"read",firestore_lint_rules:"read",firestore_resolve_modules:"read",rules_stdlib_list:"read",rules_stdlib_get:"read",rules_resolve_modules:"read"}},h0={transport:"forwarded",order:10,tools:{firestore_simulator_create:"write",firestore_simulator_execute:"write",firestore_simulator_read:"read",firestore_simulator_batch:"write",firestore_create_with_auto_id:"write",firestore_simulator_undo:"write",firestore_simulator_redo:"write",firestore_simulator_events:"read",firestore_simulator_transaction:"write"}},p0={transport:"forwarded",order:100,tools:{messaging_deliveries:"read"}},m0={transport:"forwarded",order:40,tools:{rtdb_simulate_access:"read",rtdb_crawl_structure:"read"}},y0=[{key:"auth-identity",...o0},{key:"auth-users",...a0},{key:"captures",...c0},{key:"conformance",...l0},{key:"firestore-data",...u0},{key:"firestore-inspect",...d0},{key:"firestore-rules",...f0},{key:"firestore-simulator",...h0},{key:"messaging-inspection",...p0},{key:"rtdb-inspection",...m0}];function Po(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 g0(e){return Po("key",e.map(t=>t.key)),Po("order",e.map(t=>t.order)),Po("tool name",e.flatMap(t=>Object.keys(t.tools))),[...e].sort((t,n)=>t.order-n.order)}const b0=g0(y0);function Ay(e){return b0.filter(t=>t.transport===e)}function w0(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,o)=>i!==s[o]))throw new Error(`${e} drifted from the default MCP contract
|
|
133
|
+
expected: ${n.join(", ")}
|
|
134
|
+
actual: ${t.join(", ")}`)}function v0(e){const t=e.detail??{};return{messageId:String(t.messageId),recipientId:String(t.recipientId??"sandbox-default"),receipt:"unconfirmed",acknowledgments:[],route:t.route,handled:t.handled===!0,at:e.at,payload:t.payload}}function x0(e,t){const n=e.filter(a=>a.kind==="service_mutation"&&a.service==="messaging"),r=new Map,s=(a,l)=>JSON.stringify([a,l]);for(const a of n){if(a.op!=="delivery_acknowledged")continue;const u=a.detail??{},d=s(u.messageId,u.recipientId),h=r.get(d)??[];h.push({observerId:String(u.observerId),stage:u.stage,at:a.at}),r.set(d,h)}const i=n.filter(a=>a.op==="message_delivered").map(a=>{const l=v0(a);l.acknowledgments=r.get(s(l.messageId,l.recipientId))??[];const u=l.acknowledgments.some(d=>d.stage==="received");return l.receipt=u?"received":"unconfirmed",l});return t===void 0?i:i.filter(a=>a.at>=t)}const Bd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",_0=142,Fd="APA91b",qd=22;function Vd(e){const t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let r=0;r<e;r++)n+=Bd[t[r]%Bd.length];return n}function S0(){const e=Vd(qd),t=_0-qd-1-Fd.length;return`${e}:${Fd}${Vd(t)}`}const k0="pyric-sandbox",E0="999999999999",or="sandbox-default",j0=null;class C0{projectId;senderId;sandbox;registrations=new Map;tokenRecords=new Map;subscriptions=new Map;clients=new Map;foregroundHandlers=new Map;backgroundHandlers=new Map;numericIdCounter=0;changeListeners=new Set;constructor(t={}){this.projectId=t.projectId??k0,this.senderId=t.senderId??E0,this.sandbox=t.sandbox}snapshot(){return{version:1,tokens:[...this.tokenRecords].map(([t,n])=>[t,{...n}]),topics:[...this.subscriptions].map(([t,n])=>[t,[...n]])}}restore(t){if(!rE(t))throw new Error("Invalid Messaging persistence snapshot.");this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear();for(const[n,r]of t.tokens)this.tokenRecords.set(n,{...r}),r.state==="active"&&this.registrations.set(r.registrationId,n);for(const[n,r]of t.topics)this.subscriptions.set(n,new Set(r))}reset(){this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear(),this.changed()}onChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}changed(){for(const t of this.changeListeners)t()}getTokenFor(t,n=or){const r=this.registrations.get(t);if(r!==void 0)return r;const s=S0();return this.registrations.set(t,s),this.tokenRecords.set(s,{registrationId:t,recipientId:n,state:"active"}),this.changed(),this.emit("token_minted",{path:s,detail:{registrationId:t}}),s}deleteTokenFor(t){const n=this.registrations.get(t);if(n===void 0)return!0;this.registrations.delete(t);const r=this.tokenRecords.get(n);return r!==void 0&&(r.state="unregistered"),this.changed(),this.emit("token_deleted",{path:n,detail:{registrationId:t}}),!0}tokenState(t){return this.tokenRecords.get(t)?.state??"unknown"}subscribeToTopic(t,n){return this.mutateSubscriptions(t,n,"subscribe")}unsubscribeFromTopic(t,n){return this.mutateSubscriptions(t,n,"unsubscribe")}mutateSubscriptions(t,n,r){if(!Li(n))throw new tt(Up());const s=Bc(n),i=this.subscriptions.get(s)??new Set;this.subscriptions.set(s,i);const o={successCount:0,failureCount:0,errors:[]};return t.forEach((a,l)=>{if(!Mi.test(a)){o.failureCount++,o.errors.push({index:l,reason:"invalid-token"});return}if(this.tokenState(a)==="unregistered"){o.failureCount++,o.errors.push({index:l,reason:"unregistered-token"});return}r==="subscribe"?i.add(a):i.delete(a),o.successCount++}),this.changed(),this.emit("subscription_changed",{path:s,detail:{action:r,tokenCount:t.length,successCount:o.successCount,failureCount:o.failureCount}}),o}topicsOf(t){const n=new Set;for(const[r,s]of this.subscriptions)s.has(t)&&n.add(r);return n}tokens(){const t=new Set(this.tokenRecords.keys());for(const n of this.subscriptions.values())for(const r of n)t.add(r);return[...t].sort().map(n=>({token:n,state:this.tokenState(n),topics:[...this.topicsOf(n)].sort()}))}send(t,n={}){const r=n.validateOnly===!0;let s;try{if(s=Zk(t),s.kind==="token"&&this.tokenState(s.token)!=="active")throw new tt(Kk())}catch(a){throw a instanceof tt&&this.emit("message_rejected",{detail:{status:a.envelope.status,errorStatus:a.envelope.error.status,errorCode:a.errorCode,message:a.envelope.error.message,validateOnly:r}}),a}const i=s.kind==="token"?crypto.randomUUID():this.mintNumericId(),o={name:`projects/${this.projectId}/messages/${i}`,messageId:i,target:s,validateOnly:r};if(this.emit("message_accepted",{path:I0(s),detail:{target:s.kind,name:o.name,messageId:i,validateOnly:r}}),!r){const a=this.toPayload(t,i);for(const l of this.matchingRecipients(s))this.route(a,l)}return o}mintNumericId(){return this.numericIdCounter=(this.numericIdCounter+1)%1e6,`${Date.now()}${String(this.numericIdCounter).padStart(6,"0")}`}matchingRecipients(t){const n=new Set;for(const[r,s]of this.tokenRecords){if(!(s.state==="active"))continue;let o;switch(t.kind){case"token":o=r===t.token;break;case"topic":o=this.subscriptions.get(t.topic)?.has(r)===!0;break;case"condition":o=R0(t.condition,this.topicsOf(r));break}o&&n.add(s.recipientId)}return n}toPayload(t,n){const r={from:this.senderId,messageId:n};if(t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0){const{title:s,body:i,imageUrl:o}=t.notification;r.notification={...s!==void 0?{title:s}:{},...i!==void 0?{body:i}:{},...o!==void 0?{image:o}:{}}}return r}setClientVisibility(t,n,r=or){this.clients.set(t,{state:n,recipientId:r})}removeClient(t){this.clients.delete(t)}onForegroundMessage(t,n=or){return this.foregroundHandlers.set(t,n),()=>this.foregroundHandlers.delete(t)}onBackgroundMessage(t,n=or){return this.backgroundHandlers.set(t,n),()=>this.backgroundHandlers.delete(t)}deliver(t,n=or){const r={from:t.from??this.senderId,messageId:t.messageId??crypto.randomUUID()};return t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0&&(r.notification={...t.notification}),this.route(r,n)}route(t,n){let r=!1;for(const a of this.clients.values())if(a.recipientId===n&&a.state==="visible"){r=!0;break}const s=r?"foreground":"background",i=s==="foreground"?this.foregroundHandlers:this.backgroundHandlers;this.emit("delivery_routed",{detail:{route:s,recipientId:n,visibleClient:r,messageId:t.messageId}});let o=0;for(const[a,l]of[...i])if(l===n){o++;try{a(structuredClone(t))}catch{}}return this.emit("message_delivered",{detail:{recipientId:n,route:s,handlerCount:o,handled:o>0,messageId:t.messageId,payload:structuredClone(t)}}),{route:s,handlerCount:o,payload:t}}acknowledge(t,n,r,s){this.emit("delivery_acknowledged",{detail:{messageId:t,recipientId:n,observerId:r,stage:s}})}deliveries(t){return x0(this.sandbox?.history()??[],t)}emit(t,n){if(this.sandbox!==void 0)try{pt(this.sandbox,qn({at:Te(this.sandbox).now(),service:"messaging",op:t,auth:j0,...n}),{service:"messaging"})}catch{}}}function I0(e){return e.kind==="token"?e.token:e.kind==="topic"?e.topic:e.condition}function R0(e,t){const n=e;let r=0;function s(){for(;r<n.length&&/\s/.test(n[r]);)r++}function i(l){return s(),n.startsWith(l,r)?(r+=l.length,!0):!1}function o(){if(s(),i("!"))return!o();if(i("(")){const d=a();return i(")"),d}s(),r++;const l=r;for(;r<n.length&&n[r]!=="'";)r++;const u=n.slice(l,r);return r++,i("in"),i("topics"),t.has(u)}function a(){let l=o();for(;;){if(s(),i("&&")){const u=o();l=l&&u;continue}if(i("||")){const u=o();l=l||u;continue}return l}}return a()}const Wd=new WeakMap;function N0(e,t){const n=Wd.get(e);if(n!==void 0)return n;const r=new C0({...t,sandbox:e});return Wd.set(e,r),e.registerPersistableService("messaging",{snapshot:()=>r.snapshot(),restore:s=>r.restore(s),reset:()=>r.reset(),subscribe:s=>r.onChange(s)}),r}function A0(e){return[{name:"messaging_deliveries",description:"Inspect message routing and browser-reported receipt, callback and native display outcomes. handled only means a broker handler ran; display-accepted is not proof of OS visibility. Missing receipt is unconfirmed.",parameters:{type:"object",properties:{}},async execute(){const t=await e(),n=N0(t).deliveries();return{ok:!0,summary:`${n.length} deliveries`,data:{deliveries:n}}}}]}class Va extends Error{issues;constructor(t,n){super(t),this.name="RulesCompileError",this.issues=n}}function O0(e){const t=e.severity==="critical"||e.severity==="high"?"error":e.severity==="medium"?"warning":"info";return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}function $0(e){return{...O0(e),rule:e.rule,fix:e.fix}}const P0=new Set(["PARSE_ERROR","COMPILE_ERROR"]);function zd(e,t){const n=t==="warning"?"lint":P0.has(e.code)?"parse":"validate",r={code:e.code,severity:t,message:e.message,path:e.path,origin:n};return e.rule!=="ruleset"&&(r.rule=e.rule),r}const D0="/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/",T0=new Set(["d","D","w","W","s","S"]),M0=new Set(["*","+","?","}"]);function L0(e){const t=cp(e);if(t!==null)return`RTDB refuses it at deploy (${t})`;let n=!1,r=0;for(let s=0;s<e.length;s++){const i=e[s],o=e[s+1];if(i==="\\"&&o!==void 0){const a=F0(o);if(a!==null)return a;s++}else if(n)n=i!=="]";else if(i==="["){if(B0(e,s+1))return"RTDB reads a ] right after [ or [^ as a member of the set";n=!0}else{if(i==="("&&o==="?")return"RTDB reads (? as a literal ?, so lookarounds and (?: groups never match as in JavaScript";if(M0.has(i)&&o==="?")return"RTDB has no lazy quantifier and reads +? as an optional +";if(i==="(")r++;else if(i===")")r--;else{if(i==="|"&&U0(e,s))return"RTDB reads the | of an empty alternative, as in (|a) or a||b, as a literal |";if(i==="|"&&r===0)return"RTDB applies ^, $ and the implied .* to the first and last alternatives only; wrap the alternation in a group"}}}return null}function U0(e,t){const n=e[t-1],r=e[t+1];return n==="("&&e[t-2]!=="\\"||r==="|"||r===")"}function B0(e,t){const n=e[t]==="^"?t+1:t;return e[n]==="]"}function F0(e){return!/^[A-Za-z0-9]$/.test(e)||T0.has(e)?null:e==="b"||e==="B"?`RTDB reads \\${e} as the letter ${e}, not a word boundary`:/^[1-9]$/.test(e)?`RTDB reads \\${e} as the digit ${e}, not a backreference`:`RTDB reads the escape \\${e} as the letter ${e}`}function Oy(e,t){if(!(e instanceof Pl)){const l=e?.constructor?.name??typeof e;throw new Error(`Unsupported Zod schema for RTDB rules: expected ZodObject, got ${l}`)}const n=e._def;if(n.catchall&&!(n.catchall instanceof ov))throw new Error("Unsupported Zod object catchall for RTDB rules");const r=e.shape;if(t){for(const l of Object.keys(t))if(!(l in r))throw new Error(`fieldConstraints: field "${l}" is not in schema.`)}const s=[],i={};for(const[l,u]of Object.entries(r)){Gh("schemaRules",l);const d=u,h=d instanceof av,f=h?d.unwrap():d;h||s.push(l);const p=t?.[l];if(f instanceof Pl){const m=Oy(f);let g=m.validate;p&&p.length>0&&(g=$n(m.validate,...p)),i[l]={validate:g,children:m.children}}else{const m=$y(f,l);p&&p.length>0?i[l]={validate:$n(m,...p)}:i[l]={validate:m}}}n?.unknownKeys==="strict"&&(i.$other={validate:ie("false")});const o=[m_()];for(const l of s)o.push(y_(l));return{validate:$n(...o),children:i}}function q0(e,t){const n=[ie("newData.isString()")];for(const r of e._def.checks)if(r.kind==="min")n.push(ie(`newData.val().length >= ${Ye(r.value)}`));else if(r.kind==="max")n.push(ie(`newData.val().length <= ${Ye(r.value)}`));else if(r.kind==="length")n.push(ie(`newData.val().length == ${Ye(r.value)}`));else if(r.kind==="regex"){const s=r.regex;if(!Ic(s.flags))throw new Error(`Unsupported Zod regex flags "${s.flags}" on field "${t}"; RTDB rules only support the "i" flag`);if(/[\r\n]/.test(s.source))throw new Error(`Unsupported Zod regex with newline on field "${t}"`);const i=L0(s.source);if(i!==null)throw new Error(`Unsupported Zod regex on field "${t}": ${i}`);n.push(ie(`newData.val().matches(/${s.source}/${s.flags})`))}else if(r.kind==="email")n.push(ie(`newData.val().matches(${D0})`));else if(r.kind==="startsWith")n.push(ie(`newData.val().beginsWith(${Ye(r.value)})`));else if(r.kind==="endsWith")n.push(ie(`newData.val().endsWith(${Ye(r.value)})`));else if(r.kind==="includes")n.push(ie(`newData.val().contains(${Ye(r.value)})`));else throw new Error(`Unsupported Zod string check "${String(r.kind)}" for RTDB rules on field "${t}"`);return $n(...n)}function V0(e,t){const n=[ie("newData.isNumber()")];for(const r of e._def.checks)if(r.kind==="min"){const s=r.inclusive===!1?">":">=";n.push(ie(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="max"){const s=r.inclusive===!1?"<":"<=";n.push(ie(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="int")n.push(ie("newData.val() % 1 == 0"));else if(r.kind==="multipleOf")n.push(ie(`newData.val() % ${Ye(r.value)} == 0`));else throw new Error(`Unsupported Zod number check "${String(r.kind)}" for RTDB rules on field "${t}"`);return $n(...n)}function $y(e,t){if(e instanceof cv)return q0(e,t);if(e instanceof lv)return V0(e,t);if(e instanceof uv)return ie("newData.isBoolean()");if(e instanceof dv){const n=e.options;return Vl(...n.map(r=>ie(`newData.val() == ${Ye(r)}`)))}if(e instanceof fv){const n=e.value;return ie(`newData.val() == ${Ye(n)}`)}if(e instanceof hv){const n=e._def.options;return Vl(...n.map(r=>$y(r,t)))}throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function W0(e){let t;if(typeof e=="function"){const s=[];e({path:(i,o)=>s.push([i,o])}),t=s}else t=Object.entries(e);const n=sl(t);X0(n),n.sort((s,i)=>{const o=Hd(s[0]),a=Hd(i[0]);return o-a||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&z0(r,s);for(const[s,i]of n){const o=il(r,s);o&&J0(r,o,i,s)}return r}function z0(e,t){const n=t.split("/").filter(Boolean);let r=e;for(let s=0;s<n.length;s++){const i="/"+n.slice(0,s+1).join("/"),o=n.slice(0,s+1).filter(l=>l.startsWith("$"));let a=r.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},r.children.push(a)),r=a}}function Wa(e,t,n){const r=e.validate?$n(ie(e.validate.raw),t):t;e.validate=za(r,"validate",n)}function Py(e,t,n){for(const[r,s]of Object.entries(t)){const i=Dy(`${e.path}/${r}`),o=r.startsWith("$")?[...n,r]:n;let a=e.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},e.children.push(a)),Wa(a,s.validate,o),s.children&&Py(a,s.children,o)}}const H0={read:0,write:0,validate:0,schema:0,fieldConstraints:0,indexOn:0,children:0},Do=Object.keys(H0);function K0(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`The rules for "${e}" must be a path definition object, got ${JSON.stringify(t)}.`);for(const n of Object.keys(t)){if(Do.includes(n))continue;const r=Mv(n,Do),s=r===null?`; the keys are ${Do.map(i=>`'${i}'`).join(", ")}.`:`; did you mean '${r}'?`;throw new Error(`Unknown key '${n}' in the rules for "${e}"${s}`)}}function G0(e){sl(Object.entries(e))}function To(e,t,n){if(n!==void 0){if(typeof n=="boolean")return ie(String(n));if(typeof n=="string"&&n.trim().length>0)return n;throw new Error(`The ${t} rule for "${e}" must be a non-empty expression or a boolean, got ${JSON.stringify(n)}.`)}}function J0(e,t,n,r){const s=r.split("/").filter(Boolean),i=s.filter(u=>u.startsWith("$"));if(n.fieldConstraints&&!n.schema)throw new Error(`fieldConstraints on "${r}" requires a schema.`);const o=To(r,"read",n.read),a=To(r,"write",n.write),l=To(r,"validate",n.validate);if(o!==void 0&&(t.read=za(o,"read",i)),a!==void 0&&(t.write=za(a,"write",i)),l!==void 0&&Wa(t,l,i),n.schema){const u=Oy(n.schema,n.fieldConstraints);Wa(t,u.validate,i),Py(t,u.children,i)}if(n.indexOn){const u=Y0(e,t,s);if(u){if(!u.indexOn)u.indexOn=[...n.indexOn];else if(!Q0(u.indexOn,n.indexOn))throw new Error(`Conflicting indexOn declarations for "${u.path}": ${JSON.stringify(u.indexOn)} vs ${JSON.stringify(n.indexOn)}`)}}}function Y0(e,t,n){if(n[n.length-1]?.startsWith("$")){const s="/"+n.slice(0,-1).join("/");return il(e,s)}return t}function Q0(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Dy(e){return"/"+e.split("/").filter(Boolean).join("/")}function Hd(e){return e.split("/").filter(Boolean).length}function X0(e){const t=new Set;for(const[n]of e){if(t.has(n))throw new Error(`Duplicate ruleset path declaration for "${n}"`);t.add(n)}}function sl(e){const t=[];for(const[n,r]of e){const s=Dy(n),i=typeof r=="boolean"?{validate:ie(String(r))}:r;K0(s,i);const{children:o,...a}=i;if(t.push([s,a]),o){const l=Object.entries(o).map(([u,d])=>[`${s}/${u}`,d]);t.push(...sl(l))}}return t}function za(e,t,n){return Op(String(e),t,n)}function il(e,t){if(e.path===t)return e;for(const n of e.children){const r=il(n,t);if(r)return r}return null}function Z0(e){if(e==null)return null;if(typeof e=="string")return{uid:e,token:{}};const t={uid:e.uid,token:e.token??{}};return e.tenant!==void 0&&(t.tenant=e.tenant),t}function eO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.__type==="serverTimestamp"}function ki(e){if(eO(e))return{".sv":"timestamp"};if(Array.isArray(e))return e.map(ki);if(typeof e=="object"&&e!==null){const t={};for(const[n,r]of Object.entries(e))Object.defineProperty(t,n,{value:ki(r),enumerable:!0,writable:!0,configurable:!0});return t}return e}function Ty(e){const t={operation:e.operation,path:e.path,auth:Z0(e.auth),mockData:e.mockData??e.data??{}};return e.newData!==void 0&&(t.newData=ki(e.newData)),e.now!==void 0&&(t.now=e.now),e.updates!==void 0&&(t.updates=e.updates.map(n=>({path:n.path,value:ki(n.value)}))),e.query!==void 0&&(t.query=e.query),t}function Mo(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Ha(e,t){const n=[...Mo(e.path,".read",e.read,t),...Mo(e.path,".write",e.write,t),...Mo(e.path,".validate",e.validate,t),...(e.structure??[]).filter(r=>r.severity===(t==="errors"?"error":"warning")).map(r=>({path:r.path,rule:"ruleset",code:r.code,message:r.message}))];for(const r of e.children)n.push(...Ha(r,t));return n}function My(e){let t;try{t=e()}catch(s){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:s instanceof Error?s.message:String(s)}],warnings:[]}}const n=Ha(t,"errors"),r=Ha(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}function Ly(e){const t={};e.read&&(t[".read"]=e.read.raw),e.write&&(t[".write"]=e.write.raw),e.validate&&(t[".validate"]=e.validate.raw),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const r of e.children){const s=r.path.slice(r.path.lastIndexOf("/")+1);t[s]={},Ly(r)}const n=Kh(e.path,t);return n.length>0&&(e.structure=n),e}class tO{definition;compiled;constructor(t){this.definition=t}compile(){return this.compiled??=Ly(W0(this.definition.paths)),this.compiled}toJSON(){return ak(this.compile())}check(){return My(()=>this.compile())}simulate(t){return Tc(this.compile(),Ty(t))}}function nO(e){return typeof e.paths=="object"&&e.paths!==null&&G0(e.paths),new tO(e)}function Ei(e){return e.split("/").filter(Boolean)}function Ka(e){return`/${Ei(e).join("/")}`}function rO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sO(e){if(typeof e!="object"||e===null)return!1;const t=e.path;return typeof t=="string"&&t.length>0&&t.startsWith("/")}function Uy(e){const t=e.map(Ka),n=t.find((r,s)=>t.indexOf(r)!==s);return n!==void 0?`update failed: values argument contains a path ${n} that is ancestor of another path ${n}`:Dr(()=>Mk(Object.fromEntries(e.map(r=>[r,null])),Ei))}function iO(e){if(e.operation==="read")return null;const t=e.operation==="update"?"update":"set";return Dr(()=>Pk(t,e.path))}function oO(e){return e.query===void 0?null:e.operation!=="read"?`a query applies to a 'read' case, and this case is '${e.operation}'.`:kp(e.query)}function aO(e){if(e.updates===void 0)return null;if(e.operation!=="write"&&e.operation!=="validate")return`'updates' applies to a 'write' or 'validate' case, and this case is '${e.operation}'.`;const t=e.updates;if(!Array.isArray(t))return"'updates' must be an array of { path, value } entries.";if(!t.every(sO))return"each 'updates' entry needs an absolute 'path' starting with '/'.";const n=Uy(t.map(s=>s.path));if(n!==null)return n;const r=t.find(s=>Ka(s.path)===Ka(e.path));return r===void 0?`'updates' must list the case's path '${e.path}': the case evaluates that path's rules as one of the paths written. Use an 'update' case for the verdict on the whole update.`:e.newData!==void 0&&!Ea(e.newData,r.value)?`newData differs from the value 'updates' writes at '${e.path}'. Give one value, or omit newData.`:null}function cO(e){if(e.operation!=="update")return null;if(!rO(e.newData))return"an 'update' case needs newData to be an object keyed by the paths it writes.";const t=Object.keys(e.newData);return t.length===0?"an 'update' case needs newData to name at least one path.":Uy(t)}function lO(e){const t=e.path;return typeof t!="string"?"a case needs 'path' to be a string, such as '/users/alice'.":Dr(()=>Lk(t,!1))??iO(e)??oO(e)??aO(e)??cO(e)}function ol(e){return{success:!1,error:{code:"INVALID_INPUT",message:e,recoverable:!0}}}function uO(e){return`/${e.join("/")}`}function By(e){const t={operation:e.operation==="update"?"write":e.operation,path:e.path,auth:e.auth??null};return e.data!==void 0&&(t.data=e.data),e.newData!==void 0&&(t.newData=e.newData),e.now!==void 0&&(t.now=e.now),t}function dO(e,t){const n=Ei(t.path),r=Object.entries(t.newData).map(([u,d])=>({path:uO([...n,...Ei(u)]),value:d}));let s,i;const o=[];let a=[];for(const u of r){const d=By(t);d.path=u.path,d.newData=u.value,d.updates=r;const h=e.simulate(d);if(!h.success)return h;const f=h.data.trace.filter(m=>m.kind==="write"),p=h.data.trace.filter(m=>m.kind==="validate");if(o.push(...f),!h.data.allowed||h.data.unsupported===!0){if(p.length===0)return{success:!0,data:{...h.data,trace:o}};i??={result:h,validates:p};continue}a=p,s??=h}return i?{success:!0,data:{...i.result.data,trace:[...o,...i.validates]}}:{success:!0,data:{...s.data,trace:[...o,...a]}}}function fO(e,t){const n=lO(t);if(n!==null)return ol(n);if(t.operation==="update")return dO(e,t);const r=By(t);return t.query!==void 0&&(r.query={...t.query}),t.updates!==void 0&&(r.updates=t.updates),e.simulate(r)}function Ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hO(e){if(!Ga(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]==="instances"&&Ga(e.instances)}function Kd(e,t,n){if(typeof e!="string")return{problem:'instance must be a string naming a database instance, such as "my-app-default-rtdb".'};try{const r=V_(e)?.name;return{name:r===void 0||gp(r,n)?t:r}}catch(r){const s=r instanceof Error?r.message.trim():String(r);return{problem:`"${e}" is not a database instance name: ${s}`}}}function Ja(e){return[...e].map(t=>`"${t}"`).join(", ")}function Fy(e,t,n){if(e.kind==="every-instance")return e.rules;const r=e.instances.get(t);if(r!==void 0)return r;const s=e.instances.size===0?"it declares no instances":`it holds rules for ${Ja(e.instances.keys())}`;return{problem:`this ruleset has no rules for ${n?`database instance "${t}"`:`the default instance "${t}"`}; ${s}.`}}function pO(e,t){const n=e.kind==="per-instance",r=n?e.defaultInstance:mp,s=n?e.projectId:void 0;let i;if(t.instance!==void 0){const d=Kd(t.instance,r,s);if("problem"in d)return d;i=d.name}else n&&(i=r);const o=d=>i===void 0?d:{...d,instance:i},a=Fy(e,i??r,t.instance!==void 0);if("problem"in a)return o(a);const l={...t};if(i!==void 0&&hO(t.data)){const d=new Map;for(const[f,p]of Object.entries(t.data.instances)){const m=Kd(f,r,s);if("problem"in m)return o({problem:`data.instances: ${m.problem}`});if(!Ga(p))return o({problem:`data.instances["${f}"] must be an object: the tree of database instance "${m.name}".`});if(d.has(m.name))return o({problem:`data.instances names database instance "${m.name}" more than once (key "${f}" repeats an earlier key); name each instance once, so the verdict does not depend on key order.`});d.set(m.name,p)}if(e.kind==="per-instance"){const f=[...d.keys()].filter(p=>!e.instances.has(p));if(f.length>0)return o({problem:`data.instances names ${Ja(f)}, which this ruleset does not declare; it holds rules for ${Ja(e.instances.keys())}.`})}const h=d.get(i);h===void 0?delete l.data:l.data=h}return o({rules:a,evaluated:l})}const rn="rtdbRules.fromFirebaseJson";function mO(){const e=globalThis.process?.getBuiltinModule,t=typeof e=="function"?e.call(process,"node:fs"):void 0,n=typeof e=="function"?e.call(process,"node:path"):void 0;if(t===void 0||n===void 0)throw new Error(`${rn} reads files, which needs Node.js 20.16 or later, Bun or Deno. Without a file system, pass each instance's rules text to rtdbRules.`);return{fs:t,path:n}}function Lo(e,t){try{return e.readFileSync(t,"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}}function Gd(e,t){try{return JSON.parse(e)}catch(n){throw new Error(`${rn}: ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function yO(e,t={}){const{fs:n,path:r}=mO(),s=r.resolve(e),i=r.dirname(s),o=Lo(n,s);if(o===null)throw new Error(`${rn}: there is no firebase.json at ${s}.`);const a=Gd(o,s);let l;const u=()=>{if(l!==void 0)return l;const m=r.resolve(i,".firebaserc"),g=Lo(n,m);return l=g===null?null:Gd(g,m),l};let d=t.projectId===""?void 0:t.projectId;if(d===void 0){const m=u()?.projects?.default;typeof m=="string"&&m!==""&&(d=m)}let h;try{h=aE(a?.database,{...d===void 0?{}:{projectId:d},targetInstances:m=>d===void 0?void 0:u()?.targets?.[d]?.database?.[m],resolveFile:m=>r.resolve(i,m)})}catch(m){throw new Error(`${rn}: ${m instanceof Error?m.message:String(m)}`)}const[f]=h.unresolved;if(f!==void 0){const m=d===void 0?"no project id is set: pass { projectId } or set projects.default in .firebaserc":`.firebaserc maps it to no instance for project "${d}" (firebase target:apply database ${f.target} <instance>)`;throw new Error(`${rn}: ${f.label} deploys to target "${f.target}", and ${m}.`)}const p=new Map;for(const m of h.targets){const g=p.get(m.file);if(g!==void 0){g.instances.push(m.instance);continue}const b=Lo(n,m.file);if(!(b===null&&!m.configured)){if(b===null)throw new Error(`${rn}: ${m.file} does not exist, and ${m.label} deploys it to database instance "${m.instance}".`);p.set(m.file,{file:m.configuredFile,path:m.file,text:b,instances:[m.instance]})}}if(p.size===0)throw new Error(`${rn}: ${s} deploys no Realtime Database rules.`);return{defaultInstance:h.defaultInstance,...d===void 0?{}:{projectId:d},files:[...p.values()]}}class qy{text;pos=0;line=1;lineStart=0;constructor(t){this.text=t}parseDocument(){try{this.skipTrivia();const t=this.parseValue();return this.skipTrivia(),this.pos<this.text.length?void 0:t}catch{return}}newline(){this.line++,this.lineStart=this.pos}skipTrivia(){const t=this.text;for(;this.pos<t.length;){const n=t[this.pos];if(n===`
|
|
135
|
+
`)this.pos++,this.newline();else if(n==="\r")this.pos++,t[this.pos]===`
|
|
136
|
+
`&&this.pos++,this.newline();else if(n===" "||n===" "||n==="\uFEFF")this.pos++;else if(n==="/"&&t[this.pos+1]==="/")for(;this.pos<t.length&&t[this.pos]!==`
|
|
137
|
+
`&&t[this.pos]!=="\r";)this.pos++;else if(n==="/"&&t[this.pos+1]==="*")for(this.pos+=2;;){if(this.pos>=t.length)throw new Error("unterminated comment");const r=t[this.pos];if(r==="*"&&t[this.pos+1]==="/"){this.pos+=2;break}this.pos++,r===`
|
|
138
|
+
`?this.newline():r==="\r"&&(t[this.pos]===`
|
|
139
|
+
`&&this.pos++,this.newline())}else return}}parseValue(){const t=this.text[this.pos];return t==="{"?this.parseObject():t==="["?(this.parseArray(),null):t==='"'?(this.parseString(),null):(this.parseLiteral(),null)}parseObject(){const t=new Map;if(this.pos++,this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t;for(;;){if(this.skipTrivia(),this.text[this.pos]!=='"')throw new Error("expected key");const n={line:this.line,column:this.pos-this.lineStart+1},r=this.parseString();if(this.skipTrivia(),this.text[this.pos]!==":")throw new Error("expected colon");this.pos++,this.skipTrivia();const s=this.parseValue();t.set(r,{location:n,value:s}),this.skipTrivia();const i=this.text[this.pos++];if(i==="}")return t;if(i!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t}}parseArray(){if(this.pos++,this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}for(;;){this.skipTrivia(),this.parseValue(),this.skipTrivia();const t=this.text[this.pos++];if(t==="]")return;if(t!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}}}parseString(){const t=this.text,n=this.pos;for(this.pos++;;){if(this.pos>=t.length)throw new Error("unterminated string");const s=t[this.pos];if(s==="\\"){if(this.pos+1>=t.length||t.charCodeAt(this.pos+1)<32)throw new Error("invalid escape");this.pos+=2}else if(s==='"'){this.pos++;break}else s===`
|
|
140
|
+
`?(this.pos++,this.newline()):s==="\r"?(this.pos++,t[this.pos]===`
|
|
141
|
+
`&&this.pos++,this.newline()):this.pos++}const r=t.slice(n,this.pos).replace(/[\u0000-\u001f]/g,s=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`);return JSON.parse(r)}parseLiteral(){const t=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(this.text.slice(this.pos,this.pos+64));if(!t)throw new Error("unexpected token");this.pos+=t[0].length}}function Vy(e,t,n){let r=e.get("rules")?.value??null;for(const s of t.split("/").filter(i=>i.length>0))r=r?.get(s)?.value??null;return r?.get(n)?.location??null}function gO(e,t,n){const r=new qy(e).parseDocument();return r?Vy(r,t,n):null}function Wy(e,t){const n=new qy(e).parseDocument();return t.map(r=>{const s=n?Vy(n,r.path,`.${r.kind}`):null;return s?{...r,line:s.line}:{...r}})}const Jd=["read","write","validate","indexOn"];function Uo(e,t){return`${e}\0${t}`}function bO(e){const t=["allow","deny","error"].filter(n=>e[n]>0);return t.length>1?"mixed":t.length===1?t[0]:e.unsupported>0?"unsupported":"never-evaluated"}class wO{compiled;rows=new Map;missing=new Map;constructor(t){this.compiled=t,this.collect(t)}collect(t){for(const n of Jd){let r;n==="indexOn"?t.indexOn!==void 0&&(r=JSON.stringify(t.indexOn)):r=t[n]?.raw,r!==void 0&&this.rows.set(Uo(t.path,n),{path:t.path,kind:n,expression:r,counts:{allow:0,deny:0,error:0,unsupported:0}})}for(const n of t.children)this.collect(n)}record(t){for(const n of t??[]){const r=this.rows.get(Uo(n.path,n.kind));r!==void 0&&(n.verdict==="ALLOW"?r.counts.allow++:n.verdict==="DENY"?r.counts.deny++:n.verdict==="ERROR"?r.counts.error++:r.counts.unsupported++)}}recordQuery(t,n){if(n===void 0)return;let r=null;if(n.orderByValue===!0)r=".value";else if(typeof n.orderByChild=="string"){const o=n.orderByChild.split("/").filter(Boolean).join("/");o!==""&&(r=o)}if(r===null)return;const s=t.split("/").filter(Boolean),i=Dp(this.compiled,s,r);for(const o of i){const a=this.rows.get(Uo(o.path,"indexOn"));a!==void 0&&a.counts.allow++}if(i.length===0){const o=`/${s.join("/")}`;this.missing.set(`${o}\0${r}`,{path:o,index:r})}}summarize(t={}){const n=[];for(const a of this.rows.values()){const{allow:l,deny:u,error:d,unsupported:h}=a.counts,f={path:a.path,kind:a.kind,expression:a.expression,evaluated:l+u+d,allow:l,deny:u,error:d,unsupported:h,status:bO(a.counts)};n.push(f)}const r=t.source===void 0?n:Wy(t.source,n),s=Object.fromEntries(Jd.map(a=>[a,{total:0,covered:0,unsupported:0}]));let i=0,o=0;for(const a of r)s[a.kind].total++,a.evaluated>0?(s[a.kind].covered++,i++):a.status==="unsupported"&&(s[a.kind].unsupported++,o++);return{rules:r,uncovered:r.filter(a=>a.status==="never-evaluated").map(a=>`${a.path} .${a.kind}`),missingIndexes:[...this.missing.values()],files:[{file:t.file??null,total:r.length,covered:i,neverEvaluated:r.filter(a=>a.status==="never-evaluated").length,unsupported:o,byKind:s}]}}}function vO(e){const t={rules:[],uncovered:[],missingIndexes:[],files:[]};for(const n of e){const r=n.files[0]?.file??"rules";t.rules.push(...n.rules.map(s=>({file:r,...s}))),t.uncovered.push(...n.uncovered.map(s=>`${r} ${s}`)),t.missingIndexes.push(...n.missingIndexes.map(s=>({...s,file:r}))),t.files.push(...n.files)}return t}const Gr=Symbol("non-null"),xO=/^auth(\s*\.\s*token)?$/;function _O(e,t){if(t!=="any"){if(e.startsWith("$"))return Gr;if(e==="auth")return t==="signed-out"?null:Gr}}function SO(e,t,n){if(xO.test(e.sourceString))return n==="signed-out"?null:n==="signed-in"&&t==="uid"&&e.sourceString==="auth"?Gr:void 0}const kO=new Set(["exists","isString","isNumber","isBoolean","hasChild","hasChildren"]);function Dn(e){return e===!1||e==="exists-false"||e==="delete-guard"}function Yd(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function EO(e){const t=e.newDataRelPath();return t!==void 0&&t.length===0}function Qd(e,t,n){const r=this.args.acc;(e.newDataRelPath()?.join("/")===".val()"&&n.constIn("any")===null||n.newDataRelPath()?.join("/")===".val()"&&e.constIn("any")===null)&&r.newDataExistsCalls++,e.collect(r),n.collect(r)}function js(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(typeof s!="number"||typeof i!="number")return;const o=e(s,i);return o!==void 0&&Number.isFinite(o)?o:void 0}}function Cs(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(typeof s=="number"&&typeof i=="number"||typeof s=="string"&&typeof i=="string")return e===">"?s>i:e===">="?s>=i:e==="<"?s<i:s<=i}}function Is(e){return function(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);if(!(s===void 0||i===void 0))return s===Gr||i===Gr?s!==null&&i!==null?void 0:!e:e?s===i:s!==i}}function Rs(e,t,n){const r=this.args.relSegments;return e.evalOnDelete(r)===null||n.evalOnDelete(r)===null?!1:this.constIn("any")}function Xd(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);if(s===null&&i===null&&e.constIn("any")===null!=(n.constIn("any")===null))return"delete-guard";if(s!==void 0&&i!==void 0)return s===i;if(s===null&&e.constIn("any")!==null||i===null&&n.constIn("any")!==null)return!1}function Zd(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);return s!==void 0&&i!==void 0?s!==i:void 0}function Ns(e,t,n,r){let s=n(e);for(const i of t.children)s=r(s,()=>n(i));return s}function jO(e,t){if(e===!1)return!1;if(e!==!0)return;const n=t();return typeof n=="boolean"?n:void 0}function CO(e,t){if(e===!0)return!0;if(e!==!1)return;const n=t();return typeof n=="boolean"?n:void 0}function IO(e,t){const n=t();return e===!1||e==="exists-false"||n===!1||n==="exists-false"?!1:e==="delete-guard"||n==="delete-guard"?"delete-guard":e===!0&&n===!0?!0:void 0}function RO(e,t){if(e===!0)return!0;const n=t();return Dn(e)&&Dn(n)?e==="delete-guard"||n==="delete-guard"?"delete-guard":!1:Dn(e)&&n===!0?!0:void 0}let Bo;function NO(){if(Bo)return Bo;const e=os();return e.addOperation("newDataRelPath",{_nonterminal(...t){return t.length===1?t[0].newDataRelPath():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.newDataRelPath()},ident(t,n,r){return this.sourceString==="newData"?[]:void 0},CallExpr_methodCall(t,n,r,s,i,o){const a=t.newDataRelPath();if(a===void 0||a[0]===".val()")return;const l=r.sourceString;if(l==="val"&&a.length===0&&i.asIteration().children.length===0)return[".val()"];if(l==="child"){const u=i.asIteration().children,d=u.length===1?u[0].constIn("any"):void 0;return typeof d=="string"?[...a,...d.split("/").filter(Boolean)]:void 0}return l==="parent"&&a.length>0?a.slice(0,-1):void 0}}),e.addOperation("collect(acc)",{_nonterminal(...t){t.forEach(n=>n.collect(this.args.acc))},_iter(...t){t.forEach(n=>n.collect(this.args.acc))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.acc;if(EO(t)){const l=r.sourceString;l==="exists"&&a.newDataExistsCalls++,l==="parent"&&a.newDataEscapes++,(l==="hasChild"||l==="child")&&(a.checksNamedChildren=!0),l==="hasChildren"&&i.asIteration().children.length>0&&(a.checksNamedChildren=!0)}t.collect(a),i.asIteration().children.forEach(l=>l.collect(a))},Equality_strictNeq:Qd,Equality_looseNeq:Qd,CallExpr_memberAccess(t,n,r){t.collect(this.args.acc)},ident(t,n,r){const s=this.args.acc,i=this.sourceString;i==="auth"?s.readsAuth=!0:i==="data"?s.readsData=!0:i==="root"?s.readsRoot=!0:i==="newData"&&s.newDataReads++}}),e.addOperation("constIn(world)",{_nonterminal(...t){return t.length===1?t[0].constIn(this.args.world):void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.constIn(this.args.world)},ident(t,n,r){return _O(this.sourceString,this.args.world)},CallExpr_memberAccess(t,n,r){return SO(t,r.sourceString,this.args.world)},bool_true(t){return!0},bool_false(t){return!1},null(t){return null},number(t){const n=Number(this.sourceString);return Number.isFinite(n)?n:void 0},string_single(t,n,r){return Or(this.sourceString)?void 0:$r(this.sourceString)},string_double(t,n,r){return Or(this.sourceString)?void 0:$r(this.sourceString)},UnaryExpr_not(t,n){const r=n.constIn(this.args.world);return typeof r=="boolean"?!r:void 0},UnaryExpr_neg(t,n){const r=n.constIn(this.args.world);return typeof r=="number"&&Number.isFinite(-r)?-r:void 0},Multiplicative_mul:js((t,n)=>t*n),Multiplicative_div:js((t,n)=>n===0?void 0:t/n),Multiplicative_mod:js((t,n)=>n===0?void 0:t%n),Additive_sub:js((t,n)=>t-n),Additive_add(t,n,r){const s=t.constIn(this.args.world),i=r.constIn(this.args.world);return typeof s=="number"&&typeof i=="number"?Number.isFinite(s+i)?s+i:void 0:typeof s=="string"&&typeof i=="string"?s+i:void 0},Comparison_gt:Cs(">"),Comparison_gte:Cs(">="),Comparison_lt:Cs("<"),Comparison_lte:Cs("<="),Equality_strictEq:Is(!0),Equality_looseEq:Is(!0),Equality_strictNeq:Is(!1),Equality_looseNeq:Is(!1),LogicalAnd_and(t,n,r){return Ns(t,r,s=>s.constIn(this.args.world),jO)},LogicalOr_or(t,n,r){return Ns(t,r,s=>s.constIn(this.args.world),CO)},Ternary_ternary(t,n,r,s,i){const o=t.constIn(this.args.world);if(o===!0)return r.constIn(this.args.world);if(o===!1)return i.constIn(this.args.world)}}),e.addOperation("constant(world)",{_nonterminal(){const t=this.constIn(this.args.world);return typeof t=="boolean"?t:void 0},_iter(){},_terminal(){}}),e.addOperation("evalOnDelete(relSegments)",{_nonterminal(...t){const n=this.constIn("any");return n!==void 0?n:t.length===1?t[0].evalOnDelete(this.args.relSegments):void 0},_iter(){},_terminal(){return this.constIn("any")},Primary_paren(t,n,r){return n.evalOnDelete(this.args.relSegments)},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.relSegments,l=t.newDataRelPath(),u=r.sourceString;if(l!==void 0&&l[0]!==".val()"){if(Yd(l,a)){if(u==="exists")return"exists-false";if(kO.has(u))return!1;if(u==="val"||u==="getPriority")return null}const d=i.asIteration().children;let h=[];u==="hasChild"&&d.length===1?h=[d[0]]:u==="hasChildren"&&d.length===1&&d[0].ctorName==="Array"&&(h=d[0].children[1].asIteration().children);for(const f of h){const p=f.constIn("any");if(typeof p=="string"&&Yd([...l,...p.split("/").filter(Boolean)],a))return!1}}return t.evalOnDelete(a)===null?!1:void 0},CallExpr_memberAccess(t,n,r){return t.evalOnDelete(this.args.relSegments)===null?!1:void 0},UnaryExpr_not(t,n){const r=n.evalOnDelete(this.args.relSegments);return r==="exists-false"?"delete-guard":r==="delete-guard"?!1:typeof r=="boolean"?!r:void 0},Comparison_gt:Rs,Comparison_gte:Rs,Comparison_lt:Rs,Comparison_lte:Rs,Equality_strictEq:Xd,Equality_looseEq:Xd,Equality_strictNeq:Zd,Equality_looseNeq:Zd,LogicalAnd_and(t,n,r){const s=this.args.relSegments;return Ns(t,r,i=>i.evalOnDelete(s),IO)},LogicalOr_or(t,n,r){const s=this.args.relSegments;return Ns(t,r,i=>i.evalOnDelete(s),RO)},Ternary_ternary(t,n,r,s,i){const o=this.args.relSegments,a=t.evalOnDelete(o);if(a===!0)return r.evalOnDelete(o);if(a===!1||a==="exists-false")return i.evalOnDelete(o);if(Dn(r.evalOnDelete(o))&&Dn(i.evalOnDelete(o)))return!1}}),Bo=e,e}function Fo(e){if(e===void 0||!e.parsed.valid||e.parsed.errors.length>0)return;const t=is(e.raw);if(!t.ok)return;const n=NO()(t.match),r={readsAuth:!1,readsData:!1,readsRoot:!1,newDataReads:0,newDataEscapes:0,newDataExistsCalls:0,checksNamedChildren:!1};n.collect(r);const s=n.constant("signed-out"),i=n.constant("signed-in"),o=s!==void 0&&s===i?s:void 0;return{constant:o,signedOut:s,signedIn:i,...r,canGrantOnDelete:a=>o!==!1&&!Dn(n.evalOnDelete(a))}}function ef(e,t){const n=e.split("/").filter(Boolean);return t.split("/").filter(Boolean).slice(n.length)}function zy(e){return{node:e,read:Fo(e.read),write:Fo(e.write),validate:Fo(e.validate),children:e.children.map(zy)}}function As(e){return e!==void 0&&e.constant!==!1}function AO(e){const t=e.validate;return t===void 0||t.constant!==void 0?!1:t.newDataReads-t.newDataEscapes>t.newDataExistsCalls}function Cr(e){if(AO(e))return!0;if(e.children.length===0)return!1;const t=e.children.filter(n=>!Ya(n));return e.children.some(Cr)&&t.every(Cr)}function Hy(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??""}function Ya(e){return Hy(e.node.path).startsWith("$")}function kt(e){const t=e.raw.trim();return t.length<=80?t:`${t.slice(0,77)}...`}function OO(e){return e.raw.trim()==="true"?"true":`"${kt(e)}"`}function $O(e){return e.raw.trim()==="false"?"is false":`"${kt(e)}" is false for every request`}function qo(e){return e.raw.trim()==="true"?"is true":`"${kt(e)}" is true for every request`}function Vo(e){return e==="/"?"the database":e}function PO(e){const t=[];return Ky(zy(e),{ancestors:[],unboundedAbove:!1},t),t}function Ky(e,t,n){const r=e.node.path,s=e.write,i=e.read;if(s?.constant===!0&&n.push({code:"RTDB-SEC-1",severity:"critical",path:r,rule:".write",message:`${r} .write ${qo(e.node.write)}: anyone, signed in or not, can write, replace or delete any value under ${Vo(r)}.`,fix:`Replace ${r} .write ${OO(e.node.write)} with a condition on auth that a signed-out client fails, such as "auth != null && auth.uid == $uid" on the node each user owns.`}),i?.constant===!0){const p=r==="/";n.push({code:"RTDB-SEC-2",severity:p?"critical":"medium",path:r,rule:".read",message:p?`/ .read ${qo(e.node.read)}: anyone, signed in or not, can read the entire database.`:`${r} .read ${qo(e.node.read)}: anyone, signed in or not, can read everything under ${r}.`,fix:p?"Remove .read from the root and grant .read on the subtrees clients need, with a condition on auth.":`Require auth in ${r} .read ("auth != null"), or keep ${r} only if every value under it is meant to be public.`})}s!==void 0&&s.constant===void 0&&!s.readsAuth&&n.push({code:"RTDB-SEC-3",severity:"high",path:r,rule:".write",message:`${r} .write does not read auth: a signed-out client can write under ${Vo(r)} whenever "${kt(e.node.write)}" holds.`,fix:`Add an auth condition to ${r} .write, such as "auth != null && (${kt(e.node.write)})".`});for(const p of["read","write"]){const m=e[p];if(m===void 0)continue;const g=p==="read"?".read":".write",b=t.ancestors.find(S=>{const k=S[p];return As(k)?k.constant===!0?m.constant!==!0:m.constant===!1||k.signedIn===!0&&m.signedOut===!1:!1});if(b===void 0)continue;const w=b.node.path,x=b.node[p],v=e.node[p];let _;b[p].constant===!0?_=`${r} ${g} never restricts access: ${w} ${g} is true and grants ${p} on every path under it, and a deeper rule cannot revoke an ancestor's grant.`:m.constant===!1?_=`${r} ${g} ${$O(e.node[p])} and does not revoke ${w} ${g}: whenever "${kt(x)}" holds, ${w} grants ${p} on every path under it, including ${r}.`:_=`${r} ${g} "${kt(v)}" restricts nothing: ${w} ${g} "${kt(x)}" already grants every signed-in client ${p} on every path under it, including ${r}, and a deeper rule cannot revoke an ancestor's grant.`,n.push({code:"RTDB-SEC-4",severity:"high",path:r,rule:g,message:_,fix:`Move the grant from ${w} ${g} down to the children that need it, so that no ancestor of ${r} grants ${p}.`})}const o=e.validate;if(o!==void 0&&o.constant===void 0&&(o.readsData||o.readsRoot||o.newDataExistsCalls>0)){const p=[...t.ancestors,e].find(m=>As(m.write)&&m.write.canGrantOnDelete(ef(m.node.path,r)));if(p!==void 0){const m=p.node.path,g=ef(m,r),b=g.length>0&&g.every(w=>!w.startsWith("$"))?`newData.child('${g.join("/")}').exists()`:"newData.exists()";n.push({code:"RTDB-SEC-5",severity:"high",path:r,rule:".validate",message:`${r} .validate does not run when ${r} is deleted: .validate runs only on a non-null new value, and ${m} .write grants without requiring ${b}, so a client it admits can delete ${r} (write null at ${m}) and bypass "${kt(e.node.validate)}".`,fix:`Add "${b}" to ${m} .write to refuse deletes, or write the delete condition there, such as "${b} || <who may delete>".`})}}let a=t.unboundedAbove;!a&&As(s)&&s.newDataReads===s.newDataExistsCalls&&!Cr(e)&&(a=!0,n.push({code:"RTDB-SEC-6",severity:"high",path:r,rule:".write",message:`${r} .write accepts any value: no .validate rule at or below ${r} checks its own new value, and the .write rule does not check newData, so a client it admits can store data of any shape and size under ${Vo(r)}.`,fix:`Add .validate rules under ${r} that fix the shape and bound sizes, such as "newData.isString() && newData.val().length <= 100", and "$other": { ".validate": false } for keys you do not name.`}));const l=e.children.filter(p=>!Ya(p)&&Cr(p)).map(p=>Hy(p.node.path)),u=l.length>0||o?.checksNamedChildren===!0,d=e.children.some(p=>Ya(p)&&(p.validate?.constant===!1||Cr(p))),h=[...t.ancestors,e].some(p=>As(p.write));if(u&&!d&&h){const p=l.length>0?`names ${l.join(", ")} with .validate rules`:"checks named children in .validate";n.push({code:"RTDB-SEC-7",severity:"medium",path:r,rule:".validate",message:`${r} ${p} but has no $other rule: a write at or above ${r} can add any other key under it, and no .validate rule checks that key.`,fix:`Add "$other": { ".validate": false } under ${r} to reject keys it does not name.`})}const f={ancestors:[...t.ancestors,e],unboundedAbove:a};for(const p of e.children)Ky(p,f,n)}function DO(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function TO(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class Gy{placement;constructor(t){this.placement=t}get doc(){if(this.placement.kind!=="every-instance")throw new Error("per-instance rules hold one ruleset per instance");return this.placement.rules.doc}lint(){return this.placement.kind==="every-instance"?tf(this.doc):[...new Set(this.placement.instances.values())].flatMap(t=>tf(t.doc).map(n=>t.file===void 0?n:{...n,file:t.file}))}runOne(t){const n=pO(this.placement,t),r=n.instance,s={case:t,...t.description!==void 0?{description:t.description}:{},...r!==void 0?{instance:r}:{}},i="problem"in n?ol(n.problem):fO(n.rules.doc,n.evaluated);if(!i.success)return{...s,expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:"",reason:i.error.message,trace:[]};const o=i.data,a=o.unsupported===!0,l=a?"UNSUPPORTED":o.allowed?"ALLOW":"DENY",u=!a&&l===t.expectation;return{...s,expectation:t.expectation,decision:l,passed:u,unsupported:a,matchedPath:o.matchedPath,matchedRule:o.matchedRule,reason:o.reason,trace:r===void 0?o.trace:o.trace.map(d=>({...d,instance:r}))}}simulate(t){const n=t.map(o=>this.runOne(o));let r=0,s=0,i=0;for(const o of n)o.unsupported?i++:o.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n,coverage:this.coverage(n)}}coverage(t,n){if(this.placement.kind==="every-instance")return nf(this.doc,t,n);const{defaultInstance:r,instances:s}=this.placement,o=[...new Set(s.values())].map(a=>{const l=t.filter(u=>s.get(u.instance??r)===a);return nf(a.doc,l,{...a.file===void 0?{}:{file:a.file},...a.source===void 0?{}:{source:a.source}})});return o.length===1?o[0]:vO(o)}explain(t){const n=this.runOne(t);return{...n.instance!==void 0?{instance:n.instance}:{},decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason,trace:n.trace}}toJSON(){if(this.placement.kind==="every-instance")return this.doc.toJSON();const t=Fy(this.placement,this.placement.defaultInstance,!1);if("problem"in t)throw new Error(t.problem);return t.doc.toJSON()}}function tf(e){const t=e.check(),n=[...t.errors.map(r=>zd(r,"error")),...t.warnings.map(r=>zd(r,"warning"))];return t.errors.some(r=>r.code==="COMPILE_ERROR")?n:[...n,...PO(e.compile()).map($0)]}function MO(e){try{return e.compile()}catch{return Dc({rules:{}})}}function nf(e,t,n){const r=new wO(MO(e));for(const s of t){r.record(s.trace);const i=s.unsupported&&s.trace.length===0;s.case.operation==="read"&&!i&&r.recordQuery(s.case.path,s.case.query)}return r.summarize(n)}function Wo(e){return new Gy({kind:"every-instance",rules:{doc:e}})}class Jy{json;compiled;compileError;constructor(t){this.json=t}toJSON(){return this.json}compile(){if(this.compileError!==void 0)throw this.compileError;try{this.compiled??=Dc(this.json)}catch(t){throw this.compileError=t,t}return this.compiled}check(){return My(()=>this.compile())}simulate(t){let n;try{n=this.compile()}catch(r){return ol(`the ruleset does not compile: ${r instanceof Error?r.message:String(r)}`)}return Tc(n,Ty(t))}}function Yy(e){let t;try{t=JSON.parse(LC(e))}catch(s){const i=s instanceof Error?s.message:String(s);throw rf(`Realtime Database rules text is not valid JSON: ${i}`)}const n=t?.rules;if(!(typeof n=="object"&&n!==null&&!Array.isArray(n)))throw rf('Realtime Database rules text has no top-level "rules" object');return t}function rf(e){return new Va(e,[{code:"PARSE_ERROR",severity:"error",message:e,origin:"parse"}])}function LO(e){return typeof e=="string"&&(e=Yy(e)),DO(e)?Wo(e):TO(e)?Wo(new Jy(e)):Wo(nO(e))}function UO(e,t={}){const n=yO(e,t),r=new Map;for(const s of n.files){let i;try{i=Yy(s.text)}catch(a){throw a instanceof Va?new Va(`${s.path}: ${a.message}`,a.issues):a}const o={doc:new Jy(i),file:s.file,source:s.text};for(const a of s.instances)r.set(a,o)}return new Gy({kind:"per-instance",defaultInstance:n.defaultInstance,...n.projectId===void 0?{}:{projectId:n.projectId},instances:r})}const BO=Object.assign(LO,{fromFirebaseJson:UO});function Qy(e){return e&&typeof e=="object"&&Ta in e?MR(e).backend:Bk(e)}function Xy(e){return Qy(e).getActiveRules()}function sf(e){return Qy(e).snapshotState()}function FO(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function of(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function qO(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function VO(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 Zy(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:of(e)};const i=Object.entries(e).sort(([h],[f])=>h.localeCompare(f)),o={},a=[];for(const[h,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?a.push([h,f]):o[h]=of(f);const l=n>=r&&a.length>0,u=i.length>s,d=n>=r?[]:a.slice(0,s).map(([h,f])=>Zy(f,FO(t,h),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:o}}function WO(e,t={}){const n=qO(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return Zy(VO(e,n),n,0,r,s)}function eg(e){return e.children.reduce((t,n)=>t+1+eg(n),0)}const zo={anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]};function zO(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, update, or validate operation against the RTDB rules and data currently loaded in the local sandbox. newData may be any JSON value, such as 5 or true; for update it is the patch keyed by the paths written, relative to path. A read may carry a query so query.* rules evaluate. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","update","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{},query:{type:"object",properties:{orderByChild:{type:"string"},orderByKey:{type:"boolean",enum:[!0]},orderByValue:{type:"boolean",enum:[!0]},equalTo:zo,startAt:zo,endAt:zo,limitToFirst:{type:"integer"},limitToLast:{type:"integer"}},additionalProperties:!1},now:{type:"number"}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=Xy(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=sf(r),o=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{};let a=n.now;a===void 0&&(a=Te(r).now());let l=null;if(n.auth){const h=Ny(n.auth.uid,n.auth.tenant,n.auth.claims);l={uid:h.uid,token:h.token}}const u={expectation:"ALLOW",operation:n.operation,path:n.path,auth:l,data:o,now:a};n.newData!==void 0&&(u.newData=n.newData),n.query!==void 0&&(u.query=n.query);const d=BO(s).simulate([u]).cases[0];return{ok:!d.unsupported,summary:d.unsupported?`Simulation unsupported: ${d.reason}`:`Simulation: ${d.decision.toLowerCase()}`,data:{decision:d.decision,allowed:d.decision==="ALLOW",unsupported:d.unsupported,matchedPath:d.matchedPath,matchedRule:d.matchedRule,reason:d.reason,trace:d.trace}}}},{name:"rtdb_crawl_structure",description:"Describe the structure of the RTDB data currently loaded in the local sandbox without returning leaf values or contacting a production database.",parameters:{type:"object",properties:{path:{type:"string",description:"Root-relative path to inspect. Defaults to /."},maxDepth:{type:"number",minimum:0,description:"Maximum object depth to return. Defaults to 10."},maxChildren:{type:"number",minimum:1,description:"Maximum object children to return per node. Defaults to 100."}}},async execute(t){const n=t,r=await e.resolveSandbox(),s=WO(sf(r),n);return{ok:!0,summary:`Crawled ${eg(s)} object paths from ${s.path}`,data:s}}}]}function ar(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,claims:{...e.customClaims},providers:e.providerUserInfo.map(t=>t.providerId),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,tenantId:e.tenantId,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}function HO(e,t){const n=JSON.stringify(t?{uid:e,claims:t}:{uid:e}),r=new TextEncoder().encode(n);let s="";for(const i of r)s+=String.fromCharCode(i);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(e,t){return{ok:!1,summary:t,data:{code:e}}}function cr(e){const t=typeof e?.code=="string"?e.code:"auth/internal-error";return Mt(t,e instanceof Error?e.message:String(e))}function Ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $t(e){return Ks(e)?e:{}}function Os(e,t){const n=e.uid;return typeof n!="string"||n.length===0?Mt("auth/argument-error",`${t}: uid must be a non-empty string.`):n}function tg(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>({providerId:t}))}function af(e){return{uid:e.uid,email:e.email,password:e.password,displayName:e.displayName,phoneNumber:e.phoneNumber,customClaims:e.claims,disabled:e.disabled,emailVerified:e.emailVerified,providerUserInfo:tg(e.providers)}}const Qa={type:"object",description:"Custom claims. Rules read them as request.auth.token.<name>."},KO={type:"array",items:{type:"string"},description:"Provider ids to link, for example google.com. A user created under a dotted provider id and no password is assigned a generated photoUrl."},Xa={email:{type:"string"},password:{type:"string",description:"At least six characters. Never returned."},displayName:{type:"string"},phoneNumber:{type:"string"},claims:Qa,providers:KO,disabled:{type:"boolean"},emailVerified:{type:"boolean"}},GO={type:"object",properties:{uid:{type:"string",description:"Generated when omitted."},...Xa},required:["email"]},cf="Users land in the one pool the application, Studio, and rules evaluation share. Creating a user does not sign anyone in, and a password is never returned. A user created under a dotted provider id with no password is assigned a generated photoUrl; password, phone, and anonymous users keep photoUrl null.";function JO(e){const t=async()=>Fc(await e.resolveSandbox());return[{name:"auth_create_user",description:`Create one user in the connected sandbox's user store. ${cf}`,parameters:{type:"object",properties:{uid:{type:"string",description:"User id. Generated when omitted."},...Xa}},async execute(n){const r=$t(n),s=await t();try{const i=xe.createUser(s,af(r));return{ok:!0,summary:`Created user ${i.uid}`,data:{user:ar(i)}}}catch(i){return cr(i)}}},{name:"auth_import_users",description:`Create many users in order, reporting each failure without stopping. ${cf}`,parameters:{type:"object",properties:{users:{type:"array",items:GO,description:"Users to create, in order. Each requires an email."}},required:["users"]},async execute(n){const s=$t(n).users;if(!Array.isArray(s))return Mt("auth/argument-error","auth_import_users: users must be an array.");const i=await t(),o=[],a=[];s.forEach((u,d)=>{const h=Ks(u)?u:{};if(typeof h.email!="string"||h.email.length===0){a.push({index:d,...h.uid?{uid:h.uid}:{},email:String(h.email??""),code:"auth/argument-error",message:`auth_import_users: users[${d}].email is required.`});return}try{o.push(xe.createUser(i,af(h)).uid)}catch(f){const p=cr(f).data;a.push({index:d,...h.uid?{uid:h.uid}:{},email:h.email,code:p.code,message:f instanceof Error?f.message:String(f)})}});const l=a.length===0?`Imported ${o.length} of ${s.length} users`:`Imported ${o.length} of ${s.length} users; ${a.length} failed`;return{ok:a.length===0,summary:l,data:{created:o,errors:a}}}},{name:"auth_get_user",description:"Read one user of the connected sandbox's user store by uid, or by email when uid is omitted.",parameters:{type:"object",properties:{uid:{type:"string"},email:{type:"string",description:"Matched case-insensitively. Used when uid is omitted."}}},async execute(n){const{uid:r,email:s}=$t(n);if(typeof r!="string"&&typeof s!="string")return Mt("auth/argument-error","auth_get_user: uid or email is required.");const i=xe.listUsers(await t()),o=typeof r=="string"?i.find(a=>a.uid===r):i.find(a=>a.email?.toLowerCase()===s.toLowerCase());return o?{ok:!0,summary:`Got user ${o.uid}`,data:{user:ar(o)}}:Mt("auth/user-not-found",typeof r=="string"?`No user found for uid ${r}.`:`No user found for email ${s}.`)}},{name:"auth_list_users",description:"Read every user of the connected sandbox's user store.",parameters:{type:"object",properties:{limit:{type:"number",description:"Return at most this many users."}}},async execute(n){const{limit:r}=$t(n);if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<0))return Mt("auth/argument-error","auth_list_users: limit must be a non-negative number.");const s=xe.listUsers(await t()),i=(r!==void 0?s.slice(0,r):s).map(ar);return{ok:!0,summary:`${i.length} of ${s.length} users`,data:{users:i,total:s.length}}}},{name:"auth_update_user",description:"Change one user. Every supplied field replaces what is stored; claims replaces the whole claims map. Omitted fields are left alone.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},...Xa},required:["uid"]},async execute(n){const r=$t(n),s=Os(r,"auth_update_user");if(typeof s!="string")return s;const i=r,o={...i.email!==void 0?{email:i.email}:{},...i.password!==void 0?{password:i.password}:{},...i.displayName!==void 0?{displayName:i.displayName}:{},...i.phoneNumber!==void 0?{phoneNumber:i.phoneNumber}:{},...i.disabled!==void 0?{disabled:i.disabled}:{},...i.emailVerified!==void 0?{emailVerified:i.emailVerified}:{},...i.claims!==void 0?{customClaims:i.claims}:{},...i.providers!==void 0?{providerUserInfo:tg(i.providers)}:{}};try{const a=xe.updateUser(await t(),s,o);return{ok:!0,summary:`Updated user ${s}`,data:{user:ar(a)}}}catch(a){return cr(a)}}},{name:"auth_delete_user",description:"Remove one user from the connected sandbox's user store.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to remove."}},required:["uid"]},async execute(n){const r=$t(n),s=Os(r,"auth_delete_user");if(typeof s!="string")return s;try{return xe.deleteUser(await t(),s),{ok:!0,summary:`Deleted user ${s}`,data:{uid:s}}}catch(i){return cr(i)}}},{name:"auth_set_claims",description:"Replace one user's custom claims. Rules read them as request.auth.token.<name> on the next sign-in or token refresh. An empty object clears them.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},claims:Qa},required:["uid","claims"]},async execute(n){const r=$t(n),s=Os(r,"auth_set_claims");if(typeof s!="string")return s;if(!Ks(r.claims))return Mt("auth/argument-error","auth_set_claims: claims must be an object.");const i=r.claims;try{const o=xe.updateUser(await t(),s,{customClaims:i});return{ok:!0,summary:`Set claims on user ${s}`,data:{user:ar(o)}}}catch(o){return cr(o)}}},{name:"auth_custom_token",description:"Mint a custom token for a uid that the sandbox's signInWithCustomToken accepts. The sandbox has no signing key, so the token is unsigned and is only good against this sandbox.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user the token signs in."},claims:Qa},required:["uid"]},async execute(n){const r=$t(n),s=Os(r,"auth_custom_token");if(typeof s!="string")return s;const i=r.claims;return i!==void 0&&!Ks(i)?Mt("auth/argument-error","auth_custom_token: claims must be an object."):{ok:!0,summary:`Minted custom token for ${s}`,data:{uid:s,claims:i??{},token:HO(s,i)}}}}]}const YO={"firestore-simulator":({env:e})=>px({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>gI({resolveDb:e}),"firestore-inspect":({sandbox:e})=>bI({resolveSandbox:()=>e}),"messaging-inspection":({sandbox:e})=>A0(()=>e),"rtdb-inspection":({sandbox:e})=>zO({resolveSandbox:()=>e}),"auth-users":({sandbox:e})=>JO({resolveSandbox:()=>e})};function QO(e,t){return t==="admin"?jc(e):ei(e.withAuth(Ny(t.uid,t.tenant,t.claims)))}function XO(e,t){return t===void 0||t.mode==="app-session"||t.mode==="admin"?jc(e):t.mode==="anon"?ei(e.withAuth(null)):ei(e.withAuth({uid:t.uid,...t.token!==void 0?{token:t.token}:{},...t.tenant!==void 0?{tenant:t.tenant}:{}}))}function ZO(e,t){const n={sandbox:e,env:ts(e),resolveDb:r=>r!==void 0?QO(e,r):XO(e,t)};return Ay("forwarded").flatMap(r=>YO[r.key](n))}function e$(e){return e===void 0||e.mode==="app-session"?"app-session":e.mode==="admin"||e.mode==="anon"?e.mode:JSON.stringify([e.uid,e.tenant??null,e.token??null])}const t$=16;function n$(e){const t=new Map;function n(r){const s=e$(r),i=t.get(s);if(i)return i;const o=ZO(e,r);w0("sandbox dispatcher tools",o.map(l=>l.name),ng);const a=new Map(o.map(l=>[l.name,l]));if(t.size>=t$)for(const l of[...t.keys()])l!=="app-session"&&t.delete(l);return t.set(s,a),a}return n(void 0),async(r,s,i)=>{const o=n(i).get(r);if(!o)throw new s$(r);const a={signal:new AbortController().signal},l=await o.execute(s,a);return{ok:l.ok,summary:l.summary,data:l.data}}}const lf=new WeakMap;async function r$(e,t,n,r){let s=lf.get(e);return s||(s=n$(e),lf.set(e,s)),s(t,n,r)}const ng=Ay("forwarded").flatMap(e=>Object.keys(e.tools));class s$ extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}function i$(e){if(e!==void 0&&e.length>0)return e;if(typeof window<"u"){const r=window;if("__PYRIC_BRIDGE_URL__"in r){const l=r.__PYRIC_BRIDGE_URL__;if(typeof l=="string"&&l.length>0)return l}const i=r.location.hostname||"localhost";return`${r.location.protocol==="https:"?"wss:":"ws:"}//${i}:${bd}${wd}`}return`ws://localhost:${bd}${wd}`}function o$(e){try{const t=new URL(e),n=t.protocol==="wss:";return t.protocol=n?"https:":"http:",[`${t.origin}/__pyric/health`,`${t.origin}/health`]}catch{return[]}}const a$={op:!0,sub:!0,unsub:!0,disconnect:!0,appConfig:!0,"clock-subscribe":!0,tool:!0};function Un(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function c$(e){return!Un(e)||!(typeof e.t=="string"&&Object.hasOwn(a$,e.t))?!1:e.t==="op"||e.t==="tool"||e.t==="disconnect"?typeof e.id=="string":e.t==="sub"||e.t==="unsub"?typeof e.subId=="string":!0}function l$(e){return Un(e)?typeof e.method=="string":!1}function u$(e){if(!Un(e))return!1;const n=typeof e.target=="string",r=Un(e.target);return n||r}function uf(e){if(!Un(e))return!1;switch(e.mode){case"admin":case"anon":case"app-session":return!0;case"as":try{return pv(e),!0}catch{return!1}default:return!1}}function df(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function d$(e){if("clientSessionId"in e&&e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return"Invalid bridge client session ID.";switch(e.type){case"hello":{const n=!df(e.tools),r=typeof e.sandboxId!="string",s=e.capabilities===void 0||df(e.capabilities);return n||r||!s?"Invalid sandbox peer handshake.":void 0}case"hello-ack":return typeof e.bridgeVersion!="string"?"Invalid sandbox peer acknowledgement.":void 0;case"tool-call":{const n=typeof e.id=="string",r=typeof e.name=="string",s=Un(e.args),i=e.callerId===void 0||typeof e.callerId=="string",o=e.actAs===void 0||uf(e.actAs);return!n||!r||!s||!i||!o?"Invalid sandbox tool call envelope.":void 0}case"worker-client-disconnect":case"worker-client-interrupted":return typeof e.clientSessionId=="string"?void 0:"Invalid bridge client session ID.";case"ping":case"pong":return typeof e.id!="string"?"Invalid bridge heartbeat ID.":void 0;case"remote-set-lens":{const n=typeof e.clientSessionId=="string",r=e.id===void 0||typeof e.id=="string",s=uf(e.lens);return!n||!r||!s?"Invalid remote identity lens envelope.":void 0}case"worker-message":return c$(e.message)?void 0:"Invalid worker message envelope.";case"worker-op":{const n=typeof e.id=="string",r=l$(e.op);return!n||!r?"Invalid worker relay operation envelope.":void 0}case"worker-sub":{const n=typeof e.subId=="string",r=u$(e.sub);return!n||!r?"Invalid worker relay subscription envelope.":void 0}case"worker-unsub":return typeof e.subId!="string"?"Invalid worker relay unsubscribe envelope.":void 0;default:return}}const f$=new Set(["hello-ack","tool-call","worker-op","worker-sub","worker-unsub","worker-client-disconnect","ping"]),h$=new TextEncoder,p$=500,m$=3e4,y$=2e3,g$=.5,b$=3;function w$(e,t={}){const n=i$(t.url),r=t.sandboxId??v$(),s=t.dispatcher??r$,i=t.toolNames??[...ng],o=t.initialReconnectDelayMs??p$,a=t.maxReconnectDelayMs??m$,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??y$,h=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let p=null,m=!1,g=0,b=null,w=null,x=0,v={kind:"connecting"};const _=new Map;function S(){for(const A of _.values())try{A()}catch{}_.clear()}function k(A){v=A;try{u(A)}catch{}}function I(A){const D=p;if(D!==null&&D.readyState===WebSocket.OPEN)try{const W=Ry(A);if(W===void 0){D.close(Fa,Kr);return}D.send(W)}catch{}}function O(){if(m)return;k({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(D){const W=D instanceof Error?D.message:String(D);N(`failed to open WebSocket: ${W}`);return}p=A,A.onopen=()=>{g=0;const D={type:"hello",protocol:1,tools:i,sandboxId:r};f!==null&&(D.capabilities=[eR]),I(D)},A.onmessage=D=>{const T=D.data,W=typeof T=="string";if(W&&h$.encode(T).byteLength>qr){A.close(Fa,Kr);return}let V;try{V=JSON.parse(W?T:"")}catch{A.close(4002,"Invalid bridge message JSON.");return}const F=V;if(!Mm(F)){A.close(4002,"Unrecognized bridge message envelope.");return}if(!f$.has(F.type))return;const M=d$(F);if(M!==void 0){A.close(4002,M);return}if(F.type==="hello-ack"){if(F.protocol!==1){const oe="Unsupported bridge protocol. Expected version 1.";m=!0,k({kind:"disconnected",reason:oe}),A.close(1e3,oe);return}k({kind:"connected",bridgeVersion:F.bridgeVersion});return}if(F.type==="tool-call"){P(F);return}if(F.type==="worker-op"){R(F);return}if(F.type==="worker-sub"){E(F);return}if(F.type==="worker-unsub"){const ut=_.get(F.subId);if(ut!==void 0){_.delete(F.subId);try{ut()}catch{}}return}if(F.type==="worker-client-disconnect"){f?.disconnect?.(F.clientSessionId);return}if(F.type==="ping"){I({type:"pong",id:F.id});return}},A.onclose=D=>{const T=D.reason||`closed (code ${D.code})`;if(p=null,S(),D.code===ZI){j();return}N(T)},A.onerror=()=>{}}async function P(A){let D;try{const T=await s(e,A.name,A.args??{},A.actAs,A.callerId);D={type:"tool-result",id:A.id,ok:!0,result:T}}catch(T){const W=T instanceof Error;D={type:"tool-result",id:A.id,ok:!1,error:{code:W?T.name:"Error",message:W?T.message:String(T)}}}I(D)}async function R(A){if(f!==null)try{const T=await f.op(A.op,A.clientSessionId);xd(`op '${A.op.method}'`,T),I({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!0,value:T})}catch(T){const W=T.denialContext,U=T instanceof Error,V={code:T.code??"unknown",message:U?T.message:String(T)};W!==void 0&&(V.denialContext=W),I({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!1,error:V})}}function E(A){if(!(f===null||_.has(A.subId)))try{const W=f.subscribe(A.sub,U=>{try{xd(`subscription '${A.subId}'`,U)}catch(V){const F=V instanceof Error;I({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:{code:V.code??"invalid-argument",message:F?V.message:String(V)}}});return}I({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:U})},A.clientSessionId);_.set(A.subId,W)}catch(W){const U=W.denialContext,V=W instanceof Error,F={code:W.code??"unknown",message:V?W.message:String(W)};U!==void 0&&(F.denialContext=U),I({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:F}})}}function j(){if(!m){if(l){k({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,x=0,k({kind:"standby"}),$()}}function $(){if(m)return;const A=d*(1+Math.random()*g$);w=setTimeout(()=>{w=null,C()},A)}async function C(){if(m)return;let A=null;for(const U of o$(n))try{const V=await h(U);if(!V.ok)continue;const Se=await V.json();if(typeof Se.sandboxConnected=="boolean"){A=!Se.sandboxConnected;break}}catch{}if(m)return;if(A===!0){O();return}if(A===!1){x=0,$();return}if(x+=1,x>=b$){N("standby health poll unreachable");return}$()}function N(A){if(m)return;if(l){k({kind:"disconnected",reason:A});return}g+=1;const D=Math.min(o*2**(g-1),a);k({kind:"reconnecting",attempt:g,delayMs:D}),b=setTimeout(()=>{b=null,O()},D)}return O(),{disconnect(){m=!0,S();const A=b;A!==null&&(clearTimeout(A),b=null);const T=w;T!==null&&(clearTimeout(T),w=null);const U=p;if(U!==null){try{U.close()}catch{}p=null}k({kind:"disconnected",reason:"client closed"})},state(){return v}}}function v$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function rg(e,t,n="bridge-port"){try{const r=new URL(e,t.href),s=new URL(t.href),i=t.protocol==="https:"?"wss:":"ws:",o=s.port.length>0,a=r.port.length>0,d=n==="bridge-port"&&o&&a?`${s.hostname}:${r.port}`:s.host;return`${i}//${d}${r.pathname}`}catch{return e}}function x$(e,t){return{url:t,dispatcher:(n,r,s,i)=>ZR(e,r,s,i),workerRelay:{op:n=>eN(e,n),subscribe:(n,r)=>tN(e,n,r)}}}async function _$(e,t={}){const n=t.baseUrl??"",r=t.fetchImpl??(typeof fetch<"u"?fetch:null),s=u=>t.onStateChange?.({kind:"disconnected",reason:u});if(!r)return s("no fetch available"),null;let i;try{const u=await r(`${n}/__pyric/init.json`);if(!u.ok)return s("not served"),null;i=(await u.json()).bridgeUrl??null}catch{return s("not served"),null}if(!i)return s("bridge off"),null;const o=t.locationLike??(typeof window<"u"?window.location:null),a=o?rg(i,o):i,l=w$(null,{...x$(e,a),...t.onStateChange?{onStateChange:t.onStateChange}:{},...t.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:t.initialReconnectDelayMs}:{},...t.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:t.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",a),l}const S$={};function k$(){return!1}function E$(){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 j$(e,t={}){if(e==="local"){const r=t.baseUrl??"",s=k$(),o=t.persistence==="memory"||s?mv():jI(r),l=t.disableLive===!0?null:i0(t.workerUrl),d=l!==null&&l.runtime.getSnapshot().mode!=="hosted"?E$():null;let h=!1,f=null;l!==null&&d!==null&&_$(l.db,{baseUrl:r,onStateChange:x=>d.set(x)}).then(x=>{h?x?.disconnect():f=x});const m={mode:e,projects:s?RI():kI(r),persistence:o,dispose(){h=!0,f?.disconnect(),l?.dispose()}},g=l!==null,b=d!==null;return g&&(m.live=l),b&&(m.bridge=d),!s&&(m.workspace=$m(r)),m}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const sg=y.createContext(null),C$={status:"pending",env:null,error:null};function I$(e){try{return{status:"ready",env:j$(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function R$({mode:e="local",children:t}){const[n,r]=y.useState(null);y.useEffect(()=>{const i=I$(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:C$;return c.jsx(sg.Provider,{value:s,children:t})}function lt(){const e=y.useContext(sg);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const N$="pyric-studio:theme",Gs="dark";function A$(){return Gs}function O$(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const $$=y.createContext(null);function P$({children:e}){const[t,n]=y.useState(A$);y.useEffect(()=>{O$();try{localStorage.setItem(N$,Gs)}catch{}},[t]);const r="dark",s=y.useCallback(a=>n(Gs),[]),i=y.useCallback(()=>n(Gs),[]),o=y.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return c.jsx($$.Provider,{value:o,children:e})}function Ji(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function D$(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 al(e,t="",n=Ji()){let r=e;const s=n.replace(/\/$/,"");n!=="/"&&(e===s||e.startsWith(n))&&(r=e.slice(s.length));const i=r.split("/").filter(Boolean).map(l=>decodeURIComponent(l)),[o="",...a]=i;return{tab:o,rest:a,query:D$(t)}}function T$(e,t=Ji()){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 ig="studio",M$=[{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 L$({assuranceEnabled:e=!1}={}){return M$.filter(t=>t.id!=="assurance"||e)}const pn=L$({assuranceEnabled:!1}),U$=pn.map(e=>e.id);function B$(e){return pn.find(t=>t.id===e)??pn[0]}const Za="pyric:studio:navigated",F$={tab:"",rest:[],query:{}};function cl(){return typeof window<"u"?window.location.pathname+window.location.search:""}function q$(e){return e===""||e===ig?"home":e}function Ke(){if(typeof window>"u")return F$;const e=al(window.location.pathname,window.location.search);return{...e,tab:q$(e.tab)}}function V$(e){return e.tab==="home"?{...e,tab:ig}:e}function It(e){return T$(V$(e))}function og(){typeof window<"u"&&window.dispatchEvent(new Event(Za))}function Ae(e){if(typeof window>"u")return;const t=It(e);cl()!==t&&(window.history.pushState(null,"",t),og())}function Jr(e){typeof window>"u"||(window.history.replaceState(null,"",It(e)),og())}function Jt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Za,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Za,e)})}function W$(e,t){const n=y.useCallback(i=>e.includes(i)?i:t,[e,t]),r=y.useSyncExternalStore(Jt,()=>n(Ke().tab),()=>t);y.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const a=i.slice(1),l=a.indexOf("?"),u=al(`/${l===-1?a:a.slice(0,l)}`,l===-1?"":a.slice(l),"/");if(e.includes(u.tab)){Jr(u);return}}const o=Ke();e.includes(o.tab)||Jr({tab:n(o.tab)})},[n]);const s=y.useCallback(i=>{const o=n(i);o!==r&&Ae({tab:o})},[n,r]);return[r,s]}let ec=null;function z$(e){ec=e}function H$(){return ec?(ec(),!0):!1}function K$(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function G$(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 J$=7;function Y$(e,t){const n=e.trim();if(!n)return[];const r=t.filter(h=>h.id!=="settings"),s=[],i=[],o=[],[a="",...l]=n.split(/\s+/),u=l.join(" ");for(const h of r){const f={id:`tab:${h.id}`,label:`Go to ${h.label}`,hint:h.description,target:{tab:h.id}},p=h.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):G$(n,h.label)&&i.push(f),u&&(p===a.toLowerCase()||p.startsWith(a.toLowerCase()))){const m=u.split("/").filter(Boolean);h.id==="firestore"||h.id==="storage"?o.push({id:`deep:${h.id}:${u}`,label:`Open /${m.join("/")} in ${h.label}`,hint:h.id==="firestore"?"Firestore path":"Storage object path",target:{tab:h.id,rest:m}}):h.id==="auth"?o.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):h.id==="traffic"&&o.push({id:`deep:traffic:${u}`,label:`Open ${u} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:u}}})}}const d=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(d){const h=d[1].split("/").filter(Boolean);o.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:h}})}else if(n.includes("/")&&!n.includes(" ")){const h=n.split("/").filter(Boolean);h.length&&o.push({id:`deep:firestore:${n}`,label:`Open /${h.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:h}})}return[...s,...o,...i].slice(0,J$)}function tc(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const nc={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function Q$(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let o=0;for(;i.length&&s.length<n&&o<r;){o++;const a=await t(i.shift());for(const l of a.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...a.prefixes)}return s}async function X$(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const o=[],a=[],l=[...e];let u=0;for(;l.length&&o.length<r&&u<s;){const d=l.shift();u++;let h=[];try{h=await t(d)}catch{continue}for(const f of h){if(o.length>=r)break;const p=`${d}/${f}`;o.push(p);try{const m=await n(p,i);for(const g of m.slice(0,i))a.push(g),l.push(g)}catch{}}}return{subcollections:o,documents:a}}const Z$=5;function ji(e,t){const n=e.toLowerCase(),r=t.toLowerCase();if(!n||!r)return 0;if(r===n)return 1e3;if(r.startsWith(n))return 900-Math.min(r.length-n.length,100);const s=r.indexOf(n);if(s!==-1)return 700-Math.min(s,100);let i=0,o=-1,a=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(o===-1&&(o=u),a=u,i++);if(i!==n.length)return 0;const l=a-o+1;return Math.max(1,400-(l-n.length)*10-Math.min(o,50))}const eP={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},tP=["collection","document","subcollection","user","object","rtdb-key"];function nP(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 ag(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function rP(e,t){const{base:n,trailing:r}=ag(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const o=s.length-1;for(let a=0;a<o;a++)if(s[a].toLowerCase()!==i[a].toLowerCase())return 0;return r?s[o].toLowerCase()===i[o].toLowerCase()?850:0:ji(s[o],i[o])}function sP(e,t){const{base:n,trailing:r}=ag(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:ji(n,s)}function ff(e,t,n,r=Z$){const s=e.trim();if(!s)return[];const i=[],o=Y$(e,t);o.length&&i.push({kind:"navigate",title:"Go to",results:o});for(const a of tP){const l=a==="document"||a==="subcollection",u=a==="collection"||a==="subcollection",d=new Map;for(const f of n)f.kind===a&&d.set(tc(f),f);const h=[...d.values()].map(f=>({entry:f,score:Math.max(ji(s,f.label),f.alt?ji(s,f.alt):0,l?rP(s,f.label):0,u?sP(s,f.label):0)})).filter(f=>f.score>0).sort((f,p)=>p.score-f.score||f.entry.label.localeCompare(p.entry.label)).slice(0,r);h.length&&i.push({kind:a,title:eP[a],results:h.map(({entry:f})=>({id:tc(f),label:f.label,hint:nP(f),target:f.target}))})}return i}function hf(e){return e.flatMap(t=>t.results)}function iP(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function pf(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function oP(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 aP(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 cP(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function lP(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function uP(e,t={},n){const r={...nc,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},o=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(iP));const h=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const m=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);h.push(...m),i(m.map(pf))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await X$(h,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(oP)),i(p.map(pf))}catch{}})(),a=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(aP))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(cP))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(lP))}catch{}})();return await Promise.allSettled([o,a,l,u]),s}function dP(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return FI(r,e),r}const fP=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function hP(e){return Nh(e.withAuth(null),fP)}const pP="pyric-studio";function cg(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let mP=0;function yP(e){const t=dP(e,{projectId:"pyric-studio"},`pyric-studio-${mP++}`),n=ts(e),r=hP(e);return{sandbox:e,app:t,firestore:ei(e),adminFirestore:jc(r),auth:Fc(e),storage:FE(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>cg(n,s)}}function gP(e,t){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useMemo(()=>Dv(),[]),a=y.useMemo(()=>{try{return yP(o)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[o]);return y.useEffect(()=>{let u=!1;if(!e){r(!1);return}return o.enablePersistence({key:pP,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[o,e]),s?{status:"error",handles:null,error:s}:a?e!=null&&n||t==="ready"?{status:"ready",handles:a}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function bP(e){const t=ts(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=>cg(t,n)}}function Nt(){const e=Gt(),t=lt(),n=t.status==="ready"?t.env.persistence:void 0,r=gP(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=wP(s);return y.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:bP(e.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:e.error};case"disabled":{if(s&&r.status==="ready"){const o=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:o,adminFirestore:o,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:a=>s.listSubcollections(a),listDocuments:a=>s.listDocuments(a)}}}return r}}},[e,r,s,i])}function wP(e){const[t,n]=y.useState([]);return y.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(o=>{r&&n(o)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}function vP(e){let t=!0;return n=>{const r=t;t=!1,e(s=>_P(s,n,r))}}function xP(e){const t=new Map;for(const n of e)t.set(tc(n),n);return[...t.values()]}function _P(e,t,n){return xP(n?t:[...e??[],...t])}const SP=3e4;function lg(){const e=Nt(),t=lt(),[n,r]=y.useState(null),[s,i]=y.useState(!1),o=y.useRef(!1),a=y.useRef(e);a.current=e;const l=t.status==="ready"?t.env.live:void 0,u=y.useRef(l);u.current=l;const d=y.useRef(null),h=y.useRef(0),f=y.useRef(null),p=y.useRef(0),m=y.useCallback(b=>{const w=a.current;if(w.status!=="ready")return;const x=++h.current;o.current=!0,i(!0);const v=w.handles,_=v.adminFirestore,S=w.firestoreApi?.collection??br,k=w.firestoreApi?.query??xi,I=w.firestoreApi?.getDocs??vi,O=w.firestoreApi?.limit??_i,P=w.storageApi?.ref??Mr,R=w.storageApi?.listAll??Jc,E=w.authApi?.listUsers??xe.listUsers,j={listRootCollections:()=>v.listRootCollections(),listDocumentPaths:async(C,N)=>(await I(k(S(_,C),O(N)))).docs.slice(0,N).map(D=>`${C}/${D.id}`),listSubcollections:C=>Promise.resolve(v.listSubcollections(C)),listUsers:async C=>(await Promise.resolve(E(v.auth))).slice(0,C).map(A=>({uid:A.uid,email:A.email??null})),listStorageObjectPaths:C=>Q$(P(v.storage,""),R,{maxObjects:C,maxListCalls:nc.storageListCalls}),listRtdbTopLevelKeys:async()=>{const C=u.current;if(!C)return[];const N=Date.now()-p.current<SP;if(f.current!==null&&N&&!b?.rtdbLikely)return f.current;const A=await C.readRtdbState(),D=A===null||typeof A!="object"||Array.isArray(A)?[]:Object.keys(A);return f.current=D,p.current=Date.now(),D}},$=vP(C=>r(C));uP(j,nc,C=>{x===h.current&&$(C)}).catch(()=>{}).finally(()=>{if(x===h.current&&(o.current=!1,i(!1),r(C=>C??[]),d.current)){const C=d.current;d.current=null,m(C)}})},[]),g=y.useCallback(b=>{if(a.current.status==="ready"){if(o.current){d.current={...d.current,...b};return}m(b)}},[m]);return y.useEffect(()=>{e.status==="ready"&&n===null&&!o.current&&m()},[e,n,m]),{entries:n,building:s,ensure:g}}const kP=150;function EP(e){return e.startsWith("/")||/rtdb/i.test(e)}function ug({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=y.useState(""),[o,a]=y.useState(""),[l,u]=y.useState(0),[d,h]=y.useState(!1),f=y.useRef(null),{entries:p,building:m,ensure:g}=lg();y.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),y.useEffect(()=>{e&&f.current?.focus()},[e]),y.useEffect(()=>{const S=setTimeout(()=>a(s),kP);return()=>clearTimeout(S)},[s]);const b=y.useMemo(()=>ff(o,pn,p??[]),[o,p]),w=y.useMemo(()=>hf(b),[b]);y.useEffect(()=>{u(S=>w.length===0?0:Math.min(S,w.length-1))},[w.length]);const x=S=>{S&&(i(""),a(""),h(!1),Ae(S.target),t?.(S.target))},v=()=>{if(s===o){x(w[l]??w[0]);return}const S=hf(ff(s,pn,p??[]));x(S[0])};let _=0;return c.jsxs("div",{className:"studio-home__command",children:[c.jsx("div",{className:"studio-home__command-row",children:c.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&w.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),h(!0)},onBlur:()=>h(!1),onChange:S=>{const k=S.target.value;i(k),h(!0),EP(k)&&g({rtdbLikely:!0})},onKeyDown:S=>{if(S.key==="ArrowDown")S.preventDefault(),u(k=>Math.min(k+1,Math.max(w.length-1,0)));else if(S.key==="ArrowUp")S.preventDefault(),u(k=>Math.max(k-1,0));else if(S.key==="Enter")v();else if(S.key==="Escape"){if(n){n();return}i(""),a(""),h(!1)}}})}),d&&!b.length&&m&&p===null?c.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:c.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&b.length?c.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:S=>S.preventDefault(),children:b.map(S=>{const k=_;return _+=S.results.length,c.jsxs("div",{className:"studio-home__command-group",children:[c.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:S.title}),c.jsx("ul",{className:"studio-home__command-group-list",children:S.results.map((I,O)=>{const P=k+O;return c.jsx("li",{children:c.jsxs("button",{type:"button",role:"option","aria-selected":P===l,className:"studio-home__command-result","data-active":P===l?"true":void 0,onMouseEnter:()=>u(P),onClick:()=>x(I),children:[c.jsx("span",{className:"studio-home__command-label",children:I.label}),c.jsx("span",{className:"studio-home__command-sub",children:I.hint})]})},I.id)})})]},S.kind)})}):null]})}function jP({onClose:e}){const t=y.useRef(null);return y.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),y.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),c.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:c.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:c.jsx(ug,{autoFocus:!0,onEscape:e,onNavigated:e})})})}function ll(e){if(e.result==="allow")return!1;const t=e.queryProof?.kind;return t==="unsupported-predicate"||t==="unsupported-path"}function CP(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=Bh(e);return t?t.rules.kind==="evaluated":!1}function IP(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function RP(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 NP(e){if(!("request"in e)||!e.request)return;const n=e.request.updateMask;return Array.isArray(n)&&n.every(s=>Array.isArray(s)&&s.every(i=>typeof i=="string"))?n:void 0}function AP(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 OP(e){const t=[];for(const r of e)CP(r)&&t.push($P(r));return AP(t,e).sort((r,s)=>s.at-r.at)}function $P(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:IP(e),path:n,auth:e.auth,reasons:e.reasons??[],origin:r,unsupported:s==="unsupported"};"matchedRule"in e&&e.matchedRule&&(i.matchedRule=e.matchedRule),"evaluatedRule"in e&&e.evaluatedRule&&(i.evaluatedRule=e.evaluatedRule),"queryProof"in e&&e.queryProof&&(i.queryProof=e.queryProof),"rules"in e&&e.rules&&(i.rules=e.rules);const o=RP(e);o!==void 0&&(i.resourceData=o);const a=NP(e);return a!==void 0&&(i.updateMask=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const mf=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function PP(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function DP(e){return e==="Validation rule evaluated to false"||!!e?.startsWith("Validation rule at '")}function dg(e){if(DP(e.rules?.reason))return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function TP(e,t){const n=e.rules?.matchedPath;if(!(!t||!n||e.rules?.errorCode==="NO_MATCHING_RULE"))return gO(t,n,`.${dg(e)}`)?.line}function ul(e){if(e.result!=="allow")return e.queryProof?.failures.find(t=>t.kind===e.queryProof?.kind)}function MP(e){const t=PP(e),n=e.reasons.filter(i=>mf.test(i)),r=e.reasons.filter(i=>!mf.test(i)),s=ul(e);if(s)return{headline:ll(e)?`Query proof unsupported: Pyric could not prove ${e.method} ${e.path} safe. This does not establish Firebase's decision.`:`The query constraints do not satisfy the list rule for ${e.path}.`,engine:t,ruleNode:s.rule?.citation??"list rule",ruleExpression:s.rule?.expression,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${e.method} ${e.path}.`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.result==="allow"){if(t==="firestore"&&e.matchedRule){const o=e.matchedRule,a=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`;return{headline:`${a} allowed ${e.method} on ${e.path}.`,engine:t,ruleNode:a,ruleLines:n,otherLines:r,implicitDeny:!1}}return!e.matchedRule&&!e.rules&&!e.evaluatedRule&&n.length===0?{headline:`This ${e.method} on ${e.path} succeeded, but no rules evaluation was recorded for it — rules likely never ran (an admin/bypass operation from a worker that didn't stamp its lens, or a pre-provenance event).`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${e.method} on ${e.path}.`,engine:t,...e.rules?.matchedRule?{ruleExpression:e.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return t==="rtdb"?UP(e,n,r):t==="storage"?BP(e,n,r):LP(e,n,r)}function LP(e,t,n){const r=!e.matchedRule;let s,i;if(r)s=`No rule allowed ${e.method} on ${e.path}: implicit deny (no matching \`allow\`).`;else{const o=e.matchedRule;i=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function UP(e,t,n){const r=e.rules,s=dg(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",o=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let a,l;return i?a=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,a=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,a=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:a,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:o,ruleLines:t,otherLines:n,implicitDeny:i}}function BP(e,t,n){const r=e.reasons.find(a=>/^match\s/.test(a)),i=e.reasons.some(a=>/^no rule matches/.test(a))||!r;return{headline:i?`No \`match\` block allowed ${e.method} on ${e.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${e.method} on ${e.path}.`,engine:"storage",ruleNode:i?void 0:r,ruleLines:t,otherLines:n,implicitDeny:i}}function FP(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function qP(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:FP(s),...s.value!==void 0?{value:s.value}:{},...s.error!==void 0?{error:s.error}:{},...s.letBinding?{letBinding:s.letBinding.name}:{},...s.inlinedFrom?{inlinedFrom:s.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return t.forEach((s,i)=>{s.parent===null||s.parent===void 0||!n[s.parent]?r.push(n[i]):(n[i].depth=n[s.parent].depth+1,n[s.parent].children.push(n[i]))}),r}const VP={ALLOW:"true",DENY:"false",ERROR:"error",UNSUPPORTED:"unsupported"};function WP(e,t){const n=e.rules?.rtdbTrace;return!n||n.length===0?[]:(t===void 0?[...n]:Wy(t,n)).map(s=>{const i={source:s.conditionText,outcome:VP[s.verdict],...s.verdict==="ALLOW"||s.verdict==="DENY"?{value:s.verdict==="ALLOW"}:{},...s.message!==void 0?{error:s.message}:{},depth:0,children:[]},o={path:s.path,kind:s.kind,verdict:s.verdict,step:i,bindings:s.pathVariableBindings};return s.line!==void 0&&(o.line=s.line),o})}function zP(e){const t=[{name:"request.auth",present:e.auth!==null,value:e.auth,...e.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:e.method},{name:"request.path",present:!0,value:e.path}],n=e.method==="get"||e.method==="list"||e.method==="listen";return t.push({name:"request.resource.data",present:e.resourceData!==void 0,value:e.resourceData??null,...e.resourceData===void 0?{absentNote:n?"A read carries no proposed write, so request.resource.data is absent.":"No proposed write payload was captured for this denial."}:{}}),t.push({name:"resource",present:e.resourceBefore!==void 0,value:e.resourceBefore?{data:e.resourceBefore.data,exists:e.resourceBefore.exists}:null,...e.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),t}const Ir=500;function Ho(e,t){if(e.length<=Ir)return e;const n=e.slice(-Ir);if(t==="recent")return n;const r=new Set(Nc(e).map(i=>i.id));return[...e.slice(0,-Ir).filter(i=>(i.kind==="listener_attach"||i.kind==="listener"&&i.phase==="attach")&&r.has(i.listenerId)),...n]}function Yt(e="recent"){const t=Gt(),n=lt(),r=n.status==="ready"?n.env.live?.feed:void 0,s=t.status==="ready",[i,o]=y.useState([]);y.useEffect(()=>{if(s||!r){o([]);return}return o(Ho(r.history(),e)),r.subscribe(u=>o(d=>Ho(xI(d,u),e)))},[s,r,e]);const a=y.useMemo(()=>s?Ho(t.events,e):[],[s,t,e]);return s?a:i}function HP(e){return yv(e)}function KP(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function GP(e){const t=Bh(e);if(!t)throw new Error("Studio traffic adapter received a non-operation event");if(e.kind==="request")return{...e,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const a=e.error;a!==void 0&&KP(a.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let o=[];if(e.reasons!==void 0)o=e.reasons;else{const a=e.error;a!==void 0&&a.reasons!==void 0&&(o=a.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:o,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}let n="(service)";e.path!==void 0&&(n=e.path);let r=[];return e.reasons!==void 0&&(r=e.reasons),{kind:"operation",service:e.service,id:e.id,at:e.at,durationMs:e.durationMs,method:e.method,path:n,auth:e.auth,result:e.result,reasons:r,request:e.request,resourceBefore:e.resourceBefore,resourceAfter:e.resourceAfter,origin:e.origin,groupId:e.groupId,groupKind:e.groupKind,triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}function JP(){const e=Yt();return y.useMemo(()=>e.filter(HP).map(GP),[e])}function YP(){const e=Yt();return y.useMemo(()=>OP(e),[e])}const QP={status:"loading",payload:null},$s={status:"absent",payload:null};let Ci=QP,yf=!1;const rc=new Set;function Ps(e){Ci=e;for(const t of rc)t()}function XP(){if(!yf){if(yf=!0,typeof fetch>"u"){Ci=$s;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Ps($s);const n=await e.json();Ps({status:"ready",payload:n})}).catch(()=>Ps($s))}}function ZP(e){return rc.add(e),XP(),()=>rc.delete(e)}function ms(){return y.useSyncExternalStore(ZP,()=>Ci,()=>Ci)}function eD(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function tD(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 nD(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?tD(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function rD(e=5e3){const[t,n]=y.useState("checking");return y.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=eD(await nD(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},o=()=>typeof document>"u"||document.visibilityState!=="hidden",a=()=>{s||(s=setInterval(()=>{o()&&i()},e))},l=()=>{o()&&i()};return i().then(u=>{r&&u!=="absent"&&a()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const sD="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 iD(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 oD(e){return e==="studio"?"Studio":"App"}function aD(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(o=>({clientId:o.clientId,kindLabel:oD(o.kind),route:o.route||"/",visibilityLabel:o.visibility==="hidden"?"Hidden":"Visible",isThisPage:o.clientId===t,freshnessLabel:iD(o.lastSeen,n)}));s.sort((o,a)=>o.isThisPage!==a.isThisPage?o.isThisPage?-1:1:o.kindLabel!==a.kindLabel?o.kindLabel==="Studio"?-1:1:o.route.localeCompare(a.route));const i=s.filter(o=>!o.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:sD,otherCount:i}}function cD(){const e=lt(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=y.useState(null);return y.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(aD(i,s))})},[t]),n}const lD=new Set(["flutter","swift","ios","kotlin","android"]);function uD(e){const t=(e.platform||"").toLowerCase();return lD.has(t)}function dD(){const e=ms(),[t,n]=y.useState([]),[r,s]=y.useState(!1),i=y.useRef(null),o=y.useRef(new Map);return y.useEffect(()=>{if(e.status!=="ready"||!e.payload.bridgeUrl){s(!1),n([]);return}let l=!1,u=null,d=1e3;const h=typeof window<"u"?window.location:null,f=h?rg(e.payload.bridgeUrl,h):e.payload.bridgeUrl;function p(){if(!l)try{const m=new WebSocket(f);i.current=m,m.onopen=()=>{if(l){m.close();return}s(!0),d=1e3;try{m.send(JSON.stringify({type:"attach",protocol:1,clientInfo:{platform:"studio",deviceLabel:"Desktop Studio"}}))}catch{}},m.onmessage=g=>{if(!l)try{const b=JSON.parse(g.data);if(b.type==="consumer-presence"){const x=(b.consumers||[]).filter(uD);n(x)}else if(b.type==="remote-set-lens-ack"){const w=b;if(w.id&&o.current.has(w.id)){const x=o.current.get(w.id);o.current.delete(w.id),x?.(w.ok)}}}catch{}},m.onclose=()=>{i.current=null,!l&&(s(!1),u=setTimeout(()=>{d=Math.min(d*1.5,1e4),p()},d))},m.onerror=()=>{}}catch{s(!1)}}return p(),()=>{if(l=!0,u&&clearTimeout(u),i.current){try{i.current.close()}catch{}i.current=null}for(const m of o.current.values())m(!1);o.current.clear(),s(!1)}},[e]),{consumers:t,connected:r,setLens:async(l,u)=>{n(f=>f.map(p=>p.clientSessionId===l?{...p,activeLens:u,lastSeen:Date.now()}:p));const d=i.current;if(!d||d.readyState!==WebSocket.OPEN)return!1;const h=`lens-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;return new Promise(f=>{const p=setTimeout(()=>{o.current.delete(h),f(!0)},5e3);o.current.set(h,m=>{clearTimeout(p),f(m)});try{d.send(JSON.stringify({type:"remote-set-lens",id:h,clientSessionId:l,lens:u}))}catch{clearTimeout(p),o.current.delete(h),f(!1)}})}}}const fD={listUsers:xe.listUsers,subscribeUsers:xe.subscribeUsers,createUser:xe.createUser,updateUser:xe.updateUser,deleteUser:xe.deleteUser,clearUsers:xe.clearUsers,getAuthProviderConfig:xe.getAuthProviderConfig,setAuthProviderConfig:xe.setAuthProviderConfig,subscribeAuthProviderConfig:xe.subscribeAuthProviderConfig},fg=y.createContext(fD);function hD(){return y.useContext(fg)}function hg({value:e,children:t}){return y.createElement(fg.Provider,{value:e},t)}function pD(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Yi(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:o}=hD(),[a,l]=y.useState([]),[u,d]=y.useState(!0),[h,f]=y.useState(void 0),[p,m]=y.useState(""),g=y.useCallback(k=>{l(k),f(void 0),d(!1)},[]);y.useEffect(()=>{let k=!1;d(!0),f(void 0);const I=E=>{k||g(E)},O=E=>{k||(l([]),f(E instanceof Error?E:new Error(String(E))),d(!1))},P=()=>{try{const E=t(e);E&&typeof E.then=="function"?E.then(I).catch(O):I(E)}catch(E){O(E)}};let R;try{P(),R=n(e,P)}catch(E){O(E)}return()=>{k=!0,R?.()}},[e,t,n,g]);const b=y.useMemo(()=>{const k=p.trim().toLowerCase();return k?a.filter(I=>pD(I,k)):a},[a,p]),w=y.useCallback(k=>r(e,k),[e,r]),x=y.useCallback((k,I)=>s(e,k,I),[e,s]),v=y.useCallback(k=>i(e,k),[e,i]),_=y.useCallback(()=>o(e),[e,o]),S=y.useCallback(()=>{const k=t(e);k&&typeof k.then=="function"?k.then(g).catch(()=>{}):g(k)},[e,t,g]);return{users:b,totalCount:a.length,isLoading:u,error:h,filter:p,setFilter:m,createUser:w,updateUser:x,deleteUser:v,clearUsers:_,refresh:S}}const mD=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],yD=1e3;function pg(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>yD)return{ok:!1,message:"Custom claims length must not exceed 1000 characters"};let n;try{n=JSON.parse(t)}catch{return{ok:!1,message:"Custom claims must be a valid JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,message:"Custom claims must be a valid JSON object"};for(const r of mD)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const gD={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},bD=new Set(["password","anonymous","phone"]),wD=/^[^@]+@[^@]+\.[^@]+$/,gf=6;function vD(e){return e?{email:e.email??"",password:"",displayName:e.displayName??"",phoneNumber:e.phoneNumber??"",photoUrl:e.photoUrl??"",emailVerified:e.emailVerified,disabled:e.disabled,claimsText:Object.keys(e.customClaims).length?JSON.stringify(e.customClaims,null,2):"",providerIds:e.providerUserInfo.map(t=>t.providerId).filter(t=>!bD.has(t))}:{...gD}}function xD(e){const t=vD(e);return{fields:t,initial:{...t}}}function _D(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function SD(e){const t={},n=e.email.trim(),r=e.password;n&&!wD.test(n)&&(t.email="Invalid email"),r&&r.length<gf&&(t.password=`Password should be at least ${gf} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=pg(e.claimsText);return s.ok||(t.claims=s.message),t}function kD(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!mg(t.providerIds,n.providerIds):t[r]!==n[r])}function mg(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function yg(e){const t=pg(e.claimsText);return t.ok?t.claims:void 0}function ED(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=yg(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function jD(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=yg(t)??{}),mg(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function gg(e={}){const[t,n]=y.useReducer(_D,e.initial,xD),r=y.useMemo(()=>SD(t.fields),[t.fields]),s=y.useMemo(()=>kD(t),[t]),i=y.useCallback((a,l)=>n({type:"setField",field:a,value:l}),[]),o=y.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:o,toCreateRequest:()=>ED(t),toUpdateRequest:()=>jD(t),dispatch:n}}const CD={"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 Ii(e){return CD[e]??e}var dl=Tv();function xn(e,t,n){let r=n.initialDeps??[],s,i=!0;function o(){var a,l,u;let d;n.key&&((a=n.debug)!=null&&a.call(n))&&(d=Date.now());const h=e();if(!(h.length!==r.length||h.some((m,g)=>r[g]!==m)))return s;r=h;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...h),n.key&&((u=n.debug)!=null&&u.call(n))){const m=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-p)*100)/100,b=g/16,w=(x,v)=>{for(x=String(x);x.length<v;)x=" "+x;return x};console.info(`%c⏱ ${w(g,5)} /${w(m,5)} ms`,`
|
|
142
|
+
font-size: .6rem;
|
|
143
|
+
font-weight: bold;
|
|
144
|
+
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return o.updateDeps=a=>{r=a},o}function bf(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const ID=(e,t)=>Math.abs(e-t)<1.01,RD=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},wf=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},ND=e=>e,AD=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},OD=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(s(wf(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(wf(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},vf={passive:!0},xf=typeof window>"u"?!0:"onscrollend"in window,$D=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&xf?()=>{}:RD(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:h,isRtl:f}=e.options;s=h?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},a=o(!0),l=o(!1);n.addEventListener("scroll",a,vf);const u=e.options.useScrollendEvent&&xf;return u&&n.addEventListener("scrollend",l,vf),()=>{n.removeEventListener("scroll",a),u&&n.removeEventListener("scrollend",l)}},PD=(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"]},DD=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const o=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class TD{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(i=>{const o=()=>{const a=i.target,l=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(a,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var i;return(i=r())==null?void 0:i.observe(s,{box:"border-box"})},unobserve:s=>{var i;return(i=r())==null?void 0:i.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:ND,rangeExtractor:AD,onChange:()=>{},measureElement:PD,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=xn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,i)=>{this.scrollAdjustments=0,this.scrollDirection=i?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=i,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,i=new Map;for(let o=r-1;o>=0;o--){const a=n[o];if(s.has(a.lane))continue;const l=i.get(a.lane);if(l==null||a.end>l.end?i.set(a.lane,a):a.end<l.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,a)=>o.end===a.end?o.index-a.index:o.end-a.end)[0]:void 0},this.getMeasurementOptions=xn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,i,o,a,l)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=xn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l},u)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const p of this.laneAssignments.keys())p>=n&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const h=this.measurementsCache.slice(0,d),f=new Array(a).fill(void 0);for(let p=0;p<d;p++){const m=h[p];m&&(f[m.lane]=p)}for(let p=d;p<n;p++){const m=i(p),g=this.laneAssignments.get(p);let b,w;const x=l==="estimate"||u.has(m);if(g!==void 0&&this.options.lanes>1){b=g;const k=f[b],I=k!==void 0?h[k]:void 0;w=I?I.end+this.options.gap:r+s}else{const k=this.options.lanes===1?h[p-1]:this.getFurthestMeasurement(h,p);w=k?k.end+this.options.gap:r+s,b=k?k.lane:p%this.options.lanes,this.options.lanes>1&&x&&this.laneAssignments.set(p,b)}const v=u.get(m),_=typeof v=="number"?v:this.options.estimateSize(p),S=w+_;h[p]={index:p,start:w,size:_,end:S,key:m,lane:b},f[b]=p}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=xn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?MD({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=xn(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,i,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,s-i),a=Math.min(this.options.count-1,s+i);return n>=o&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,a)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(a))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),i=this.elementsCache.get(s);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s;const i=this.measurementsCache[n];if(!i)return;const o=this.itemSizeCache.get(i.key)??i.size,a=r-o;a!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,a,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=xn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,o=n.length;i<o;i++){const a=n[i],l=r[a];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return bf(r[bg(0,r.length-1,s=>bf(r[s]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),i=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[o,a]=i,l=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const i=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&i.some(a=>a===null);){const a=r[o];i[a.lane]===null&&(i[a.lane]=a.end),o--}s=Math.max(...i.filter(a=>a!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,i=1,o=s!==this.scrollState.lastTargetOffset;if(!o&&ID(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const bg=(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 MD({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:s};let o=bg(0,s,i,n),a=o;if(r===1)for(;a<s&&e[a].end<n+t;)a++;else if(r>1){const l=Array(r).fill(0);for(;a<s&&l.some(d=>d<n+t);){const d=e[a];l[d.lane]=d.end,a++}const u=Array(r).fill(n+t);for(;o>=0&&u.some(d=>d>=n);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:o,endIndex:a}}const _f=typeof document<"u"?y.useLayoutEffect:y.useEffect;function LD({useFlushSync:e=!0,...t}){const n=y.useReducer(()=>({}),{})[1],r={...t,onChange:(i,o)=>{var a;e&&o?dl.flushSync(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[s]=y.useState(()=>new TD(r));return s.setOptions(r),_f(()=>s._didMount(),[]),_f(()=>s._willUpdate()),s}function UD(e){return LD({observeElementRect:OD,observeElementOffset:$D,scrollToFn:DD,...e})}function fl({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:o}){const a=y.useRef(null),l=typeof t=="function"?t:()=>t,u=UD({count:e.length,getScrollElement:()=>a.current,estimateSize:l,overscan:r});return c.jsx("div",{ref:a,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:c.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const h=e[d.index],f=o?o(h,d.index):d.key;return c.jsx("div",{"data-pyric-virtual-row":!0,"data-index":d.index,ref:u.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${d.start}px)`},children:n(h,d.index)},f)})})})}function Sf(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function BD(e){return e.isAnonymous&&e.providerUserInfo.length===0?c.jsx("span",{"data-pyric-provider-id":"anonymous",children:Ii("anonymous")}):e.providerUserInfo.map(t=>c.jsx("span",{"data-pyric-provider-id":t.providerId,children:Ii(t.providerId)},t.providerId))}function kf(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function wg({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:o,renderSelection:a,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:h=kf,formatLastLoginAt:f=kf,emptyState:p,noResultsState:m,className:g,virtualizeThreshold:b=100,rowHeight:w=44,virtualizedHeight:x="60vh"}){if(n)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const S=!!r?.trim();return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":S?"":void 0,children:S?m??"No results":p??"No users for this project yet"})}const v=e.length>b,_=S=>c.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":S.uid,"data-pyric-user-disabled":S.disabled?"":void 0,children:[a?c.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:a(S)}):null,c.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?c.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(S),children:i?i(S):Sf(S)}):(i??Sf)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(o??BD)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:h(S.createdAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(S.lastLoginAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:S.uid}),u?c.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(S)}):null]},S.uid);return c.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":v?"":void 0,"data-pyric-selection":a?"":void 0,"data-pyric-actions":u?"":void 0,children:[c.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[a?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,c.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),v?c.jsx(fl,{items:e,estimateSize:w,height:x,getItemKey:S=>S.uid,renderItem:_}):c.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(_)})]})}function FD({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return c.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[c.jsx("textarea",{"data-pyric-field":"claims","data-pyric-claims-invalid":n!=null?"":void 0,"aria-label":"Custom claims (optional)","aria-invalid":n!=null||void 0,placeholder:s,value:e,onChange:o=>t(o.target.value)}),n!=null&&c.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&c.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function qD({selected:e,onChange:t}){return c.jsx("div",{"data-pyric-provider-checklist":!0,children:hp.map(n=>c.jsxs("label",{"data-pyric-provider-option":n,children:[c.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),c.jsx("span",{"data-pyric-provider-option-label":!0,children:Ii(n)}),c.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function vg({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:o,renderField:a}){const l=gg({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),h=(m,g,b,w,x=null)=>({name:m,label:g,input:w,error:x,kind:b,defaultRender:()=>b==="checkbox"?c.jsxs("label",{"data-pyric-field-label":m,children:[w,c.jsx("span",{"data-pyric-label-text":!0,children:g})]},m):b==="group"?c.jsxs("fieldset",{"data-pyric-field-label":m,children:[c.jsx("legend",{"data-pyric-label-text":!0,children:g}),w]},m):c.jsxs("label",{"data-pyric-field-label":m,children:[c.jsx("span",{"data-pyric-label-text":!0,children:g}),w,x!=null&&c.jsx("p",{role:"alert","data-pyric-field-error":m,children:x})]},m)}),f=[h("email","Email","text",c.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:m=>l.setField("email",m.target.value)}),l.errors.email??null),h("password","Password","text",c.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:m=>l.setField("password",m.target.value)}),l.errors.password??null),h("display-name","Display name","text",c.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:m=>l.setField("displayName",m.target.value)})),h("phone-number","Phone number","text",c.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:m=>l.setField("phoneNumber",m.target.value)})),h("photo-url","Photo URL","text",c.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:m=>l.setField("photoUrl",m.target.value)})),...u==="create"?[h("providers","Sign-in providers","group",c.jsx(qD,{selected:l.fields.providerIds,onChange:m=>l.setField("providerIds",m)}))]:[],h("email-verified","Verified email","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:m=>l.setField("emailVerified",m.target.checked)})),h("disabled","Disabled (sign-in attempts are rejected)","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:m=>l.setField("disabled",m.target.checked)}))],p=m=>{m.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return c.jsxs("form",{className:o,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":l.isDirty?"":void 0,"data-pyric-is-valid":l.isValid?"":void 0,onSubmit:p,children:[f.map(m=>a?c.jsx(y.Fragment,{children:a(m)},m.name):m.defaultRender()),c.jsx(FD,{value:l.fields.claimsText,onChange:m=>l.setField("claimsText",m),error:l.errors.claims}),i,c.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?c.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,c.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}const xg=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex^="-"])'].join(", ");function VD(e){return Array.from(e.querySelectorAll(xg)).filter(t=>{if(t.disabled||t.hasAttribute("disabled")||t.getAttribute("aria-hidden")==="true"||t.tabIndex<0)return!1;if(typeof window<"u"&&typeof window.getComputedStyle=="function")try{const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!0})}function WD(e,t,n){const r=y.useRef(n);r.current=n,y.useEffect(()=>{if(!t)return;const s=i=>{if(i.key==="Escape"){i.stopPropagation(),r.current();return}if(i.key!=="Tab")return;const o=e.current;if(!o)return;const a=VD(o);if(a.length===0){i.preventDefault(),o.focus();return}const l=a[0],u=a[a.length-1],d=document.activeElement;let h=a.indexOf(d);if(h===-1&&d&&o.contains(d)){const f=d.closest?.(xg);f&&(h=a.indexOf(f))}if(i.preventDefault(),h===-1){i.shiftKey?u.focus():l.focus();return}i.shiftKey?h<=0?u.focus():a[h-1].focus():h>=a.length-1?l.focus():a[h+1].focus()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function zD({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:o="Cancel",onConfirm:a,className:l}){const u=y.useRef(null),d=y.useRef(null),h=y.useRef(null);return WD(u,e,()=>t(!1)),y.useEffect(()=>{if(e)return h.current=document.activeElement,d.current?.focus(),()=>{h.current?.focus?.()}},[e]),!e||typeof document>"u"?null:dl.createPortal(c.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:f=>{f.target===f.currentTarget&&t(!1)},children:[c.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),c.jsxs("div",{ref:u,role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:l,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[c.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?c.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,c.jsxs("div",{"data-pyric-confirm-actions":!0,children:[c.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:o}),c.jsx("button",{ref:d,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:a,children:i})]})]})]}),document.body)}const _g=y.createContext(null);function Yn(){const e=y.useContext(_g);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function hl({children:e,dialogClassName:t}){const[n,r]=y.useState(null),s=y.useRef(!1),i=y.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),o=y.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),a=y.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=y.useMemo(()=>i,[i]);return c.jsxs(_g.Provider,{value:l,children:[e,n?c.jsx(zD,{open:!0,onOpenChange:a,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:o,className:t}):null]})}function HD(e){return e.email??e.phoneNumber??e.displayName??e.uid}function KD({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:o}){const a=Yn(),l=async()=>{await a({title:n,body:r??`This will permanently delete ${HD(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?c.jsx(c.Fragment,{children:i({onClick:l})}):c.jsx("button",{type:"button",className:o,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function GD(e,t=Date.now()){const n=Math.max(0,t-e);return n<5e3?"just now":n<6e4?`${Math.floor(n/1e3)}s ago`:n<36e5?`${Math.floor(n/6e4)}m ago`:`${Math.floor(n/36e5)}h ago`}function JD(e){const t=e.toLowerCase();return t==="flutter"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--flutter",children:"Flutter"}):t==="swift"||t==="ios"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--swift",children:"iOS Swift"}):t==="kotlin"||t==="android"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--kotlin",children:"Android Kotlin"}):c.jsx("span",{className:"studio-remote-client__badge",children:e})}function YD(e){if(!e||e.mode==="app-session")return"App Session";if(e.mode==="admin")return"Admin Bypass";if(e.mode==="anon")return"Anonymous";if(e.mode==="as"){const t=e.token?" +claims":"",n=e.tenant?` @${e.tenant}`:"";return`User: ${e.uid}${t}${n}`}return"Unknown"}function QD({auth:e,onSelectUser:t}){const{users:n,isLoading:r}=Yi(e);return c.jsxs("select",{className:"studio-remote-client__select",defaultValue:"",disabled:r||n.length===0,onChange:s=>{const i=n.find(o=>o.uid===s.target.value);i&&(t(i),s.target.value="")},children:[c.jsx("option",{value:"",disabled:!0,children:r?"Loading sandbox users…":n.length===0?"No sandbox users found":"Impersonate sandbox user…"}),n.map(s=>c.jsx("option",{value:s.uid,children:s.email?`${s.email} (${s.uid.slice(0,6)}…)`:s.uid},s.uid))]})}function XD({isOpen:e,onClose:t,consumers:n,onSetLens:r,triggerRef:s,auth:i}){const[o,a]=y.useState(""),[l,u]=y.useState(""),[d,h]=y.useState(""),[f,p]=y.useState(!1),[m,g]=y.useState("");if(y.useEffect(()=>{if(!e)return;const x=v=>{v.key==="Escape"&&(t(),s?.current?.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[e,t,s]),!e)return null;const b=i,w=(x,v)=>{let _;if(l.trim())try{_=JSON.parse(l)}catch{alert("Invalid JSON for custom claims");return}const S=d.trim()||void 0;r(x,{mode:"as",uid:v,token:_,tenant:S})};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-remote-clients__backdrop",onMouseDown:t}),c.jsxs("div",{id:"studio-remote-clients-panel",className:"studio-remote-clients__panel",role:"dialog","aria-label":"Remote Mobile Clients",children:[c.jsxs("div",{className:"studio-remote-clients__header",children:[c.jsx("h3",{className:"studio-remote-clients__title",children:"Remote Mobile Clients"}),c.jsxs("span",{className:"studio-remote-clients__count",children:[n.length," connected"]})]}),n.length===0?c.jsx("p",{className:"studio-remote-clients__empty",children:"No remote mobile clients connected over the bridge. Connect your Flutter, iOS, or Android app to control its identity remotely."}):c.jsx("ul",{className:"studio-remote-clients__list",children:n.map(x=>c.jsxs("li",{className:"studio-remote-clients__item",children:[c.jsxs("div",{className:"studio-remote-clients__item-top",children:[c.jsxs("div",{className:"studio-remote-clients__item-info",children:[JD(x.platform),c.jsx("span",{className:"studio-remote-clients__device",children:x.deviceLabel||"Mobile Device"})]}),c.jsx("span",{className:"studio-remote-clients__freshness",children:GD(x.lastSeen)})]}),c.jsxs("div",{className:"studio-remote-clients__session",children:["Session: ",c.jsxs("code",{children:[x.clientSessionId.slice(0,10),"…"]})]}),c.jsxs("div",{className:"studio-remote-clients__current-lens",children:[c.jsx("span",{className:"studio-remote-clients__lens-label",children:"Active Lens:"}),c.jsx("span",{className:"studio-remote-clients__lens-pill",children:YD(x.activeLens)})]}),c.jsxs("div",{className:"studio-remote-clients__actions",children:[c.jsxs("div",{className:"studio-remote-clients__btn-group",children:[c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="app-session"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"app-session"}),children:"App Session"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="admin"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"admin"}),children:"Admin"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="anon"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"anon"}),children:"Anon"})]}),c.jsx("div",{className:"studio-remote-clients__switcher",children:b?c.jsx(QD,{auth:b,onSelectUser:v=>w(x.clientSessionId,v.uid)}):c.jsxs("div",{className:"studio-remote-clients__manual-row",children:[c.jsx("input",{type:"text",placeholder:"Impersonate UID…",className:"studio-remote-client__input",value:o===x.clientSessionId?m:"",onChange:v=>{a(x.clientSessionId),g(v.target.value)}}),c.jsx("button",{type:"button",className:"studio-remote-btn studio-remote-btn--primary",disabled:!m.trim(),onClick:()=>{w(x.clientSessionId,m.trim()),g("")},children:"Switch"})]})}),c.jsxs("div",{className:"studio-remote-clients__advanced",children:[c.jsx("button",{type:"button",className:"studio-remote-clients__advanced-toggle",onClick:()=>p(!f),children:f?"▲ Hide Claims & Tenant":"▼ Custom Claims / Tenant"}),f?c.jsxs("div",{className:"studio-remote-clients__advanced-inputs",children:[c.jsx("input",{type:"text",placeholder:"Custom Claims JSON, e.g. { role: 'admin' }",className:"studio-remote-client__input",value:l,onChange:v=>u(v.target.value)}),c.jsx("input",{type:"text",placeholder:"Tenant ID (optional)",className:"studio-remote-client__input",value:d,onChange:v=>h(v.target.value)})]}):null]})]})]},x.clientSessionId))})]})]})}const ZD={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},eT=()=>()=>{},Ef=()=>ZD;function tT(){const e=lt(),t=ms(),n=Yt(),[r,s]=y.useState(!1),i=n.some(he=>he.kind==="runtime_error"&&he.error.code==="persistence-unhealthy"),o=t.status==="ready"&&t.payload.persistenceUnhealthy===!0;y.useEffect(()=>{(i||o)&&s(!0)},[i,o]);const a=rD(),l=cD(),[u,d]=y.useState(!1),h=y.useRef(null),{consumers:f,setLens:p}=dD(),[m,g]=y.useState(!1),b=y.useRef(null),w=Nt(),v=w.status==="ready"?w.handles?.auth:void 0,S=e.status==="ready"?e.env.live?.runtime:void 0,k=y.useSyncExternalStore(S?.subscribe??eT,S?.getSnapshot??Ef,S?.getSnapshot??Ef),O=t.status==="ready"&&e.status==="ready"&&!e.env.live,P=e.status==="error",R="mode"in k&&k.mode==="hosted",E=R?k.error:"worker update failed",j=k.error!==null;let $=null;O&&($="worker unreachable"),P&&($="backend error"),j&&($=E),r&&($="persistence failed — writes blocked");let C="Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.";P&&(C=e.error.message),j&&(C=k.error??C),r&&(C="Reads may include unsaved changes. Repair the hosted store and restart the host.");const N=!j,A=R?N:a==="available",D=!R||N;y.useEffect(()=>{if(!u)return;const he=Ge=>{Ge.key==="Escape"&&(d(!1),h.current?.focus())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[u]);const T=k.updateAvailable,U=k.updating?"updating worker…":"update worker",V=$!==null,F=D&&l!==null&&l.count>0,we=l?.prominent===!0?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger",M=l!==null&&l.otherCount>0,ge=l?.otherCount===1?"":"s";let ce=`${l?.chipLabel}. Expand for details.`;M&&(ce=`${l.chipLabel}. ${l.otherCount} other page${ge} can keep the worker alive.`),R&&(ce=`${l?.chipLabel}. These pages share the Node host.`);const Z=R?"Data is shared by every client connected to this host.":l?.boundaryCopy;let fe=l?.count===1?"This page is the only connection to the shared sandbox worker.":`${l?.count} pages share this sandbox worker. Closing this page alone will not restart it.`;R&&(fe="These pages share the Node-hosted sandbox. Closing a page does not stop the host.");const et=D&&f.length>0,wt=f.length===1,ut=wt?"":"s",oe=wt?"1 remote client":`${f.length} remote clients`;return c.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[T&&c.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:k.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void S?.update().catch(()=>{}),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),U]}),V&&c.jsxs("a",{className:"studio-chip studio-chip--warn",href:It({tab:"settings"}),title:C,onClick:he=>{he.preventDefault(),Ae({tab:"settings"})},children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),$]}),F&&c.jsxs("span",{className:"studio-presence",children:[c.jsxs("button",{ref:h,type:"button",className:we,"aria-haspopup":"dialog","aria-expanded":u,"aria-controls":"studio-presence-panel",title:ce,onClick:()=>d(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.chipLabel]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>d(!1)}),c.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[c.jsx("p",{className:"studio-presence__lead",children:fe}),c.jsx("ul",{className:"studio-presence__list",children:l.clients.map(he=>c.jsxs("li",{className:"studio-presence__item",children:[c.jsxs("div",{className:"studio-presence__item-head",children:[c.jsx("span",{className:"studio-presence__kind",children:he.kindLabel}),he.isThisPage?c.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),c.jsx("div",{className:"studio-presence__route",title:he.route,children:he.route}),c.jsxs("div",{className:"studio-presence__meta",children:[he.visibilityLabel," · ",he.freshnessLabel]})]},he.clientId))}),c.jsx("p",{className:"studio-presence__boundary",children:Z})]})]})]}),et&&c.jsxs("span",{className:"studio-remote-clients",children:[c.jsxs("button",{ref:b,type:"button",className:"studio-chip studio-chip--live studio-remote-clients__trigger","aria-haspopup":"dialog","aria-expanded":m,"aria-controls":"studio-remote-clients-panel",title:`${f.length} remote client${ut} connected over the bridge. Click to control identity.`,onClick:()=>g(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),oe]}),c.jsx(XD,{isOpen:m,onClose:()=>g(!1),consumers:f,onSetLens:p,triggerRef:b,auth:v})]}),A&&c.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]})]})}function nT(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 jf(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 rT({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return y.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let o=s+1;for(;o<e.length&&e[o].groupId===i.groupId;)o++;const a=e.slice(s,o),l=i.origin==="transaction"?"transaction":"batch";r.push(jf(l,i.groupId,a)),s=o;continue}if(n&&i.origin==="listener"){let o=s+1;for(;o<e.length&&e[o].origin==="listener"&&!e[o].groupId&&nT(e[o],i);)o++;const a=e.slice(s,o);if(a.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(jf("listener-run",`listener-run:${l}:${s}`,a))}else r.push({type:"single",event:i});s=o;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const sT={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function iT({events:e,window:t,bucketCount:n=30}){return y.useMemo(()=>oT(e,t,n),[e,t.start,t.end,n])}function oT(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return sT;const s=r/n,i=new Array(n).fill(0),o=new Array(n).fill(0);let a=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let m=Math.floor((p-t.start)/s);m>=n&&(m=n-1),i[m]++,a++,f.result==="deny"&&(o[m]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const m=o[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:m,allows:f-m,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:m/d}}),total:a,denies:l,maxCount:d,outOfWindow:u}}const aT=new Set(["get","list"]),cT=new Set(["create","update","set"]),lT=new Set(["delete","remove"]),uT=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],dT=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Qi(e){return e.origin==="admin"}function fT(e,t=Qi){return e.result==="allow"||t(e)?aT.has(e.method)?"reads":cT.has(e.method)?"writes":lT.has(e.method)?"deletes":null:null}function hT(e,t=Qi){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const pT=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Sg(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return pT(r);const o=i/n,a=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),l=new Map(r.map(f=>[f.key,0]));for(const f of e){const p=f.at;if(p<t.start||p>=t.end)continue;const m=s(f);if(m==null)continue;let g=Math.floor((p-t.start)/o);g>=n&&(g=n-1);const b=a.get(m);b[g]++,l.set(m,(l.get(m)??0)+1)}let u=0;for(const f of a.values())for(const p of f)p>u&&(u=p);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*o,end:t.start+(f+1)*o};const h=r.map(f=>({key:f.key,label:f.label,values:a.get(f.key),total:l.get(f.key)??0}));return{points:d,series:h,maxValue:u}}function mT(e,t,n=24,r=Qi){return Sg(e,t,n,uT,s=>fT(s,r))}function yT(e,t,n=24,r=Qi){return Sg(e,t,n,dT,s=>hT(s,r))}function gT({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>mT(e,t,n,r),[e,t.start,t.end,n,r])}function bT({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>yT(e,t,n,r),[e,t.start,t.end,n,r])}function sc({children:e,kind:t,className:n,ariaLabel:r}){return c.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?c.jsx("span",{"aria-hidden":"true",children:e}):e})}function Yr(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function kg({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Yr,className:i}){return c.jsxs("button",{type:"button",onClick:()=>n?.(e),className:i,"data-pyric-traffic-row":"","data-pyric-result":e.result,"data-pyric-origin":e.origin,"data-pyric-method":e.method,"data-pyric-selected":t?"":void 0,children:[c.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),c.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),c.jsx(sc,{kind:e.method,children:e.method}),c.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}const wT={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function vT({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:o}){const[a,l]=y.useState(t);return c.jsxs("div",{className:o,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":a?"":void 0,children:[c.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":a,children:[c.jsx("span",{"data-pyric-group-kind-label":"",children:wT[e.kind]}),c.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?c.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),a?c.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>c.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:c.jsx(kg,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function xT(e){return e<0?0:e>1?1:e}function Ko(e,t){const n=t.end-t.start;return n<=0?0:xT((e-t.start)/n)}function Eg({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:o,liveAt:a,header:l,axis:u,emptyState:d,className:h}){const f=y.useId(),[p,m]=y.useState(null),[g,b]=y.useState(null),w=iT({events:e??[],window:n,bucketCount:r}),x=t??w,{buckets:v,total:_}=x,S=p??g,k=S===null?null:v.find(j=>j.index===S)??null,I=k!==null&&s?.start===k.start&&s.end===k.end;if(v.length===0)return c.jsx("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const O=_===0,P=a===void 0?n.end:a,R=P==null?null:Ko(P,n),E=typeof u=="function"?u(n):u;return c.jsxs("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":O?"":void 0,children:[l!==void 0&&c.jsx("div",{"data-pyric-timeline-header":"",children:l}),c.jsxs("div",{"data-pyric-timeline-chart":"",children:[c.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:v.map(j=>c.jsx(_T,{bucket:j,window:n,onBrush:i,onHover:o?m:void 0,onFocus:o?b:void 0,summaryId:o&&!I&&k?.index===j.index?f:void 0,selected:s?.start===j.start&&s.end===j.end},j.index))}),k&&o&&!I?c.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(k.index+.5)/Math.max(v.length,1)},children:o(k)}):null,s&&c.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Ko(s.start,n),"--pyric-brush-right":1-Ko(s.end,n)}}),R!=null&&c.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":R}})]}),E!=null&&c.jsx("div",{"data-pyric-timeline-axis":"",children:E})]})}function _T({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:o}){const a=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return c.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":e.index,"data-pyric-bucket-count":e.count,"data-pyric-bucket-denies":e.denies,"data-pyric-has-denies":e.denies>0?"":void 0,"data-pyric-bucket-selected":o?"":void 0,disabled:!a,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":a?o:void 0,onPointerEnter:r?()=>r(e.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(e.index):void 0,onBlur:s?()=>s(null):void 0,onClick:a?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[c.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const ST=e=>String(e);function pl({series:e,visible:t,onToggle:n,formatValue:r=ST,className:s}){const i=t!==void 0&&n!==void 0;return c.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((o,a)=>{const l=t?t.has(o.key):!0,u=c.jsxs(c.Fragment,{children:[c.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-metric-label":"",children:o.label}),c.jsx("span",{"data-pyric-metric-value":"",children:r(o.total)})]});return i?c.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,"data-pyric-metric-hidden":l?void 0:"",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(o.key),"data-pyric-metric-checkbox":""}),u]},o.key):c.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,children:u},o.key)})})}const kT=e=>String(e),ET=e=>new Date(e).toLocaleTimeString();function jg({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=kT,formatTime:i=ET,emptyState:o,className:a}){const[l,u]=y.useState(null);if(e.length===0)return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:o});const d=t.filter(w=>(!n||n.has(w.key))&&(!r||w.total>0));let h=0;for(const w of d)for(const x of w.values)x>h&&(h=x);const f=h===0?1:h,p=e.length,m=w=>p===1?50:w/(p-1)*100,g=w=>100-w/f*100,b=l!=null?e[l]:null;return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart",children:c.jsxs("div",{"data-pyric-chart-svg":"",children:[c.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(w=>{const x=t.indexOf(w);if(!((!n||n.has(w.key))&&(!r||w.total>0)))return null;const _=w.values.map((S,k)=>`${k===0?"M":"L"}${m(k)},${g(S)}`).join(" ");return c.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":w.key,"data-pyric-series-index":x,d:_,fill:"none",vectorEffect:"non-scaling-stroke"},w.key)})}),c.jsx("div",{"data-pyric-chart-hits":"",children:e.map((w,x)=>c.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":x,onMouseEnter:()=>u(x),onFocus:()=>u(x),onMouseLeave:()=>u(v=>v===x?null:v),onBlur:()=>u(v=>v===x?null:v),"aria-label":`${i(w.start)} to ${i(w.end)}`},w.index))}),b&&c.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":m(b.index)},children:[c.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(b.start)," – ",i(b.end)]}),d.map(w=>c.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":w.key,"data-pyric-series-index":t.indexOf(w),children:[c.jsx("span",{"data-pyric-tooltip-label":"",children:w.label}),c.jsx("span",{"data-pyric-tooltip-value":"",children:s(w.values[b.index])})]},w.key))]})]})})}function Cg(e={}){const[t]=y.useState(()=>(e.captureOwnerStack,void 0)),[n,r]=y.useState(void 0),s=y.useCallback(o=>{o!==null&&r(o)},[]);return{owner:y.useMemo(()=>{if(t!==void 0)return n===void 0?t:{...t,element:n}},[t,n]),ref:s}}function jT(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 CT={addDoc:Wh,collection:br,deleteDoc:oa,doc:st,getDoc:vm,getDocs:vi,limit:_i,onSnapshot:dI,query:xi,setDoc:Zs,startAfter:uI},Ig=y.createContext(CT);function ml(){return y.useContext(Ig)}function IT({value:e,children:t}){return y.createElement(Ig.Provider,{value:e},t)}function RT(e){const{onSnapshot:t}=ml(),{owner:n}=Cg(),[r,s]=y.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return y.useEffect(()=>{if(!e){s({data:void 0,error:void 0,isLoading:!1});return}return s(o=>({data:o.data,error:void 0,isLoading:!0})),t(e,{owner:n},o=>s({data:o,error:void 0,isLoading:!1}),o=>s({data:void 0,error:jT(o),isLoading:!1}))},[t,n,e]),r}function Xi(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&wn(e)!==null?"vector":Array.isArray(e)?"array":e instanceof Vt?"timestamp":e instanceof Mn?"geopoint":e instanceof on?"bytes":typeof e=="object"&&Rg(e)?"timestamp":typeof e=="object"&&Ag(e)?"geopoint":typeof e=="object"&&Ng(e)?"bytes":typeof e=="object"&&NT(e)?"reference":typeof e=="object"?"map":"null"}function Rg(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 Ng(e){const t=e,n=Object.keys(t);return n.length===1?t.bytes instanceof Uint8Array:n.length===2&&t.type==="firestore/bytes/1.0"&&typeof t.bytes=="string"}function yl(e){if(e instanceof on)return e;const t=e;return typeof t.bytes=="string"?on.fromBase64String(t.bytes):on.fromUint8Array(t.bytes)}function Ag(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function NT(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 wn(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Ds(t.value)||t.__type__==="__vector__"&&Ds(t.value))return Ts(t.value);if(Ds(t._values))return Ts(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Ds(n))return Ts(n)}catch{}return null}function Ds(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Ts(e){const t=e.slice();return{values:t,dimension:t.length}}const Cf=4;function Og(e){const t=e.values.slice(0,Cf).join(", "),n=e.values.length>Cf?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function Ri(e){const t=wn(e);if(t)return Og(t);if(Array.isArray(e))return e.map(Ri);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]=Ri(i);return r}}return e}function $g(){return crypto.randomUUID()}function AT(e){const t=$g(),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))ic(n,t,r,s);return n}function ic(e,t,n,r){const s=Xi(r),i=$g(),o={id:i,parentId:t,key:n,type:s,value:OT(s)?void 0:r};if(e.nodes[i]=o,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[a,l]of Object.entries(r))ic(e,i,a,l);else if(s==="array"&&Array.isArray(r))for(const a of r)ic(e,i,null,a);return i}function OT(e){return e==="map"||e==="array"}function Pg(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return oc(e,e.rootId)}function oc(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]=oc(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(oc(e,s));return r}default:return n.value}}function ac(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 Dg(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 Tg(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 Vt?void 0:"Expected a Timestamp";case"geopoint":return t instanceof Mn?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 wn(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Mg(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=Tg(r.type,r.value);s&&(t[r.id].error=s,n++)}for(const[r,s]of Object.entries(t)){if(s.type!=="map")continue;const i=e.childIds[r]??[],o=new Map;for(const a of i){const l=t[a];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[a].error=t[a].error??"Field name is required");const d=o.get(u)??[];d.push(a),o.set(u,d)}for(const[a,l]of o)if(a&&l.length>1)for(const u of l)t[u].error||n++,t[u].error=t[u].error??"Field name must be unique"}return{tree:{rootId:e.rootId,nodes:t,childIds:e.childIds},errorCount:n}}function gl(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return Vt.now();case"geopoint":return new Mn(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 cc(e){if(e===null||typeof e!="object"||wn(e)!==null)return e;if(Rg(e)){const n=e;return new Vt(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Ag(e)){const n=e;return new Mn(n.latitude,n.longitude)}if(Ng(e))return yl(e);if(Array.isArray(e))return e.map(cc);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=cc(s);return n}return e}function Lg(e){const t=AT(cc(e)),{tree:n,errorCount:r}=Mg(t);return{tree:n,initial:n,errorCount:r}}function $T(e,t){switch(t.type){case"setValue":return _n(e,n=>DT(n,t.nodeId,t.value));case"setType":return _n(e,n=>TT(n,t.nodeId,t.newType));case"setKey":return _n(e,n=>MT(n,t.nodeId,t.key));case"addMapEntry":return _n(e,n=>LT(n,t.parentId,t.key,t.childType));case"addArrayEntry":return _n(e,n=>UT(n,t.parentId,t.childType));case"remove":return _n(e,n=>BT(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:PT(e.initial)};case"replaceData":return Lg(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=ac(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=ac(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function _n(e,t){const n=t(ac(e.tree)),{tree:r,errorCount:s}=Mg(n);return{...e,tree:r,errorCount:s}}function PT(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function DT(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function TT(e,t,n){const r=e.nodes[t];if(!r||r.id===e.rootId&&n!=="map"||r.type===n)return e;if(r.type==="map"||r.type==="array"){const i=(e.childIds[t]??[]).slice();for(const o of i)for(const a of Dg(e,o))delete e.nodes[a],delete e.childIds[a];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:gl(n);return e.nodes[t]={...r,type:n,value:s},e}function MT(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 LT(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),o=r==="map"||r==="array"?void 0:gl(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:o},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function UT(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:gl(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 BT(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Dg(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 Ug(e={}){const t=e.initial??{},n=y.useRef(null);n.current==null&&(n.current=Lg(t));const[r,s]=y.useReducer($T,n.current),i=y.useCallback((x,v)=>s({type:"setValue",nodeId:x,value:v}),[]),o=y.useCallback((x,v)=>s({type:"setType",nodeId:x,newType:v}),[]),a=y.useCallback((x,v)=>s({type:"setKey",nodeId:x,key:v}),[]),l=y.useCallback((x,v,_)=>s({type:"addMapEntry",parentId:x,key:v,childType:_}),[]),u=y.useCallback((x,v)=>s({type:"addArrayEntry",parentId:x,childType:v}),[]),d=y.useCallback(x=>s({type:"remove",nodeId:x}),[]),h=y.useCallback(()=>s({type:"reset"}),[]),f=y.useCallback(x=>s({type:"replaceData",data:x}),[]),p=y.useCallback(x=>s({type:"touch",nodeId:x}),[]),m=y.useCallback(()=>s({type:"touchAll"}),[]),g=y.useCallback(()=>Pg(r.tree),[r.tree]),b=r.tree!==r.initial,w=r.errorCount===0;return y.useMemo(()=>({...r,isDirty:b,isValid:w,dispatch:s,setValue:i,setType:o,setKey:a,addMapEntry:l,addArrayEntry:u,remove:d,reset:h,replaceData:f,touch:p,touchAll:m,toData:g}),[r,b,w,i,o,a,l,u,d,h,f,p,m,g])}function FT({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=y.useState([]),[o,a]=y.useState(!0),[l,u]=y.useState(void 0),[d,h]=y.useState(!1),[f,p]=y.useState(0),[m,g]=y.useState(n),b=y.useRef(0),[w,x]=y.useState(0),{addDoc:v,deleteDoc:_,doc:S,getDoc:k,getDocs:I,limit:O,onSnapshot:P,query:R,setDoc:E,startAfter:j}=ml(),{owner:$}=Cg();y.useEffect(()=>{g(n)},[e,r,n,t]),y.useEffect(()=>{let T=!1;r==="paged"&&i([]),h(!1),a(!0),u(void 0);const W=t??e,U=r==="live"?m:n,V=R(W,O(U)),F=we=>{T||(i([...we.docs]),h(we.docs.length===U),a(!1))},Se=we=>{T||(u(we instanceof Error?we:new Error(String(we))),a(!1))};if(r==="live"){const we=++b.current,M=P(V,{owner:$},ne=>{x(we),F(ne)},Se);return()=>{T=!0,M()}}return I(V).then(we=>{F(we)}).catch(Se),()=>{T=!0}},[e,I,O,r,P,$,n,t,R,m,f]);const C=y.useCallback(()=>{if(!d||o)return;if(r==="live"){a(!0),g(V=>V+n);return}const T=s[s.length-1];if(!T)return;a(!0);const U=R(t??e,j(T),O(n));I(U).then(V=>{i(F=>[...F,...V.docs]),h(V.docs.length===n),a(!1)}).catch(V=>{u(V instanceof Error?V:new Error(String(V))),a(!1)})},[e,s,I,d,o,O,r,n,t,R,j]),N=y.useCallback(async(T,W,U)=>{if(T==null){const F=await v(e,W);return r==="paged"&&p(Se=>Se+1),F}const V=S(e,T);if(U?.onExisting==="fail"){const F=await k(V);if(typeof F.exists=="function"?F.exists():!!F.exists){const we=new Error(`Document "${T}" already exists.`);throw we.code="already-exists",we}}return await E(V,W),r==="paged"&&p(F=>F+1),V},[v,e,S,k,r,E]),A=y.useCallback(async T=>{await _(T),r==="paged"&&p(W=>W+1)},[_,r]),D=y.useCallback(()=>p(T=>T+1),[]);return{documents:s,isLoading:o,error:l,subscriptionGeneration:w,hasMore:d,loadMore:C,createDocument:N,deleteDocument:A,refresh:D}}function qT({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=y.useState([]),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(n);u.current=n;const d=t?.path;return y.useEffect(()=>{if(!t){s([]),o(!1),l(void 0);return}let h=!1;return o(!0),l(void 0),u.current(e,t).then(f=>{h||(s(f),o(!1))}).catch(f=>{h||(l(f instanceof Error?f:new Error(String(f))),o(!1))}),()=>{h=!0}},[e,d]),{subcollections:r,isLoading:i,error:a}}function If(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Rf(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ni(e,t){if(Object.is(e,t))return!0;if(If(e))return e.isEqual(t);if(If(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)=>Ni(s,t[i]));if(!Rf(e)||!Rf(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&Ni(e[s],t[s]))}function VT({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function WT({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const zT={type:"string",Display:VT,Edit:WT};function HT({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function KT({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,o=i===""?Number.NaN:parseFloat(i);t(o)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const GT={type:"number",Display:HT,Edit:KT};function JT({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function YT({value:e,onChange:t,path:n}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:c.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]})})}const QT={type:"boolean",Display:JT,Edit:YT};function XT({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function ZT({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const eM={type:"null",Display:XT,Edit:ZT};function bl(e){if(e instanceof Vt)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 tM(e){const t=e;return new Vt(t.seconds??t._seconds??0,t.nanoseconds??t._nanoseconds??0)}function nM(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const r=bl(t);return!Number.isNaN(r.getTime())&&r.getTime()===n.getTime()?t instanceof Vt?t:tM(t):Vt.fromDate(n)}function rM({value:e,path:t}){const n=bl(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return c.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function sM({value:e,onChange:t,error:n,path:r}){const s=bl(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),o=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,23);return c.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"datetime-local",step:"0.001",value:o,onChange:a=>{const l=a.target.value;if(!l)return;const u=nM(l,e);u&&t(u)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const iM={type:"timestamp",Display:rM,Edit:sM};function oM({value:e,path:t}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":t,"data-lat":String(e.latitude),"data-lng":String(e.longitude),children:[e.latitude,", ",e.longitude]})}function aM({value:e,onChange:t,error:n,path:r}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new Mn(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new Mn(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const cM={type:"geopoint",Display:oM,Edit:aM},Bg=y.createContext({});Bg.Provider;function lM(){return y.useContext(Bg)}function uM({value:e,path:t}){const{onReferenceClick:n}=lM();return n?c.jsx("button",{type:"button",onClick:()=>n(e),"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,"data-pyric-clickable":"",children:e.path}):c.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function dM({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,o=i.split("/").filter(Boolean),a=o[o.length-1]??"",l=e.firestore??{};t({path:i,id:a,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const fM={type:"reference",Display:uM,Edit:dM};function hM({value:e,path:t}){const n=yl(e),r=n.toBase64();return c.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(n.toUint8Array().byteLength),children:r})}function pM({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("textarea",{value:yl(e).toBase64(),onChange:s=>{try{t(on.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const mM={type:"bytes",Display:hM,Edit:pM};function lc({value:e,path:t,fieldEditors:n}){const r=Xi(e),s=n[r];if(!s)return null;const{Display:i}=s;return c.jsx(i,{value:e,path:t,fieldEditors:n})}function Fg({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Xi(t),o=i==="map"||i==="array",[a,l]=y.useState(!0),u=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},d=s==="key"?{"data-field-name":e}:{"data-field-index":e};return o?c.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[c.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":a,onClick:()=>l(h=>!h),children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),c.jsx("span",{...u,children:e})]}),a?c.jsx(lc,{value:t,path:n,fieldEditors:r}):null]}):c.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),c.jsx("span",{...u,children:e}),c.jsx(lc,{value:t,path:n,fieldEditors:r})]})}function yM({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return c.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>c.jsx(Fg,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const gM={type:"map",Display:yM};function bM({value:e,path:t,fieldEditors:n}){return c.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>c.jsx(Fg,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const wM={type:"array",Display:bM},Nf=4;function vM(e){return e.length<=Nf?`[${e.join(", ")}]`:`[${e.slice(0,Nf).join(", ")}, …]`}function xM({value:e,path:t}){const n=wn(e);return n?c.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),c.jsx("span",{"data-pyric-vector-preview":!0,children:vM(n.values)})]}):c.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function _M(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 SM({value:e,onChange:t,error:n,path:r}){const s=wn(e),i=s?JSON.stringify(s.values):"[]",[o,a]=y.useState(i),[l,u]=y.useState(void 0),d=p=>{a(p);const m=_M(p);if(!m.ok){u(m.error);return}u(void 0),t(m.value)},h=s?s.dimension:0,f=l??n;return c.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(h),"data-pyric-error":f?"":void 0,children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${h}`}),c.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),c.jsx("textarea",{"data-pyric-vector-raw":!0,value:o,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?c.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const kM={type:"vector",Display:xM,Edit:SM},Af={string:zT,number:GT,boolean:QT,null:eM,timestamp:iM,geopoint:cM,reference:fM,bytes:mM,map:gM,array:wM,vector:kM};function qg(e){return e?{...Af,...e}:Af}function Zi(e={}){const t=y.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=y.useState("wide");return y.useEffect(()=>{const o=t.current;if(!o||typeof ResizeObserver>"u")return;const a=new ResizeObserver(l=>{const u=l[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return a.observe(o),()=>a.disconnect()},[n,r]),{ref:t,size:s}}const Vg=y.createContext(null);function Qt(){const e=y.useContext(Vg);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function EM({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Ug({initial:e}),o=qg(t),a=y.useRef(n);a.current=n,y.useEffect(()=>{a.current?.(i)},[i]);const{ref:l,size:u}=Zi();return c.jsx(Vg.Provider,{value:{editor:i,fieldEditors:o},children:c.jsx("div",{ref:l,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":i.isValid?"":void 0,"data-pyric-is-dirty":i.isDirty?"":void 0,"data-size":u,children:r})})}function jM(){const{editor:e}=Qt(),t=e.tree.childIds[e.tree.rootId]??[];return c.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>c.jsx(wl,{nodeId:n,path:CM(e,n)},n)),c.jsx(Wg,{parentId:e.tree.rootId})]})}function CM(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 wl({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Qt(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return c.jsx(NM,{node:s,path:t});if(s.type==="array")return c.jsx(AM,{node:s,path:t});const o=r[s.type]?.Edit;if(!o)return null;const a=s.touched?s.error:void 0;return c.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":a?"":void 0,onBlur:()=>n.touch(s.id),children:[c.jsx(vl,{node:s,path:t}),c.jsx(o,{value:s.value,path:t,error:a,onChange:l=>n.setValue(s.id,l)})]})}function vl({node:e,path:t}){const{editor:n}=Qt(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:c.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?c.jsx("input",{type:"text",value:e.key??"",onChange:o=>n.setKey(e.id,o.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,c.jsx(RM,{node:e}),c.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const IM=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function RM({node:e}){const{editor:t}=Qt(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=IM.filter(s=>!(n?.type==="array"&&s==="array"));return c.jsx("select",{value:e.type,onChange:s=>t.setType(e.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>c.jsx("option",{value:s,children:s},s))})}function NM({node:e,path:t}){const{editor:n}=Qt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":e.key??void 0,children:[e.id!==n.tree.rootId?c.jsx(vl,{node:e,path:t}):null,c.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const o=t?`${t}.${i.key??""}`:i.key??"";return c.jsx(wl,{nodeId:s,path:o},s)})}),c.jsx(Wg,{parentId:e.id})]})}function AM({node:e,path:t}){const{editor:n}=Qt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[c.jsx(vl,{node:e,path:t}),c.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const o=t?`${t}[${i}]`:`[${i}]`;return c.jsx("li",{"data-field-index":String(i),children:c.jsx(wl,{nodeId:s,path:o})},s)})}),c.jsx(OM,{parentId:e.id})]})}function Wg({parentId:e}){const{editor:t}=Qt();return c.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function OM({parentId:e}){const{editor:t}=Qt();return c.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Of={Root:EM,Fields:jM};function $M({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):c.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(o=>c.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":o.id,children:c.jsx("button",{type:"button",onClick:()=>r?.(o),"data-pyric-collection-select":!0,children:o.id})},o.path))})}const lr=new Map;function xl({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=y.useRef(null),o=y.useRef(new Map),a=y.useRef(new Map),[l,u]=y.useState(lr);return y.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(lr)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(lr);return}const h=new Map;for(const[f,p]of t){const m=d.entries.has(f),g=d.entries.get(f);if(m&&n(g,p))continue;const b=o.current.get(f)===0?1:0;o.current.set(f,b),h.set(f,{kind:m?"modified":"added",cycle:b})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let m=h.size>0;for(const g of f.keys())t.has(g)||(p.delete(g),m=!0);for(const[g,b]of h)p.set(g,b);return m?p.size===0?lr:p:f});for(const[f,p]of h){const m=a.current.get(f);m&&clearTimeout(m);const g=setTimeout(()=>{a.current.delete(f),u(b=>{if(b.get(f)?.cycle!==p.cycle)return b;const w=new Map(b);return w.delete(f),w.size===0?lr:w})},r);a.current.set(f,g)}},[r,t,n,s,e]),y.useEffect(()=>()=>{for(const d of a.current.values())clearTimeout(d);a.current.clear()},[]),l}function ur(e){return e.ref}function PM({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:o,renderRowAction:a,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const m=y.useMemo(()=>new Map(e.map(w=>[ur(w).path,w.data()])),[e]),g=xl({scope:d,entries:m,equals:Ni,ready:!t});if(n)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const b=e.length>h;return c.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":b?"":void 0,children:[b?c.jsx(fl,{items:e,estimateSize:f,height:p,getItemKey:w=>ur(w).path,renderItem:w=>{const x=g.get(ur(w).path);return c.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(ur(w)),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]})}}):c.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(w=>{const x=ur(w),v=g.get(x.path);return c.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(x),"data-pyric-document-select":!0,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]},x.path)})}),r&&i?c.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const DM=/^__.*__$/;function zg(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(DM.test(e))return"Cannot match __.*__ (reserved)";if(MM(e)>1500)return"Cannot exceed 1500 bytes"}function TM(e){return zg(e)}function MM(e){return new TextEncoder().encode(e).length}function LM(e){return zg(e)}const $f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function UM(){let e="";for(let t=0;t<20;t++)e+=$f.charAt(Math.floor(Math.random()*$f.length));return e}const BM={ref:Mr,listAll:Jc,getMetadata:AC,getBlob:NC,uploadBytes:IC,uploadBytesResumable:RC,deleteObject:ym},Hg=y.createContext(BM);function eo(){return y.useContext(Hg)}function FM({value:e,children:t}){return y.createElement(Hg.Provider,{value:e},t)}function Go(e){return e.replace(/^\/+|\/+$/g,"")}function uc(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function Jo(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(uc)}function qM(e,t){const{listAll:n,ref:r}=eo(),s=Go(t),[i,o]=y.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[a,l]=y.useState(0),u=y.useRef(new Map);y.useEffect(()=>{if(u.current.clear(),e==null){o({status:"idle",items:[],prefixes:[],error:void 0});return}let m=!1;return o({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{m||o({status:"success",items:[...g.items].sort(uc),prefixes:[...g.prefixes].sort(uc),error:void 0})}).catch(g=>{m||o({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{m=!0}},[e,s,a]);const d=y.useCallback(()=>l(m=>m+1),[]),h=y.useCallback(m=>{if(e==null)return;const g=m.endsWith("/"),b=Go(m),w=s===""?"":`${s}/`;if(!b.startsWith(w)||b===s)return;const x=b.slice(w.length),v=x.indexOf("/");o(_=>{if(_.status==="idle")return _;if(v===-1)return g?(u.current.set(b,_.prefixes.some(k=>k.fullPath===b)?null:b),{..._,prefixes:Jo(_.prefixes,r(e,b))}):(u.current.set(b,_.items.some(k=>k.fullPath===b)?null:b),{..._,items:Jo(_.items,r(e,b))});const S=`${w}${x.slice(0,v)}`;return u.current.set(b,_.prefixes.some(k=>k.fullPath===S)?null:S),{..._,prefixes:Jo(_.prefixes,r(e,S))}})},[e,s]),f=y.useCallback(m=>{const g=Go(m),b=u.current.get(g);if(u.current.delete(g),b===null)return;const w=b??g;o(x=>({...x,items:x.items.filter(v=>v.fullPath!==w),prefixes:x.prefixes.filter(v=>v.fullPath!==w)}))},[]),p=y.useMemo(()=>[...i.prefixes.map(m=>({kind:"folder",name:m.name,fullPath:m.fullPath,ref:m})),...i.items.map(m=>({kind:"object",name:m.name,fullPath:m.fullPath,ref:m}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:h,removeItem:f}}function de(e){return e.split("/").filter(Boolean).join("/")}function VM(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,o]=y.useState(()=>de(r)),a=s?de(t):i,l=y.useCallback(p=>{const m=de(p);s||o(m),n?.(m)},[s,n]),u=y.useMemo(()=>a===""?[]:a.split("/"),[a]),d=y.useCallback(p=>{const m=de(p);l(m.includes("/")||a===""?m:`${a}/${m}`)},[a,l]),h=y.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=y.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:a,segments:u,setPath:l,enter:d,up:h,navigateToIndex:f}}const Pf={status:"idle",blob:void 0,url:void 0,error:void 0};function WM(e,t){const{getBlob:n,getMetadata:r,ref:s}=eo(),i=t==null?null:de(t),o=e!=null&&i!=null&&i!=="",[a,l]=y.useState(()=>({status:o?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=y.useState(Pf),[h,f]=y.useState(0),p=y.useRef(0);y.useEffect(()=>{if(p.current++,d(Pf),!o){l({status:"idle",metadata:void 0,error:void 0});return}let w=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(x=>{w||l({status:"success",metadata:x,error:void 0})}).catch(x=>{w||l({status:"error",metadata:void 0,error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[e,i,h]);const m=u.url;y.useEffect(()=>{if(m!==void 0)return()=>{URL.revokeObjectURL(m)}},[m]);const g=y.useCallback(()=>f(w=>w+1),[]),b=y.useCallback(()=>{if(e==null||i==null||i==="")return;const w=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(x=>{w===p.current&&d({status:"success",blob:x,url:URL.createObjectURL(x),error:void 0})}).catch(x=>{w===p.current&&d({status:"error",blob:void 0,url:void 0,error:x instanceof Error?x:new Error(String(x))})})},[e,i]);return{status:a.status,metadata:a.metadata,error:a.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:b}}function zM(){const[e,t]=y.useState(()=>new Map),n=y.useCallback(u=>e.has(u),[e]),r=y.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const h=new Map(d);return h.set(u.fullPath,u),h})},[]),s=y.useCallback(u=>{t(d=>{if(!d.has(u))return d;const h=new Map(d);return h.delete(u),h})},[]),i=y.useCallback(u=>{t(d=>{const h=new Map(d);return h.has(u.fullPath)?h.delete(u.fullPath):h.set(u.fullPath,u),h})},[]),o=y.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),a=y.useCallback(()=>t(new Map),[]);return{selected:y.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:o,clear:a}}function HM(e,t){const n=Mr(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function KM(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function GM(e){return{async*start(t){const n=e??{listAll:Jc,deleteObject:ym};let r=0;const s=[t],i=[];for(;s.length>0;){const o=s.pop();i.push(o);const a=await n.listAll(o);s.push(...a.prefixes);for(const l of a.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const o of i)try{await n.deleteObject(KM(o))}catch{}yield{deletedCount:r,done:!0}}}}function JM(e,t={}){const n=eo(),[r,s]=y.useState(0),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(0),d=y.useRef(t);return d.current=t,{deleteEntries:y.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const m={deleted:[],failed:[]};if(e==null||f.length===0)return m;o(!0);const g=d.current.impl??GM(n);let b=0;try{for(const w of f){d.current.list?.removeItem(w.fullPath);try{if(w.kind==="object")await n.deleteObject(n.ref(e,w.fullPath)),b++;else for await(const x of g.start(n.ref(e,w.fullPath))){if(p!==u.current)return m;if(s(b+x.deletedCount),x.done){b+=x.deletedCount;break}}m.deleted.push(w.fullPath),p===u.current&&s(b)}catch(x){const v=x instanceof Error?x:new Error(String(x));m.failed.push({fullPath:w.fullPath,error:v}),d.current.list?.insertItem(w.kind==="folder"?`${w.fullPath}/`:w.fullPath),p===u.current&&m.failed.length===1&&l(v)}}return m}finally{p===u.current&&o(!1)}},[n,e]),progress:r,isRunning:i,error:a}}const YM=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),QM=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 XM(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,o=e==null?null:e[Bi],[a,l]=y.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));y.useEffect(()=>{if(o==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const x=typeof r=="string"?xa(r):r;l({status:"ready",rules:x,source:"option",error:void 0})}catch(x){l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}return}let w=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),o.servicePromise.then(x=>{w||l({status:"ready",rules:x.rules,source:x.rules?"sandbox":"none",error:void 0})}).catch(x=>{w||l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[o,r]);const u=s!==void 0?s:o?.context.auth??null,{rules:d,status:h}=a,f=i?.size,p=i?.contentType,m=y.useCallback(w=>{if(d==null)return h==="ready"?QM:YM;const x=de(w),v=o?.bucket??"pyric-default",_=x===""?`b/${v}/o`:`b/${v}/o/${x}`,S=R=>cm(d,{request:{auth:u,method:R,path:_,...R==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),k=S("read"),I=S("create"),O=S("delete"),P=I;return{read:k.allowed,write:P.allowed,delete:O.allowed,upload:I.allowed,reasons:{read:k.allowed?[]:k.reasons,write:P.allowed?[]:P.reasons}}},[d,h,o?.bucket,u,f,p]),g=typeof n=="string"?n:(n??[]).join(`
|
|
145
|
+
`),b=y.useMemo(()=>{const w=typeof n=="string"?[n]:n??[],x={};for(const v of w)x[de(v)]=m(v);return x},[g,m]);return{status:h,source:a.source,advisory:!1,identity:u,verdicts:b,verdictFor:m,error:a.error}}function Df(e,t){return e===""?t:t===""?e:`${e}/${t}`}function ZM(e){return e instanceof Blob?e.size:e.byteLength}function eL(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function tL(e,t={}){const{ref:n,uploadBytes:r}=eo(),s=de(t.path??""),[i,o]=y.useState([]),a=y.useRef(t);a.current=t;const l=y.useCallback(f=>{o(p=>p.map(m=>m.id===f.id?f:m))},[]),u=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=(Array.isArray(f)?f:[f]).map(g=>{const b=eL(g);return{task:{id:crypto.randomUUID(),fullPath:Df(s,de(b.path)),status:"running",bytesTransferred:0,totalBytes:ZM(b.data)},entry:b}});o(g=>[...g,...m.map(b=>b.task)]);for(const{task:g}of m)a.current.list?.insertItem(g.fullPath),a.current.onProgress?.(g);return Promise.all(m.map(async({task:g,entry:b})=>{try{const w=await r(n(e,g.fullPath),b.data,b.metadata),x={...g,status:"success",bytesTransferred:g.totalBytes,metadata:w.metadata};return l(x),a.current.onProgress?.(x),a.current.onComplete?.(x),x}catch(w){const x={...g,status:"error",error:w instanceof Error?w:new Error(String(w))};return a.current.list?.removeItem(g.fullPath),l(x),a.current.onError?.(x),x}}))},[e,s,l,n,r]),d=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=Df(s,de(f));if(p==="")throw new Error("createFolder: folder name is empty");a.current.list?.insertItem(`${p}/`);try{await r(HM(e,p),new Blob([]),{contentType:"text/plain"})}catch(m){throw a.current.list?.removeItem(p),m}},[e,s,r]),h=y.useCallback(()=>{o(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:h}}function nL({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=de(e),o=i===""?[]:i.split("/");return c.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:c.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[c.jsx("li",{"data-pyric-breadcrumb-item":!0,children:c.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":o.length===0?"":void 0,"aria-current":o.length===0?"page":void 0,children:n})}),o.map((a,l)=>{const u=l===o.length-1,d=o.slice(0,l+1).join("/");return c.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),c.jsx("button",{type:"button",onClick:()=>t?.(d),"data-pyric-breadcrumb-link":!0,"data-pyric-current":u?"":void 0,"aria-current":u?"page":void 0,children:a})]},d)})]})})}function rL({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:o,renderEntry:a,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:m,size:g}=Zi();if(n)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((t==="loading"||t==="idle")&&e.length===0)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-loading":t==="loading"?"":void 0,"data-pyric-idle":t==="idle"?"":void 0});if(e.length===0)return c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const b=v=>{if(!o)return{denied:!1};const _=o.verdictFor(v.fullPath);return _.read?{denied:!1}:{denied:!0,reason:_.reasons.read.join("; ")}},w=v=>{const _=v.kind==="object"&&v.fullPath===i;return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:()=>v.kind==="folder"?r?.(v.fullPath):s?.(v.ref),"data-pyric-entry-select":!0,"data-pyric-selected":_?"":void 0,"aria-selected":_||void 0,children:a?a(v):v.name}),l?c.jsx("span",{"data-pyric-storage-action":!0,children:l(v)}):null]})},x=e.length>h;return c.jsx("div",{ref:m,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":x?"":void 0,children:x?c.jsx(fl,{items:e,estimateSize:f,height:p,getItemKey:v=>`${v.kind}:${v.fullPath}`,renderItem:v=>{const _=b(v);return c.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)})}}):c.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(v=>{const _=b(v);return c.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)},`${v.kind}:${v.fullPath}`)})})})}async function Kg(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,o)=>e.file(i,o));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((o,a)=>s.readEntries(o,a));if(i.length===0)break;for(const o of i)await Kg(o,r,n)}}}async function sL(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 Kg(i,"",t);else{const o=r.getAsFile?.();o&&t.push({file:o,relativePath:o.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function iL({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,o]=y.useState(!1),a=y.useRef(0),l=y.useCallback(f=>{f.preventDefault(),!n&&(a.current+=1,o(!0))},[n]),u=y.useCallback(f=>{f.preventDefault()},[]),d=y.useCallback(f=>{f.preventDefault(),!n&&(a.current=Math.max(0,a.current-1),a.current===0&&o(!1))},[n]),h=y.useCallback(f=>{if(f.preventDefault(),a.current=0,o(!1),n)return;const p=f.dataTransfer;p&&sL(p).then(m=>{m.length>0&&e(m)})},[n,e]);return c.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":i?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:l,onDragOver:u,onDragLeave:d,onDrop:h,children:t})}function oL(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 aL(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 Tf(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=oL(e),{base:s,counter:i}=aL(n);let o=i===null?1:i+1;for(;;){const a=`${s} (${o})${r}`;if(!t.has(a))return a;o+=1}}function cL(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=Tf(s,n);return n.add(l),l}const o=s.slice(0,i);let a=r.get(o);return a===void 0&&(a=Tf(o,n),n.add(a),r.set(o,a)),`${a}${s.slice(i)}`})}function Mf(e){const t=de(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Gg=[];function lL(e,t){switch(t.type){case"create":{const n=Mf(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Mf(t.path));if(n.size===0)return e;const r=e.filter(s=>!n.has(s));return r.length===e.length?e:r}case"discard":{const n=de(t.path);if(n==="")return e;const r=e.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===e.length?e:r}case"clear":return e.length===0?e:Gg}}function uL(e,t){const n=de(t),r=n===""?"":`${n}/`;return e.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function Lf(e,t){return e.includes(de(t))}function dL(e){const t=de(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const fL=256*1024;function dc(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const hL={id:"image",match:e=>dc(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?c.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function pL({blob:e,isJson:t}){const[n,r]=y.useState(void 0);return y.useEffect(()=>{let s=!1;return e.text().then(i=>{if(!s){if(t)try{r(JSON.stringify(JSON.parse(i),null,2));return}catch{}r(i)}}),()=>{s=!0}},[e,t]),n===void 0?null:c.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const mL={id:"text",match:e=>{const t=dc(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:fL,render:({metadata:e,blob:t})=>t?c.jsx(pL,{blob:t,isJson:dc(e)==="application/json"}):null},yL=[hL,mL];function gL(e,t){for(const n of[...t??[],...yL])if(n.match(e))return n}const bL=[{key:"fullPath",label:"Path",value:e=>e.fullPath},{key:"size",label:"Size",value:e=>`${e.size}`},{key:"contentType",label:"Content type",value:e=>e.contentType},{key:"cacheControl",label:"Cache control",value:e=>e.cacheControl},{key:"timeCreated",label:"Created",value:e=>e.timeCreated},{key:"updated",label:"Updated",value:e=>e.updated}];function wL({metadata:e}){return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[bL.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":t,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[c.jsx("dt",{children:t}),c.jsx("dd",{children:n})]},`custom:${t}`))]})}function vL({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:o,size:a}=Zi(),l=WM(e,t),{metadata:u,blobStatus:d,loadBlob:h}=l,f=u?gL(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,m=f?.needsBlob===!0&&!p;if(y.useEffect(()=>{m&&d==="idle"&&h()},[m,d,h]),l.status==="idle")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,b={};return f===void 0?b={"data-pyric-preview-none":""}:p?b={"data-pyric-preview-too-large":""}:m&&d==="loading"?b={"data-pyric-preview-loading":""}:m&&d==="error"?(b={"data-pyric-preview-error":""},g=l.blobError?.message):(!m||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),c.jsxs("div",{ref:o,className:i,"data-pyric-ui":"object-inspector","data-size":a,children:[c.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):c.jsx(wL,{metadata:u}),c.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...b,children:g}),s]})}const Jg=y.createContext(null);function xL(){const e=y.useContext(Jg);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function _L({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=y.useState([]),o=y.useCallback(u=>{i(d=>d.filter(h=>h.id!==u))},[]),a=y.useCallback(u=>{const d=crypto.randomUUID(),h=u.duration??t;return i(f=>[...f,{id:d,...u}]),h>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},h),d},[t]),l=y.useMemo(()=>({toast:a,dismiss:o,toasts:s}),[a,o,s]);return c.jsxs(Jg.Provider,{value:l,children:[e,c.jsx(SL,{toasts:s,dismiss:o,className:n,regionLabel:r})]})}function SL({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=y.useState(!1);return y.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:dl.createPortal(c.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(o=>c.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":o.kind??"info",role:o.kind==="error"?"alert":"status",children:[c.jsx("div",{"data-pyric-toast-title":!0,children:o.title}),o.body?c.jsx("div",{"data-pyric-toast-body":!0,children:o.body}):null,c.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(o.id),children:"×"})]},o.id))}),document.body)}function kL({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:o,confirmLabel:a="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:h}){const f=Yn(),{toast:p}=xL(),{deleteEntries:m,isRunning:g,progress:b}=JM(e,{impl:n,list:r}),w=s?t.map(S=>({entry:S,verdict:s.verdictFor(S.fullPath)})).filter(S=>!S.verdict.delete):[],x=w.length===0?void 0:`Delete denied for ${w[0].entry.fullPath}${w.length>1?` (+${w.length-1} more)`:""}: ${w[0].verdict.reasons.write.join("; ")}`,v=g||t.length===0||e==null||w.length>0,_=async()=>{if(v||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:o??c.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(I=>c.jsxs("li",{"data-pyric-entry-kind":I.kind,children:[I.fullPath,I.kind==="folder"?"/":""]},I.fullPath))}),destructive:!0,confirmLabel:a}))return;const k=await m(t);k.failed.length===0?(p({title:`Deleted ${k.deleted.length} ${k.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(k)):(p({title:`Delete failed for ${k.failed.length} of ${t.length}`,kind:"error",body:c.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:k.failed.map(I=>c.jsxs("li",{children:[I.fullPath,":"," ",I.error.code??I.error.message]},I.fullPath))})}),u?.(k))};return d?c.jsx(c.Fragment,{children:d({onClick:_,isRunning:g,progress:b,disabled:v,deniedReason:x})}):c.jsx("button",{type:"button",onClick:_,className:h,disabled:v,title:x,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":x?"":void 0,"data-pyric-denied-reason":x,children:g?`Deleting… (${b})`:a})}function Qr(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 Yg(e){const t=e.indexOf("?");return al(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function EL(e){const{tab:t,rest:n,query:r}=Yg(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:Qr(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 Qg(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 Xg(e){const{tab:t,query:n}=Yg(e),r=EL(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Uf=null,fc=Xg("");function jL(){const e=cl();return e!==Uf&&(Uf=e,fc=Xg(e)),fc}function CL(){return fc}function Ms(e){Ae(Qg(e))}function IL(e){Ae({tab:"traffic",query:{inspect:e}})}function to(){const e=y.useSyncExternalStore(Jt,jL,CL),t=y.useCallback(s=>Ms(s),[]),n=y.useCallback(s=>{switch(s.kind){case"user":Ms({view:"auth",uid:s.uid});break;case"storage":Ms({view:"storage",kind:"object",path:s.objectPath});break;case"document":Ms({view:"firestore",path:Qr(s.path)});break}},[]),r=y.useCallback(s=>IL(s),[]);return y.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const RL={narrowBreakpoint:640,mediumBreakpoint:920};function NL(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function AL(e,t){const n=NL(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 Yo({label:e,error:t,hint:n,children:r}){return c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:e}),r,t?c.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?c.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function Zg({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=y.useState(""),[o,a]=y.useState(()=>UM()),[l,u]=y.useState(null),[d,h]=y.useState(null),[f,p]=y.useState(!1),m=y.useRef(null),g=e==="collection"&&s?TM(s):void 0,b=o?LM(o):void 0,x=!(e==="collection"&&(!s||g))&&!!o&&!b&&!f;y.useEffect(()=>{const S=k=>{k.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f,r]);const v=async()=>{if(!(!x||!l)){if(!l.isValid){l.touchAll();return}p(!0),h(null);try{await n({collectionId:e==="collection"?s:null,docId:o,data:Pg(l.tree)}),r()}catch(S){h(S instanceof Error?S:new Error(String(S))),p(!1)}}},_=e==="collection"?"Start a collection":"Add a document";return c.jsx("div",{className:"fs-modal-backdrop",onMouseDown:S=>{S.target===S.currentTarget&&!f&&r()},children:c.jsxs("div",{ref:m,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":_,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[c.jsx("h2",{className:"fs-modal__title",children:_}),c.jsx(Yo,{label:"Parent path",children:c.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?c.jsx(Yo,{label:"Collection ID",error:g,children:c.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:S=>i(S.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,c.jsx(Yo,{label:"Document ID",error:o?b:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:c.jsx("input",{autoFocus:e==="document",type:"text",value:o,onChange:S=>a(S.target.value),"data-pyric-field":"doc-id","aria-invalid":b||!o?"true":void 0})}),c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:"Fields"}),c.jsx("div",{className:"fs-modal__fields",children:c.jsx(Of.Root,{initial:{},onChange:u,children:c.jsx(Of.Fields,{})})})]}),d?c.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,c.jsxs("div",{className:"fs-modal__actions",children:[c.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),c.jsx("button",{type:"button",className:"fs-editor__save",disabled:!x,onClick:()=>void v(),children:f?"Saving…":"Save"})]})]})})}function eb({items:e,label:t="More actions"}){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useRef(null),a=()=>{if(!n){const l=o.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return y.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),o.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),c.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[c.jsx("button",{ref:o,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:a,children:c.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),c.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>c.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":l.destructive?"":void 0,disabled:l.disabled,onClick:()=>{r(!1),l.onSelect()},children:l.label},l.label))})]}):null]})}function tb(e){return JSON.stringify(e)}function OL(e,t){const n=new Map,r=(s,i)=>{const o=t(s),a=tb(i);if(o==="map"){const l=s,u=Object.keys(l).sort();n.set(a,[o,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(o==="array"){const l=s;n.set(a,[o,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(a,[o,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function nb(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 tb(n)}function $L(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 PL(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 Bf(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 DL=42;function TL(e,t,n,r=DL){const s=e.nodes[t],i=e.childIds[t]??[];let o;return s.type==="array"?o=`[${i.slice(0,3).map(l=>Bf(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:o=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${Bf(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,o.length>r?`${o.slice(0,r-1)}…`:o}function ML(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function LL(e){return e.shiftKey===!0}const rb=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],UL=[...rb,"map","array"];function BL({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:o,onStartCollection:a,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const h=y.useMemo(()=>e?.data()??{},[e]),f=y.useMemo(()=>h,[]),p=Ug({initial:f}),m=p.replaceData,g=y.useMemo(()=>qg(i),[i]),b=Yn(),[w,x]=y.useState(()=>new Set),[v,_]=y.useState(null),S=y.useRef(e),k=y.useRef(new Set),I=y.useRef(!1),[O,P]=y.useState(null),R=y.useMemo(()=>OL(h,Xi),[h]),E=xl({scope:t.path,entries:R,equals:Ni,ready:v===null});y.useEffect(()=>{I.current&&(I.current=!1,P(null),n(p.toData()).catch(U=>{P(U instanceof Error?U:new Error(String(U)))}))},[p.tree]),y.useEffect(()=>{!e||e===S.current||v!==null||(S.current=e,k.current.clear(),m(e.data()??{}))},[v,m,e]);const j=y.useCallback(U=>{x(V=>{const F=new Set(V);return F.has(U)?F.delete(U):F.add(U),F})},[]),[$,C]=y.useState(null),N=y.useCallback((U,V)=>{if(V==="map"?p.addMapEntry(U,"","string"):p.addArrayEntry(U,"string"),U!==p.tree.rootId){const F=nb(p.tree,U);x(Se=>new Set(Se).add(F))}C(U)},[p]);y.useEffect(()=>{if(!$)return;const U=p.tree.childIds[$]??[],V=U[U.length-1];V&&!v&&(k.current.add(V),_(V),C(null))},[p.tree,$]);const A=y.useCallback(U=>{p.remove(U),k.current.delete(U),I.current=!0,v===U&&_(null)},[p,v]),D=y.useCallback(async(U,V,F)=>{if(LL(F)){A(U.id);return}await b({title:`Delete field "${V}"?`,destructive:!0,confirmLabel:"Delete"})&&A(U.id)},[b,A]),T=t.id,W=p.tree.childIds[p.tree.rootId]??[];return c.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[c.jsxs("div",{className:"fs-doctree__head",children:[c.jsx("span",{className:"fs-doctree__docid",children:T}),c.jsx(eb,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await b({title:"Delete all fields?",body:"The document itself is kept, empty.",destructive:!0,confirmLabel:"Delete fields"})&&s())()},destructive:!0},{label:"Delete document",onSelect:r,destructive:!0}]})]}),O?c.jsx("p",{className:"fs-doctree__err",children:O.message}):null,c.jsxs("ul",{className:"fs-doctree__rows",children:[a?c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:a,children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>N(p.tree.rootId,"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(U=>c.jsx(sb,{nodeId:U,depth:0,editor:p,registry:g,expanded:w,onToggle:j,editingId:v,setEditingId:_,newIdsRef:k,onAdd:N,onDelete:D,onCommitNeeded:()=>{I.current=!0},onReferenceClick:o,updates:E},U))]}),l&&u?c.jsx(ib,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function sb({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p}){const{tree:m}=n,g=m.nodes[e];if(!g)return null;const{label:b,isArrayChild:w}=PL(m,e),x=g.type==="map"||g.type==="array",v=$L(m,e),_=nb(m,e),S=p.get(_),k=s.has(_),I=o===e,O=l.current.has(e);return I?c.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:c.jsx(FL,{node:g,isNew:O,isArrayChild:w,tree:m,editor:n,registry:r,path:v,onCommitNeeded:h,onDone:()=>{l.current.delete(e),a(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),a(null)}})}):c.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":x?"":void 0,style:{"--fs-depth":t},children:[c.jsxs("div",{className:"fs-doctree__line","data-pyric-update":S?.kind,"data-pyric-update-cycle":S?.cycle,children:[x?c.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":k,onClick:()=>i(_),children:c.jsx("span",{"aria-hidden":"true",children:k?"▼":"▶"})}):c.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),w?c.jsx("span",{className:"fs-doctree__chip",children:b}):c.jsx("span",{className:"fs-doctree__key",children:b}),x?k?null:c.jsx("span",{className:"fs-doctree__preview",children:TL(m,e,{asVectorView:wn,vectorPreview:Og})}):c.jsx("span",{className:"fs-doctree__value",children:c.jsx(lc,{value:g.value,path:v,fieldEditors:r})}),c.jsxs("span",{className:"fs-doctree__hover",children:[c.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),x?c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${b||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${b}`,onClick:()=>a(e),children:"✎"}),c.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${b||"field"} (shift-click to skip confirmation)`,onClick:P=>void d(g,b,{shiftKey:P.shiftKey}),children:"🗑"})]})]}),x&&k?c.jsxs("ul",{className:"fs-doctree__children",children:[(m.childIds[e]??[]).map(P=>c.jsx(sb,{nodeId:P,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p},P)),c.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function FL({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:o,onCommitNeeded:a,onDone:l,onCancelNew:u}){const[d,h]=y.useState(e.key??""),[f,p]=y.useState(e.type),[m,g]=y.useState(e.value),[b,w]=y.useState(!1),x=n?void 0:d===""?"Field name is required":ML(r,e,d)?"Field name must be unique":void 0,v=f==="map"||f==="array"?void 0:Tg(f,m),_=!x&&!v,S=()=>{if(!_){w(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,m),a(),l()},k=()=>{t?u():l()},O=i[f]?.Edit,P=f!=="map"&&f!=="array"&&O?c.jsx(O,{value:m,path:o,error:b?v:void 0,onChange:j=>g(j)}):f==="map"||f==="array"?c.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,R=c.jsxs("span",{className:"fs-doctree__editactions",children:[c.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:S,"aria-label":"Save field",children:"✓"}),c.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:k,"aria-label":"Cancel edit",children:"✕"})]}),E=c.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:j=>{const $=j.target.value;p($),$!=="map"&&$!=="array"&&$!==f&&g(qL($))},"aria-label":"Field type",children:(t?UL:rb).map(j=>c.jsx("option",{value:j,children:j},j))});return c.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:j=>{j.key==="Enter"&&!j.target.matches("textarea")?(j.preventDefault(),S()):j.key==="Escape"&&(j.preventDefault(),k())},children:[n?null:c.jsxs("div",{className:"fs-doctree__editline",children:[c.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:j=>h(j.target.value),onBlur:()=>w(!0),"aria-label":"Field name","aria-invalid":b&&x?"true":void 0}),E]}),c.jsxs("div",{className:"fs-doctree__editline",children:[n?E:null,P,R]}),b&&x?c.jsx("span",{className:"fs-doctree__editerr",children:x}):null]})}function qL(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function ib({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=qT({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:c.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[c.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),c.jsx("ul",{className:"fs-doctree__sublist",children:s.map(o=>c.jsx("li",{children:r?c.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(o),"aria-label":`Open subcollection ${o.id}`,children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),c.jsx("span",{"aria-hidden":"true",children:"›"})]}):c.jsxs("div",{className:"fs-doctree__subrow",children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},o.path))})]})}function VL(e){return e.split("/").filter(Boolean).length%2===0}function ob(e,t){async function*n(s,i,o=!1){const a=await t.listSubcollections(s.path);for(const l of a)yield*r(e.collection(s,l),i);o||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const o=await t.listDocuments(s.path);for(const a of o){const l=a.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,a.phantom===!0))}}return{async*start(s){const i={n:0};VL(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function ab(e,t){for await(const n of e.start(t))if(n.done)return}async function cb({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:c.jsxs("label",{className:"fs-delete-recursive",children:[c.jsx("input",{type:"checkbox",onChange:o=>{s=o.currentTarget.checked}}),c.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await ab(r,t):await n.deleteDoc(t),!0):!1}function WL(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function zL(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 HL(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function Ff(e){return e.__pyricPhantom===!0}function KL(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 GL({handles:e}){const{target:t,navigate:n}=to(),r=e.adminFirestore,s=ml(),i=y.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),o=y.useCallback(_=>{const S=typeof _=="function"?_(i):_;n({view:"firestore",path:S})},[n,i]),a=(_,S)=>o(k=>[...k.slice(0,_+1),S]),[l,u]=y.useState(null),d=y.useCallback(async({collectionId:_,docId:S,data:k})=>{if(!l||!_)return;const I=l.parentDocPath,O=I?s.collection(s.doc(r,I),_):s.collection(r,_);await zL(s,O,S,k);const P=I?`${I}/${_}`:_;n({view:"firestore",path:Qr(`${P}/${S}`)})},[s,r,l,n]),h=[c.jsx(QL,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:_=>o([{kind:"collection",id:_,path:_}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((_,S)=>_.kind==="collection"?c.jsx(XL,{api:s,firestore:r,handles:e,collectionPath:_.path,selectedId:i[S+1]?.id??null,onSelect:k=>a(S,{kind:"document",id:k.id,path:k.path}),onCollectionDeleted:()=>o(k=>k.slice(0,S))},_.path):c.jsx(ZL,{api:s,firestore:r,handles:e,docPath:_.path,onOpenSubcollection:k=>a(S,{kind:"collection",id:k.id,path:k.path}),onReferenceClick:k=>n({view:"firestore",path:Qr(k.path)}),onStartCollection:()=>u({parentDocPath:_.path}),onDeleted:()=>o(k=>k.slice(0,S))},_.path))],{ref:f,size:p}=Zi(RL),{startIndex:m,visibleCount:g,emptySlots:b}=AL(h.length,p),w=h.slice(m,m+g),x=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,v=[...w,...Array.from({length:b},(_,S)=>c.jsx(YL,{hint:S===0?x:null},`__empty_${S}__`))];return y.useEffect(()=>{if(p==="wide")return;const _=f.current;if(!_)return;const S=document.activeElement;if(S&&S!==document.body&&_.contains(S))return;const k=_.querySelector(".fs-columns > .fs-col:last-child");k&&(k.tabIndex=-1,k.focus({preventScroll:!0}))},[i.length,p]),c.jsx(hl,{children:c.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[c.jsx(JL,{path:i,onHome:()=>o([]),onJump:_=>o(S=>S.slice(0,_+1))}),c.jsx("div",{className:"fs-columns",children:v}),l?c.jsx(Zg,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function JL({path:e,onHome:t,onJump:n}){return c.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[c.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>c.jsxs(y.Fragment,{children:[c.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?c.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):c.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function YL({hint:e}){return c.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?c.jsx("p",{className:"fs-empty",children:e}):null})}function QL({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=y.useMemo(()=>n.map(o=>e.collection(t,o)),[e,t,n]);return c.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:"Collections"}),c.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),c.jsx($M,{collections:i,onSelect:o=>r(o.id),emptyState:c.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function XL({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:o}){const a=y.useMemo(()=>KL(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:h,hasMore:f,loadMore:p,createDocument:m}=FT({collection:a,mode:"live"}),[g,b]=y.useState([]);y.useEffect(()=>{let E=!1;return Promise.resolve(n.listDocuments(r)).then(j=>{E||b(j.filter($=>$.phantom).map($=>$.path.split("/").pop()??""))}).catch(()=>{E||b([])}),()=>{E=!0}},[n,r,l]);const w=y.useMemo(()=>{const E=new Set(l.map(j=>j.id));return[...l,...g.filter(j=>j.length>0&&!E.has(j)).map(j=>HL(e.doc(t,`${r}/${j}`)))]},[l,g,e,t,r]),x=r.split("/").pop()??r,[v,_]=y.useState(null),[S,k]=y.useState(!1),I=Yn(),O=y.useMemo(()=>ob(e,n),[e,n]),P=y.useCallback(async E=>{_(null);try{await cb({confirm:I,ref:E,api:e,recursiveImpl:O})}catch(j){_(j instanceof Error?j:new Error(String(j)))}},[e,I,O]),R=y.useCallback(async()=>{if(await I({title:`Delete collection "${x}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){_(null);try{await ab(O,a),o()}catch(j){_(j instanceof Error?j:new Error(String(j)))}}},[I,O,a,x,o]);return c.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:x}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:()=>k(!0),children:"+ New"})}),c.jsx(eb,{items:[{label:"Delete collection",onSelect:()=>void R(),destructive:!0}]})]}),S?c.jsx(Zg,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:E,data:j})=>{const $=await m(E,j,{onExisting:"fail"});i($)},onClose:()=>k(!1)}):null,c.jsx(PM,{documents:w,isLoading:u,error:d,updateScope:`${r}:${h}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:E=>{const j=E.ref;return c.jsx("span",{"data-pyric-selected":s===j.id?"":void 0,style:{display:"contents"},children:Ff(E)?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"fs-doc-phantom",children:E.id}),c.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):E.id})},renderRowAction:E=>{if(Ff(E))return null;const j=E.ref;return c.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${j.id}`,onClick:$=>{$.stopPropagation(),P(j)},children:"×"})},emptyState:c.jsx("p",{className:"fs-empty",children:"No documents."})}),v?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:v.message}):null]})}function ZL({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:o,onDeleted:a}){const l=y.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:h}=RT(l),f=y.useCallback(async(_,S)=>(await n.listSubcollections(S.path)).map(I=>e.collection(S,I)),[n,e]),p=Yn(),m=y.useMemo(()=>ob(e,n),[e,n]),[g,b]=y.useState(null),w=y.useCallback(async()=>{b(null);try{await cb({confirm:p,ref:l,api:e,recursiveImpl:m})&&a()}catch(_){b(_ instanceof Error?_:new Error(String(_)))}},[e,p,m,l,a]),x=y.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),v=u!=null&&WL(u);return c.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[v?null:c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:l.id}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:o,children:"+ Collection"})})]}),u&&v?c.jsx(BL,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:o,onDeleteDocument:()=>void w(),onDeleteDocumentFields:x,onCommit:async _=>{await e.setDoc(l,_)}},r):d?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):h?c.jsx("p",{className:"fs-empty",children:"Loading document…"}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"fs-empty",children:"This document does not exist."}),c.jsx(ib,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const eU="block w-full text-sm text-soft-white";function tU({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:o,setFilter:a,updateUser:l}=Yi(e),[u,d]=y.useState(null);y.useEffect(()=>{t&&(d(t),a(t))},[t,a]);const h=n.find(f=>f.uid===u)??null;return c.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[c.jsxs("section",{className:"min-w-0",children:[c.jsx("input",{value:o,onChange:f=>a(f.target.value),placeholder:"Filter users…",className:"mb-3 w-full rounded border border-border bg-content-bg px-3 py-1.5 text-sm text-soft-white placeholder:text-slate-gray"}),c.jsx(wg,{users:n,isLoading:s,error:i,filter:o,onSelect:f=>d(f.uid),className:eU,emptyState:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users yet. Sign in from the app, or the agent seeds them, and they appear here."}),noResultsState:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),c.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),c.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:h?c.jsx(nU,{user:h,onSave:f=>l(h.uid,f)},h.uid):c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function nU({user:e,onSave:t}){const n=gg({initial:e}),[r,s]=y.useState(null),[i,o]=y.useState(!1),a=()=>{s(null),o(!1);try{t(n.toUpdateRequest()),o(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return c.jsxs("div",{"data-pyric-ui":"auth-editor",children:[c.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",c.jsx("input",{value:n.fields.displayName,onChange:l=>n.setField("displayName",l.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",c.jsx("textarea",{value:n.fields.claimsText,onChange:l=>n.setField("claimsText",l.target.value),rows:6,spellCheck:!1,className:"mt-1 w-full rounded border border-border bg-content-bg p-2 font-mono text-xs text-soft-white"}),n.errors.claims?c.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),c.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[c.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?c.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?c.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:a,disabled:!n.isValid||!n.isDirty,className:"rounded bg-primary/15 px-3 py-1 text-xs font-medium text-primary hover:bg-primary/25 disabled:opacity-40",children:"Save"}),c.jsx("button",{type:"button",onClick:n.reset,disabled:!n.isDirty,className:"rounded border border-border px-3 py-1 text-xs text-slate-gray hover:text-soft-white disabled:opacity-40",children:"Reset"})]})]})}function qf(e){const t=de(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Vf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Wf(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const rU=[{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 sU(e){const t=Object.entries(e.customMetadata??{});return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[c.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),rU.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":n,children:[c.jsx("dt",{children:r}),c.jsx("dd",{children:i})]},n)}),t.length>0?c.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:r})]},`custom:${n}`))]})}function iU(){return c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:c.jsx("path",{d:"M1.75 4.25c0-.55.45-1 1-1h3.4l1.5 1.7h5.6c.55 0 1 .45 1 1v6.05c0 .55-.45 1-1 1H2.75c-.55 0-1-.45-1-1z"})})}function oU(){return c.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),c.jsx("path",{d:"M9.25 1.75v3h3"})]})}function aU(e){const t=e.kind==="folder";return c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"storage__cell-name",children:[c.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?c.jsx(iU,{}):c.jsx(oU,{})}),c.jsx("span",{className:"storage__nm",children:e.name}),t?c.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),c.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),c.jsx("span",{className:"storage__cell-size"}),c.jsx("span",{className:"storage__cell-updated"})]})}function cU({storage:e,focusTarget:t}){const n=to(),r=t.kind==="object"?de(t.path):null,s=t.kind==="prefix"?de(t.path):r?qf(r):"",i=y.useCallback(E=>{const j=de(E);n.navigate(j?{view:"storage",kind:"prefix",path:j}:{view:"storage",kind:"root"})},[n.navigate]),o=VM({path:s,onPathChange:i}),a=E=>{n.navigate({view:"storage",kind:"object",path:de(E)})},l=qM(e,o.path),u=zM(),d=XM(e),[h,f]=y.useReducer(lL,Gg),p=tL(e,{path:o.path,list:l,onComplete:E=>f({type:"materialize",path:qf(E.fullPath)})});y.useEffect(()=>{if(l.status==="success")for(const E of l.entries)E.kind==="folder"&&Lf(h,E.fullPath)&&f({type:"materialize",path:E.fullPath})},[l.status,l.entries,h]);const[m,g]=y.useState(!1),[b,w]=y.useState(""),[x,v]=y.useState(null),_=y.useRef(null),S=y.useMemo(()=>{const E=uL(h,o.path).filter(C=>!l.entries.some(N=>N.kind==="folder"&&N.name===C));if(E.length===0)return l.entries;const j=E.map(C=>{const N=Vf(o.path,C);return{kind:"folder",name:C,fullPath:N,ref:{fullPath:N,name:C}}});return[...[...l.entries.filter(C=>C.kind==="folder"),...j].sort((C,N)=>C.name<N.name?-1:C.name>N.name?1:0),...l.entries.filter(C=>C.kind==="object")]},[l.entries,h,o.path]),k=S.length>0&&S.every(E=>u.isSelected(E.fullPath)),I=E=>{const j=new Set(S.map(C=>C.name)),$=cL(E.map(C=>C.relativePath),j);p.upload(E.map((C,N)=>({path:$[N],data:C.file})))},O=E=>{E.preventDefault();const j=dL(b);if(j){v(j);return}const $=Vf(o.path,de(b));f({type:"create",path:$}),o.setPath($),w(""),v(null),g(!1)};y.useEffect(()=>u.clear(),[o.path,u.clear]);const P=p.tasks.filter(E=>E.status==="error"),R=d.verdictFor(o.path);return c.jsx(_L,{children:c.jsx(hl,{children:c.jsxs("div",{className:"storage",children:[c.jsxs("div",{className:"storage__sub",children:[c.jsx(nL,{path:o.path,rootLabel:"files",onNavigate:o.setPath}),c.jsx("div",{className:"storage__actions",children:u.size>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),c.jsx(kL,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:E=>{for(const j of u.selected)j.kind==="folder"&&E.deleted.includes(j.fullPath)&&f({type:"discard",path:j.fullPath});r&&u.selected.some(j=>j.kind==="object"?j.fullPath===r:r.startsWith(`${j.fullPath}/`))&&o.setPath(o.path),u.clear(),l.refresh()},onFailed:E=>{const j=new Set(E.failed.map($=>$.fullPath));u.selectAll(u.selected.filter($=>j.has($.fullPath))),l.refresh()}}),c.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__action","aria-expanded":m,onClick:()=>{g(E=>!E),v(null)},children:"New folder"}),c.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>_.current?.click(),children:"Upload files"}),c.jsx("input",{ref:_,type:"file",multiple:!0,hidden:!0,onChange:E=>{const j=Array.from(E.currentTarget.files??[]);j.length>0&&I(j.map($=>({file:$,relativePath:$.name}))),E.currentTarget.value=""}})]})})]}),m?c.jsxs("form",{className:"storage__newfolder",onSubmit:O,children:[c.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:b,onChange:E=>{w(E.currentTarget.value),v(null)},onKeyDown:E=>{E.key==="Escape"&&g(!1)}}),c.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),x?c.jsx("span",{className:"storage__newfolder-err",role:"alert",children:x}):c.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,P.length>0?c.jsxs("p",{className:"storage__upload-err",role:"alert",children:[P.length===1?`Upload failed: ${Wf(P[0].fullPath)} — ${P[0].error?.message??"error"}`:`${P.length} uploads failed: ${P.map(E=>Wf(E.fullPath)).join(", ")}`,c.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,c.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[c.jsxs(iL,{className:"storage__browser",onFiles:I,disabled:!R.upload,disabledReason:R.reasons.write.join("; "),children:[c.jsxs("div",{className:"storage__lhead",children:[c.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:c.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:k,onChange:E=>E.currentTarget.checked?u.selectAll(S):u.clear()})}),c.jsx("span",{children:"name"}),c.jsx("span",{children:"type"}),c.jsx("span",{children:"size"}),c.jsx("span",{children:"updated"})]}),c.jsx(rL,{entries:S,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:aU,renderRowAction:E=>c.jsx("label",{className:"storage__select-row",title:`Select ${E.name}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${E.name}`,checked:u.isSelected(E.fullPath),onChange:()=>u.toggle(E)})}),onNavigate:o.enter,onSelect:E=>a(E.fullPath),emptyState:c.jsx("p",{className:"storage__empty",children:Lf(h,o.path)?"Empty folder — session-only until a file is uploaded here. Drop files anywhere in this pane, or use Upload files.":"No files yet. Drop files here or use Upload files; files your app uploads to Storage also appear here."})}),c.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",o.path||""]})]}),c.jsx("div",{className:"storage__inspector",children:r?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__back",onClick:()=>o.setPath(o.path),"aria-label":"Back to files",children:"‹ Files"}),c.jsx(vL,{storage:e,path:r,renderMetadata:sU})]}):c.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function lU({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return c.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[c.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),c.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",t," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function lb({view:e}){const{target:t}=to(),n=Nt(),r=n.status==="ready"?n.handles.auth:null;return c.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?c.jsx(lU,{view:e}):n.authApi?c.jsx(hg,{value:n.authApi,children:c.jsx(zf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):c.jsx(zf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function zf({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:o}=Yi(n),a=y.useMemo(()=>new Set(o.map(l=>l.uid)),[o]);switch(e){case"firestore":{const l=c.jsx(GL,{handles:t,knownUids:a});return s?c.jsx(IT,{value:s,children:l}):l}case"auth":return c.jsx(tU,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=c.jsx(cU,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?c.jsx(FM,{value:i,children:l}):l}}}function uU(){return c.jsx(lb,{view:"firestore"})}function dU(){return c.jsx(lb,{view:"storage"})}function fU(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function hU(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function pU(e){const[t,n]=y.useState(()=>new Set);y.useEffect(()=>{n(s=>{const i=fU(s,e);return i.size===s.size&&[...i].every(o=>s.has(o))?s:i})},[e]);const r=y.useMemo(()=>e.filter(s=>t.has(s.uid)),[t,e]);return{selectedUsers:r,allVisibleSelected:e.length>0&&r.length===e.length,isSelected:s=>t.has(s),toggle(s){n(i=>{const o=new Set(i);return o.has(s)?o.delete(s):o.add(s),o})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function mU({users:e,filter:t,onDelete:n,onComplete:r}){const s=Yn(),[i,o]=y.useState(!1),[a,l]=y.useState(null),u=async()=>{const d=t.trim().length>0;if(!await s({title:`Delete ${e.length} ${e.length===1?"user":"users"}?`,body:d?`Only the ${e.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${e.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;o(!0),l(null);const f=await hU(e,n);o(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),a?c.jsx("span",{className:"auth-sub__error",children:a}):null]})}function ub(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 db(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 yU(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return c.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[c.jsx("span",{className:"auth-ident__primary",title:n,children:n}),c.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function gU({auth:e}={}){const t=Gt(),n=Nt(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return c.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:c.jsx(_U,{status:t.status})});const i=c.jsx(hl,{children:c.jsx(bU,{auth:r})});return s?c.jsx(hg,{value:s,children:i}):i}function bU({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:o,createUser:a,updateUser:l,deleteUser:u}=Yi(e),d=to(),h=d.target?.view==="auth"?d.target.uid:null,f=w=>d.navigate({view:"auth",uid:w}),p=y.useMemo(()=>t.find(w=>w.uid===h)??null,[t,h]),[m,g]=y.useState(!1),b=pU(t);return c.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[c.jsxs("div",{className:"auth-sub",children:[c.jsxs("span",{className:"auth-sub__h",children:["users ",c.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),c.jsx("input",{className:"auth-sub__filter",value:i,onChange:w=>o(w.target.value),placeholder:"filter users…","aria-label":"Filter users"}),c.jsx("div",{className:"auth-sub__right",children:b.selectedUsers.length>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[b.selectedUsers.length," selected"]}),c.jsx(mU,{users:b.selectedUsers,filter:i,onDelete:w=>Promise.resolve(u(w)),onComplete:w=>{b.replace(w),h&&!w.includes(h)&&f(null)}}),c.jsx("button",{type:"button",className:"auth-sub__clear",onClick:b.clear,children:"Clear selection"})]}):c.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),c.jsxs("div",{className:"auth-body","data-auth-level":p||m?"detail":"list",children:[c.jsx("div",{className:"auth-list",children:c.jsx(wg,{users:t,isLoading:r,error:s,filter:i,onSelect:w=>{g(!1),f(w.uid)},renderIdentifier:yU,formatCreatedAt:db,formatLastLoginAt:ub,renderSelectionHeader:c.jsx("label",{className:"auth-select",title:"Select all shown users",children:c.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:b.allVisibleSelected,onChange:w=>b.selectAll(w.currentTarget.checked)})}),renderSelection:w=>c.jsx("label",{className:"auth-select",title:`Select ${w.uid}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${w.uid}`,checked:b.isSelected(w.uid),onChange:()=>b.toggle(w.uid)})}),emptyState:c.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:c.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),c.jsx("div",{className:"auth-detail",children:m?c.jsx(wU,{onCancel:()=>g(!1),onCreate:async w=>{const x=await Promise.resolve(a(w));g(!1),f(x.uid)}}):p?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),c.jsx(xU,{user:p,onSave:w=>{w.mode==="edit"&&l(w.uid,w.request)},onProvidersChange:async w=>{await Promise.resolve(l(p.uid,{providerUserInfo:w}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):c.jsx("div",{className:"auth-detail__empty",children:c.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function wU({onCreate:e,onCancel:t}){const[n,r]=y.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(o=>{r(o instanceof Error?o:new Error(String(o)))}))};return c.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsx("div",{className:"auth-editor__who",children:"New user"}),c.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),c.jsx(vg,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const Hf=[...hp];function vU({user:e,onChange:t}){const[n,r]=y.useState(null),[s,i]=y.useState(""),o=e.providerUserInfo.map(p=>p.providerId),a=o.includes("password"),l=o.filter(p=>p!=="password"),u=l.filter(p=>!Hf.includes(p)),d=p=>{r(null),t(p.map(m=>({providerId:m}))).catch(m=>{r(m instanceof Error?m:new Error(String(m)))})},h=(p,m)=>{d(m?[...l,p]:l.filter(g=>g!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return c.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[c.jsx("div",{className:"auth-group",children:"Sign-in providers"}),c.jsx("div",{className:"auth-providers-editor__list",children:[...Hf,...u].map(p=>c.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[c.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:m=>h(p,m.target.checked)}),c.jsx("span",{className:"auth-provider-row__label",children:Ii(p)}),c.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),a||e.isAnonymous?c.jsx("p",{className:"auth-providers-editor__derived",children:a?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,c.jsx("div",{className:"auth-provider-custom",children:c.jsxs("label",{className:"auth-provider-custom__field",children:[c.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),c.jsxs("span",{className:"auth-provider-custom__row",children:[c.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),c.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function xU({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=y.useState(null),[o,a]=y.useState(!1),l=h=>{i(null),a(!1);try{t(h),a(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=db(e.createdAt),d=ub(e.lastLoginAt);return c.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?c.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),c.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),c.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),c.jsx(vU,{user:e,onChange:n}),c.jsxs(vg,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,o?c.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),c.jsx("div",{className:"auth-editor__foot",children:c.jsx(KD,{user:e,onDelete:r,className:"auth-del"})})]})}function _U({status:e}){const t=e==="pending"?"Seeding the sandbox…":e==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return c.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:c.jsx("p",{className:"auth-zero",children:t})})}function SU(e){return e.operationContext.source.kind==="studio"}function kU(e,t){return t?e.filter(n=>!SU(n)):[...e]}const EU=["all","allow","deny","proof-unsupported","bypassed"];function Qn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":ll(e)?"proof-unsupported":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function jU(e,t){return t==="all"?[...e]:e.filter(n=>Qn(n)===t)}function Qo(e){return e.rulesDisposition.kind==="evaluated"}function Kf(e){const t=e.path;if(e.service==="storage"&&e.method==="list"&&(t===""||t==="/"))return{tab:"storage"};if(!t||t==="(service)")return null;const n=t.split("/").filter(Boolean);switch(e.service??"firestore"){case"firestore":return n.length?{tab:"firestore",rest:n}:null;case"rtdb":return{tab:"rtdb"};case"storage":return n.length?{tab:"storage",rest:n,...e.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return t!=="*"?{tab:"auth",rest:[t]}:null;default:return null}}function CU(e){return e.filter(t=>{const n=Qn(t);return n==="allow"||n==="deny"})}function IU(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end&&Qn(n)==="proof-unsupported").length}function fb(e){return e==="proof-unsupported"?"Query proof unsupported":e}const hc="inspect";function hb(e){const t=e[hc];return t||null}function pb(e,t){const{[hc]:n,...r}=e;return t?{...r,[hc]:t}:r}function RU(e,t){return pb(e,hb(e)===t?null:t)}const NU=y.lazy(()=>Cm(()=>import("./RulesCodeEditor.Cp_-FK3b.js"),__vite__mapDeps([0,1,2])));function mb(e){return c.jsx(y.Suspense,{fallback:c.jsx(AU,{value:e.value,minHeightRem:e.minHeightRem}),children:c.jsx(NU,{...e})})}function AU({value:e,minHeightRem:t=14}){return c.jsx("pre",{"data-pyric-ui":"rules-code-editor-loading",className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",style:{minHeight:`${t}rem`},children:e||"Loading editor…"})}function yb({denial:e,rulesSource:t}){const n=MP(e);let r="denied",s="deny";return ll(e)?(r="Query proof unsupported",s="proof-unsupported"):e.unsupported&&(r="unsupported",s="unsupported"),c.jsxs("div",{"data-pyric-ui":"denial-detail",className:"flex min-h-0 flex-col gap-4 overflow-auto rounded-lg border border-border bg-sidebar-bg p-5",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?c.jsx(sc,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):c.jsx(sc,{kind:s,className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:r}),c.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),c.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?c.jsx("p",{"data-pyric-ui":"rules-debug-no-evaluation",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"No matched rule, evaluation trace, or re-run is shown because this event carries no rules verdict to ground them in."}):c.jsxs(c.Fragment,{children:[c.jsx(OU,{denial:e,exp:n,rulesSource:t}),c.jsx(MU,{denial:e})]}),c.jsx(UU,{denial:e})]})}function OU({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?c.jsx(FU,{denial:e,exp:t,rulesSource:n},e.id):s?c.jsx(WU,{exp:t}):c.jsx(TU,{denial:e,exp:t,rulesSource:n})}function $U(e){const t="// @pyric-source-map:",n=e.indexOf(t);if(!(n!==-1))return null;const s=n+t.length,i=e.slice(s).trim();try{const o=JSON.parse(i);return Array.isArray(o)?o:null}catch{return null}}function PU(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function DU(e,t){if(e===void 0||t===void 0)return t;const s=$U(e);if(s!==null){const o=s.find(l=>l.authoredLine===t);if(o!==void 0)return o.generatedLine}return t}function TU({denial:e,exp:t,rulesSource:n}){const r=ul(e),s=r?.rule?.line??e.evaluatedRule?.line,i=DU(n,s),o=n!==void 0?PU(n):void 0,a=e.result==="allow",l=!!(o&&o.trim().length>0);return c.jsxs(Et,{label:r?`query proof — ${t.ruleNode}`:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${s?` · line ${s}`:""}`,children:[r?.predicate?c.jsxs("div",{className:"mb-3 text-sm text-slate-gray",children:[c.jsxs("p",{children:["Unsupported predicate",r.predicate.citation?` · ${r.predicate.citation}`:""]}),c.jsx("pre",{className:"overflow-auto font-mono text-xs",children:r.predicate.expression})]}):null,l?c.jsx(mb,{value:o,readOnly:!0,markLine:i,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:r?"Deployed firestore.rules — the rule Pyric could not prove is marked":`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...r?.rule?.expression?[r.rule.expression]:[],...t.ruleLines,...t.otherLines].join(`
|
|
146
|
+
`)||"(no trace)"})]})}function MU({denial:e}){const t=qP(e);return t.length===0?null:c.jsx(Et,{label:ul(e)?"residual evaluation — separate from the static proof":"show the work — how the condition evaluated",children:c.jsx("div",{"data-pyric-ui":"rules-debug-trace",className:"flex flex-col gap-0.5 overflow-auto rounded-md border border-border bg-content-bg p-3",children:t.map((n,r)=>c.jsx(_l,{step:n},r))})})}const LU={true:"✓",false:"✗",skipped:"⊘",error:"!",unsupported:"?",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:e.outcome==="unsupported"?`unsupported${e.error?`: ${e.error}`:""}`:`→ ${gb(e.value)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[c.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:LU[e.outcome]}),c.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),c.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?c.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>c.jsx(_l,{step:r},s))]})}function gb(e){if(e===void 0)return"undefined";try{return JSON.stringify(Ri(e))}catch{return String(e)}}function UU({denial:e}){const t=zP(e);return c.jsx(Et,{label:"what the rule saw (request / resource)",children:c.jsx("div",{"data-pyric-ui":"rules-debug-variables",className:"flex flex-col gap-2 rounded-md border border-border bg-content-bg p-3",children:t.map(n=>c.jsx(BU,{variable:n},n.name))})})}function BU({variable:e}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?c.jsx(bb,{value:e.value}):c.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function bb({value:e,depth:t=0}){const[n,r]=y.useState(t<2),s=Ri(e);if(s===null||typeof s!="object")return c.jsx("span",{className:"font-mono text-xs text-soft-white",children:gb(s)});const i=Array.isArray(s)?s.map((o,a)=>[String(a),o]):Object.entries(s);return i.length===0?c.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):c.jsxs("div",{className:"flex flex-col",children:[c.jsxs("button",{type:"button",onClick:()=>r(o=>!o),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[c.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),c.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?c.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([o,a])=>c.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[c.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[o,":"]}),c.jsx(bb,{value:a,depth:t+1})]},o))}):null]})}function FU({denial:e,exp:t,rulesSource:n}){const r=TP(e,n),s=WP(e,n),[i,o]=y.useState(null),[a,l]=y.useState(!1),u=a?s:s.slice(0,qU),d=i===null?void 0:s[i];let h=r;d&&(h=d.verdict==="UNSUPPORTED"?void 0:d.line);const f=d?d.verdict==="ALLOW":e.result==="allow",p=n!==void 0&&n.trim().length>0;let m;t.implicitDeny||!t.ruleNode?m="rule node":r!==void 0?m=`rule node: ${t.ruleNode} · line ${r}`:m=`rule node: ${t.ruleNode}`;let g;return f?g="Deployed database.rules.json, the allowing rule is marked":g="Deployed database.rules.json, the denying rule is marked",c.jsxs(c.Fragment,{children:[c.jsx(Et,{label:m,children:p?c.jsx("div",{"data-pyric-ui":"rtdb-rule-source","data-marked-line":h,children:c.jsx(mb,{value:n,readOnly:!0,markLine:h,markKind:f?"allow":"deny",minHeightRem:12,ariaLabel:g})}):c.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[t.phase?`.${t.phase}`:"(no matching rule)",e.rules?.matchedPath?` at ${e.rules.matchedPath}`:""]})}),s.length>0?c.jsxs(Et,{label:"evaluated rules, root first",children:[c.jsx("ul",{"data-pyric-ui":"rtdb-trace",className:"flex flex-col gap-1",children:u.map((b,w)=>c.jsx(VU,{row:b,current:w===i,onSelect:()=>o(w)},w))}),s.length>u.length?c.jsxs("button",{type:"button","data-pyric-ui":"rtdb-trace-show-all",onClick:()=>l(!0),className:"w-fit font-mono text-xs text-slate-gray hover:text-soft-white",children:["show all ",s.length," rules"]}):null]}):null,!p&&t.ruleExpression?c.jsx(Et,{label:"rule expression",children:c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:t.ruleExpression})}):null,t.bindings?c.jsx(Et,{label:"$variable bindings",children:c.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([b,w])=>`${b.startsWith("$")?b:`$${b}`} → ${w}`).join(", ")})}):null,e.rules?.reason?c.jsx(Et,{label:"simulator reason",children:c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}const qU=20;function VU({row:e,current:t,onSelect:n}){const r=Object.entries(e.bindings);return c.jsxs("li",{"data-pyric-ui":"rtdb-trace-row","data-line":e.line,"aria-current":t?"true":void 0,onClick:n,className:`flex cursor-pointer flex-col gap-1 rounded-md border px-3 py-2 ${t?"border-primary bg-primary/10":"border-border bg-content-bg hover:bg-sidebar-bg"}`,children:[c.jsxs("button",{type:"button",onClick:s=>{s.stopPropagation(),n()},className:"flex w-fit items-baseline gap-2 font-mono text-xs text-slate-gray",children:[c.jsx("span",{className:"text-soft-white",children:e.path}),c.jsxs("span",{children:[".",e.kind]}),e.line!==void 0?c.jsxs("span",{children:["line ",e.line]}):null]}),c.jsx(_l,{step:e.step}),r.length>0?c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:r.map(([s,i])=>`${s} → ${i}`).join(", ")}):null]})}function WU({exp:e}){return c.jsxs(Et,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?c.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,c.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...e.ruleLines,...e.otherLines].join(`
|
|
147
|
+
`)||"(no trace)"})]})}function Et({label:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function zU(e="firestore"){const t=Gt(),n=t.status==="ready",[r,s]=y.useState({});return y.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{if(!i||!o||typeof o!="object")return;const l={};typeof o.rules=="string"&&(l.firestore=o.rules),o.databaseRules!==void 0&&o.databaseRules!==null&&(typeof o.databaseRules=="string"?l.rtdb=o.databaseRules:l.rtdb=JSON.stringify(o.databaseRules,null,2)),typeof o.storageRules=="string"&&(l.storage=o.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),y.useMemo(()=>{const i=t.status==="ready",o=e==="database"?"rtdb":e;if(!i){const a=r[o];return a!==void 0?a:""}try{if(o==="rtdb"){const u=Xy(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return ts(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function Gf({eventId:e,onClose:t}){const r=YP().find(o=>o.id===e),s=r?.service??"firestore",i=zU(s);return r?c.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),c.jsx(yb,{denial:r,rulesSource:i})]}):c.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[c.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const HU=new Intl.NumberFormat,KU={reads:"read operations",writes:"writes",deletes:"deletes"},GU={allows:"allowed requests",denies:"denied requests"};function Jf(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 Yf(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function wb(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=`${HU.format(n)} observed ${n===1?t.singular:t.plural}`,o=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(o);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${Jf(u)}.`:`${Yf(Jf(u))} tied for the largest share of ${t.subject} in this window.`}}const a=s[0],l=Math.round(a.total/n*100);return{total:n,headline:i,finding:`${Yf(o(a))} accounted for ${l}% of ${t.subject} in this window.`}}function JU(e){return wb(e,{labels:KU,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 YU(e){return wb(e,{labels:GU,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 QU=new Intl.NumberFormat,XU=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Qf(e){return QU.format(e)}function dr(e){return XU.format(e)}function ZU(e){return Qn(e)==="bypassed"}function eB(e){return e.every(t=>t.total===0)}function vb({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:o,source:a,methodology:l}){const[u,d]=y.useState(()=>new Set(n.map(f=>f.key))),h=y.useCallback(f=>{d(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:e}),c.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),c.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),c.jsx(pl,{series:n,visible:u,onToggle:h,formatValue:Qf,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),eB(n)?c.jsx("p",{className:"traffic__empty",children:i}):c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:o}),c.jsxs("span",{children:[dr(s.start),"–",dr(s.end)]})]}),c.jsx(jg,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:Qf,formatTime:dr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:dr(s.start)}),c.jsx("span",{children:dr(s.end)})]})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:a}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsx("div",{children:l})]})]})]})}function tB({events:e,window:t}){const n=y.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=gT({events:n,window:t,isAdmin:ZU}),s=y.useMemo(()=>JU(r.series),[r.series]);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:c.jsx(vb,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:t,emptyLabel:"No reads, writes, or deletes in this session yet.",evidenceTitle:"When the activity happened",source:"Source: Pyric Firestore sandbox events · Operation counts, not a Firebase invoice",methodology:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts successful Firestore sandbox ",c.jsx("code",{children:"get"}),"/",c.jsx("code",{children:"list"}),","," ",c.jsx("code",{children:"create"}),"/",c.jsx("code",{children:"update"}),"/",c.jsx("code",{children:"set"}),", and"," ",c.jsx("code",{children:"delete"}),"/",c.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",c.jsx("code",{children:"list"})," is counted once because the event does not report how many documents the query returned. This is observed sandbox activity, not a Firebase invoice."]})]})})})}function nB({events:e,window:t}){const n=y.useMemo(()=>CU(e),[e]),r=bT({events:n,window:t}),s=y.useMemo(()=>r.series.filter(o=>o.key==="allows"||o.key==="denies"),[r.series]),i=y.useMemo(()=>YU(s),[s]);return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:[c.jsxs("p",{children:["Query proof unsupported: ",IU(e,t)]}),c.jsx(vb,{eyebrow:"Rules decisions",story:i,series:s,points:r.points,window:t,emptyLabel:"No allow or deny decisions in this session yet.",evidenceTitle:"When Rules evaluated requests",source:"Source: Pyric sandbox events · Evaluated Rules dispositions only",methodology:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",c.jsx("code",{children:"evaluated"}),", grouped by its ",c.jsx("code",{children:"allow"})," or ",c.jsx("code",{children:"deny"})," ","verdict. Query-proof limitations are counted separately, not as ordinary denials."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Bypasses and runtime failures are not Rules decisions."})," Admin bypasses, services without Rules, unsupported operations, and runtime errors are excluded because Rules did not produce a verdict."]})]})})]})}function Sl(e){for(const t of e??[])if(t.kind==="component")return t;return null}function no(e){for(const t of e??[])if(t.kind==="tag")return t;return null}function rB(e){for(const t of e??[])if(t.kind==="frame")return t;return null}function sB(e){const t=Sl(e);if(t?.element!==void 0)return t.element;const n=no(e);if(n?.element!==void 0)return n.element}function Bn(e){return typeof e=="string"?e:e.query!==void 0?`${e.collection} (query)`:e.collection}function iB(e,t){const n=Sl(e);if(n)return n.name;const r=no(e);return r?r.name:Bn(t)}function ro(e){const t=Sl(e.owners);if(t)return{key:`component:${t.name}`,label:t.name};const n=no(e.owners);if(n)return{key:`tag:${n.name}`,label:n.name};const r=Bn(e.target);return{key:`target:${r}`,label:r}}function oB(e,t){return!(t.service!==void 0&&e.service!==t.service||t.targetPrefix!==void 0&&t.targetPrefix!==""&&!j_(e.target,t.targetPrefix))}function aB(e,t={}){const n=new Map;for(const r of e){if(!oB(r,t))continue;const s=ro(r),i=n.get(s.key);i?i.listeners.push(r):n.set(s.key,{identity:s,listeners:[r]})}return[...n.values()].map(r=>Object.freeze({identity:r.identity,listeners:Object.freeze(r.listeners)})).sort((r,s)=>r.listeners[0].attachedAt-s.listeners[0].attachedAt)}function cB(e){return{history:()=>e,subscribe:()=>()=>{}}}function xb(e){const t=zC(cB(e),()=>{});try{return t.report().incidents}finally{t.dispose()}}function lB(e){try{const t=JSON.parse(e.targetFingerprint);if(t.kind==="doc"&&typeof t.path=="string")return t.path;if(t.kind==="query"&&typeof t.collection=="string")return{collection:t.collection,query:!0}}catch{}return null}function uB(e,t){return typeof e=="string"||typeof t=="string"?e===t:e.collection===t.collection}function _b(e,t){return e.filter(n=>{if(n.pattern!=="duplicate-listener"&&n.pattern!=="listener-churn")return!1;const r=lB(n);return r!==null&&uB(r,t)})}function dB(e,t){return e?.column===t&&e.direction==="asc"?{column:t,direction:"desc"}:{column:t,direction:"asc"}}const fB=e=>e.deliveryCount;function hB(e,t,n){const r=new Map;for(const s of e.listeners){const i=Bn(s.target),o=r.get(i);o?o.push(s):r.set(i,[s])}return[...r.entries()].map(([s,i])=>{const o=[...i].sort((l,u)=>l.attachedAt-u.attachedAt),a=o[0];return Object.freeze({key:`${e.identity.key}|${s}`,listeners:Object.freeze(o),listener:a,ownerLabel:e.identity.label,target:s,count:o.length,deliveryCount:o.reduce((l,u)=>l+n(u),0),incidents:_b(t,a.target)})})}function Xf(e,t){return e<t?-1:e>t?1:0}function Ai(e){return e.incidents.length>0?1:0}function pB(e,t,n){return n==="target"?Xf(e.target,t.target):n==="service"?Xf(e.listener.service,t.listener.service):n==="attached"?e.listener.attachedAt-t.listener.attachedAt:n==="deliveries"?e.deliveryCount-t.deliveryCount:Ai(e)-Ai(t)}function mB(e,t){const n=Ai(t)-Ai(e);if(n!==0)return n;const r=t.deliveryCount-e.deliveryCount;return r!==0?r:e.listener.attachedAt-t.listener.attachedAt}function yB(e){if(e===void 0)return mB;const t=e.direction==="asc"?1:-1;return(n,r)=>{const s=pB(n,r,e.column)*t;return s!==0?s:n.listener.attachedAt-r.listener.attachedAt}}function gB(e,t,n,r=fB){const s=yB(n);return e.map(i=>{const o=[...hB(i,t,r)].sort(s);return Object.freeze({identity:i.identity,rows:Object.freeze(o),listenerCount:i.listeners.length})}).sort((i,o)=>s(i.rows[0],o.rows[0]))}function bB(e,t){let n=0;const r=[];let s;for(const a of e){n+=a.listenerCount,(s===void 0||a.listenerCount>s.count)&&(s={label:a.identity.label,count:a.listenerCount});for(const l of a.rows)l.count>1&&r.push(l.count)}const i=t.filter(a=>a.pattern==="listener-churn").length,o={listeners:n,duplicates:r,churn:i};return s!==void 0&&(o.busiest=s),o}function wB(e){let t=0,n=0,r=0;for(const s of e)for(const i of s.rows)i.deliveryCount>0?t+=i.count:n+=i.count,i.incidents.length>0&&(r+=i.count);return{delivering:t,idle:n,incidents:r}}function vB(e){const t=[e.deliveryCount>0?"delivering":"idle"];return e.incidents.length>0&&t.push("incidents"),t}function kl(e){return e.kind==="snapshot_delivery"?!0:e.kind==="listener"&&e.phase==="delivery"}const Sb=[{key:"delivering",label:"Delivering"},{key:"idle",label:"Idle"},{key:"incidents",label:"Incidents"}];function xB(e){return Sb.map(t=>({key:t.key,label:t.label,values:[],total:e[t.key]}))}const Xo=[{key:"firestore",label:"Firestore"},{key:"database",label:"Database"}];function _B(e,t){const n=new Map;for(const r of e){if(!kl(r)||r.at<t.start||r.at>=t.end)continue;const s=r.listenerId;s!==void 0&&n.set(s,(n.get(s)??0)+1)}return n}function SB(e,t,n,r=24){const s=n.end-n.start,i=Xo.map(f=>({key:f.key,label:f.label,values:[],total:0}));if(r<=0||s<=0)return{points:[],series:i,total:0};const o=s/r,a=new Map;for(const f of t)a.set(f.id,f.service);const l=new Map(Xo.map(f=>[f.key,new Array(r).fill(0)]));let u=0;for(const f of e){if(!kl(f)||f.at<n.start||f.at>=n.end)continue;const p=f.listenerId;if(p===void 0)continue;const m=a.get(p);if(m===void 0)continue;const g=l.get(m);if(g===void 0)continue;let b=Math.floor((f.at-n.start)/o);b>=r&&(b=r-1),g[b]=(g[b]??0)+1,u+=1}const d=[];for(let f=0;f<r;f+=1)d.push({index:f,start:n.start+f*o,end:n.start+(f+1)*o});const h=Xo.map(f=>{const p=l.get(f.key);return{key:f.key,label:f.label,values:p,total:p.reduce((m,g)=>m+g,0)}});return{points:d,series:h,total:u}}function pc(e,t){if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>pc(i,t[o]));if(typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n);return s.length!==Object.keys(r).length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&pc(n[i],r[i]))}function kB(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function EB(e){if(e.kind==="snapshot_delivery"){const r=e.sample?.docs;return r===void 0?[]:r.map(s=>[s.path,s.data])}const t=e.target?.path;if(t===void 0||t==="")return[];const n=e.sample;return n==null?[]:kB(n)?Object.keys(n).map(r=>[`${t}/${r}`,n[r]]):[[t,n]]}function jB(e){if(e.kind!=="snapshot_delivery")return;const t=e;if(!(t.addedCount===void 0||t.modifiedCount===void 0||t.removedCount===void 0))return{added:t.addedCount,modified:t.modifiedCount,removed:t.removedCount}}function kb(e,t){const n=[];let r=new Map;for(const s of e){if(!kl(s)||s.listenerId!==t)continue;const i=EB(s),o=new Map(i.map(([f,p])=>[f,p])),a=[];let l=0,u=0;for(const[f,p]of i)r.has(f)?pc(r.get(f),p)?a.push({path:f,change:"unchanged"}):(a.push({path:f,change:"modified"}),u+=1):(a.push({path:f,change:"added"}),l+=1);let d=0;for(const f of r.keys())o.has(f)||(a.push({path:f,change:"removed"}),d+=1);const h=jB(s);n.push({at:s.at,initial:n.length===0,addedCount:h?.added??l,modifiedCount:h?.modified??u,removedCount:h?.removed??d,size:i.length,docs:a}),r=o}return n}function Eb(e){const t=e[0];if(t===void 0)return 0;let n=Math.max(t.size,1);for(const r of e.slice(1))n+=r.addedCount+r.modifiedCount;return n}function jb(e){const t=[{key:"deliveries",label:"Deliveries",total:e.deliveries},{key:"snapshot",label:"Snapshot",total:e.snapshot,unit:e.single||e.snapshot===1?"document":"documents"}];return e.service==="firestore"&&t.push({key:"reads",label:"Estimated reads",total:e.reads}),t}function CB(e){return e.map(t=>({key:t.key,label:t.label,values:[],total:t.total}))}function IB(e,t){let n=0;return r=>{const s=e[n];return n+=1,s?.unit===void 0?t(r):`${t(r)} ${s.unit}`}}function RB(e){if(e==="firestore")return"Estimated reads: initial snapshot + documents added or modified since · reconnects and duplicate listeners not counted"}function NB(e,t){return e.map((n,r)=>({id:`delivery-${r}`,at:n.at,method:"listen",path:t,auth:null,result:"allow",reasons:[],origin:"listener"}))}function Zf(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end)}function eh(e){let t=0,n=0,r=0;for(const o of e)t+=o.initial?o.size:o.addedCount,n+=o.initial?0:o.modifiedCount,r+=o.initial?0:o.removedCount;const s=e.length,i=[`${s} ${s===1?"delivery":"deliveries"}`];return t>0&&i.push(`${t} added`),n>0&&i.push(`${n} modified`),r>0&&i.push(`${r} removed`),i}function AB(e){if(e.initial)return"initial";const t=[];return e.addedCount>0&&t.push(`+${e.addedCount}`),e.modifiedCount>0&&t.push(`~${e.modifiedCount}`),e.removedCount>0&&t.push(`−${e.removedCount}`),t.join(" ")}const Cb="listeners";function Ib(e,t){return e==="firestore"?Qg({view:"firestore",path:Qr(t)}):{tab:"rtdb",rest:t.split("/").filter(Boolean)}}function OB(e,t){return It(Ib(e,t))}function Rb(e){return{tab:"traffic",rest:[Cb,e]}}function $B(e){return It(Rb(e))}function Nb(){return{tab:"traffic",query:{view:"listeners"}}}function PB(){return It(Nb())}function Ab(e){if(e.tab!=="traffic"||e.rest[0]!==Cb)return;const t=e.rest[1];return t===void 0||t===""?void 0:t}const Ob=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});function th(e){return Ob.formatToParts(e).filter(t=>t.type!=="dayPeriod").map(t=>t.value).join("").trim()}function DB(e){const t=e.lastIndexOf("/");return t===-1?{prefix:"",id:e}:{prefix:e.slice(0,t+1),id:e.slice(t+1)}}function TB({path:e,service:t}){const{prefix:n,id:r}=DB(e);return c.jsx("a",{className:"traffic__listener-path-link",href:OB(t,e),title:e,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.button!==0||(s.preventDefault(),Ae(Ib(t,e)))},children:c.jsxs("span",{"data-pyric-path":e,children:[c.jsx("span",{"data-pyric-path-prefix":"",children:n}),c.jsx("span",{"data-pyric-path-id":"",children:r})]})})}function MB(e){return e.initial?[]:e.docs.filter(t=>t.change!=="unchanged")}function $b({delivery:e,service:t,expanded:n=!1,onToggle:r}){const s=MB(e),i=n&&s.length>0;return c.jsxs("div",{className:"traffic__delivery-entry","data-pyric-delivery-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__delivery-row","data-pyric-delivery-row":"","data-pyric-delivery-at":e.at,"data-pyric-selected":i?"":void 0,disabled:s.length===0||r===void 0,onClick:r,children:[c.jsx("span",{"data-pyric-delivery-time":"",children:Ob.format(e.at)}),c.jsx("span",{"data-pyric-delivery-figures":"",children:AB(e)}),c.jsxs("span",{"data-pyric-delivery-snapshot":"",children:[e.size," in snapshot"]})]}),i?c.jsx("div",{className:"traffic__delivery-changes","data-pyric-delivery-changes":"",children:s.map(o=>c.jsxs("div",{className:"traffic__delivery-path","data-pyric-delivery-path":o.path,children:[c.jsx(TB,{path:o.path,service:t}),c.jsx("span",{className:"traffic__delivery-change","data-pyric-change":o.change,children:o.change})]},o.path))}):null]})}const LB=/^\[[a-zA-Z][\w-]*(?:=["']?([^"'\]]+)["']?)?\]$/,UB=/^([a-z][a-z0-9-]*?)-[0-9a-z]+$/,BB=/^[a-z][a-z0-9-]*$/;function FB(e){const n=e?.find(r=>r.kind==="component"&&typeof r.tag=="string")?.tag??no(e)?.name;if(!(n===void 0||!BB.test(n)))return n}function qB(e){const t=e.split(">");return t[t.length-1].trim()}function VB(e){const t=LB.exec(e);if(t!==null){const a=UB.exec(t[1]??"");return a===null?{}:{tag:a[1]}}const n=e.replace(/:[a-z-]+(\([^)]*\))?/g,""),r={},s=/^[a-zA-Z][\w-]*/.exec(n)?.[0];s!==void 0&&(r.tag=s.toLowerCase());const i=/#([\w-]+)/.exec(n)?.[1];i!==void 0&&(r.id=i);const o=/\.([\w-]+)/.exec(n)?.[1];return o!==void 0&&(r.className=o),r}function so(e){const t=sB(e);if(t===void 0||t==="")return;const n=VB(qB(t)),r=n.tag??FB(e)??"";return n.id!==void 0?`${r}#${n.id}`:n.className!==void 0?`${r}.${n.className}`:r===""?void 0:r}function WB(e){const t="owners"in e&&Array.isArray(e.owners)?e.owners:void 0;if(e.kind==="listener_attach"){const n=e.target;if(n.kind==="doc"&&n.path!==void 0)return t===void 0?{target:n.path}:{target:n.path,owners:t};const r={collection:n.collection??"",query:n.query};return t===void 0?{target:r}:{target:r,owners:t}}if(e.kind==="listener"&&e.phase==="attach"){const n=e.target?.path??"";return t===void 0?{target:n}:{target:n,owners:t}}return null}function zB(e,t,n){const r=Bn(t),s=[];for(const i of e){const o=WB(i);if(o===null||Bn(o.target)!==r||iB(o.owners,o.target)!==n)continue;const a=rB(o.owners),l=so(o.owners),u={at:i.at};a!==null&&(u.frame=`${a.file}:${a.line}`),l!==void 0&&(u.element=l),s.push(Object.freeze(u))}return Object.freeze(s)}function Pb(e){const t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function El(e,t){return`${Pb(t-e)} ago`}function mc(e,t){return`${e} ${t}${e===1?"":"s"}`}function Db(e){return e===2?"twice":`${e} times`}function Tb(e){return e==="firestore"?"Firestore":"Database"}function HB(e){if(e.listeners===0)return"No listeners attached";const t=mc(e.listeners,"listener");if(e.duplicates.length>0){const n=Math.max(...e.duplicates);return`${t}, ${e.duplicates.length} attached ${Db(n)}`}return e.churn>0?`${t}, ${mc(e.churn,"listener")} reattaching`:t}function KB(e){const t=e.busiest;if(!(t===void 0||t.count<2))return`${t.label} · ${mc(t.count,"listener")}`}function Mb(e,t){const n=[];return e.owner!==void 0&&n.push(e.owner),e.element!==void 0&&n.push(e.element),n.push(Tb(e.service)),n.push(`attached ${El(e.attachedAt,t)}`),n.join(" · ")}function GB(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function JB(e,t,n){const r=t===void 0?"":` by ${t}`;if(e.pattern==="listener-churn")return`Reattached ${e.count} times in ${Pb(e.windowMs)}${r}`;const s=GB(n),i=`Attached ${Db(e.count)}${r}`;return s===""?i:`${i} · ${s}`}function Lb({incident:e,listener:t,events:n,now:r}){const s=ro(t).label,i=zB(n,t.target,s),o=e.pattern==="listener-churn"?i.slice(-1):i,a=e.pattern==="listener-churn"?[]:i.map(d=>El(d.at,r)),l=so(t.owners),u=o.filter(d=>d.frame!==void 0||(d.element??l)!==void 0);return c.jsxs("div",{className:"traffic__listener-incident","data-pyric-incident-block":"",children:[c.jsxs("p",{className:"traffic__listener-incident-line",children:[c.jsx("span",{"aria-hidden":"true",children:"⚠"})," ",JB(e,s,a)]}),u.map((d,h)=>{const f=d.element??l;return c.jsxs("p",{className:"traffic__listener-incident-attach","data-pyric-incident-attach":"",children:[d.frame===void 0?null:c.jsx("span",{children:d.frame}),d.frame!==void 0&&f!==void 0?c.jsx("span",{children:" · "}):null,f===void 0?null:c.jsx("span",{"data-pyric-element":"",children:f})]},`${d.at}|${h}`)})]})}const Zo=40,Nn=" ";function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ve(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function YB(e){return e.length<=Zo?e:e.startsWith("'")&&e.endsWith("'")?`${e.slice(0,Zo-2)}…'`:`${e.slice(0,Zo-1)}…`}function Xr(e,t){const n=QB(e,t);return t?n:YB(n)}function QB(e,t){if(typeof e=="string")return Ve(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return"null";if(!at(e))return"…";switch(e.type){case"string":return typeof e.value=="string"?Ve(e.value):"…";case"number":case"boolean":return String(e.value);case"null":return"null";case"reference":return typeof e.path=="string"?`doc(db, ${Ve(e.path)})`:"…";case"timestamp":return typeof e.iso=="string"?Ve(e.iso):"…";case"geoPoint":return`GeoPoint(${String(e.latitude)}, ${String(e.longitude)})`;case"bytes":return`Bytes(${String(e.length)})`;case"vector":return`Vector(${String(e.length)})`;case"array":{const r=(Array.isArray(e.values)?e.values:[]).map(s=>Xr(s,t));return e.truncated===!0&&r.push("…"),`[${r.join(", ")}]`}case"map":{const r=(Array.isArray(e.entries)?e.entries:[]).filter(s=>Array.isArray(s)&&typeof s[0]=="string").map(([s,i])=>`${s}: ${Xr(i,t)}`);return e.truncated===!0&&r.push("…"),r.length===0?"{}":`{ ${r.join(", ")} }`}default:return"…"}}function Ub(e,t,n){if(!at(e))return;const r=Nn.repeat(t);if(e.kind==="where"){const o=typeof e.field=="string"?e.field:"",a=typeof e.op=="string"?e.op:"",l="display"in e?e.display:e.value;return`${r}where(${Ve(o)}, ${Ve(a)}, ${Xr(l,n)})`}if(e.kind!=="or"&&e.kind!=="and")return;const i=(Array.isArray(e.filters)?e.filters:[]).map(o=>Ub(o,t+1,n)).filter(o=>o!==void 0);if(i.length!==0)return`${r}${e.kind}(
|
|
148
|
+
${i.join(`,
|
|
149
|
+
`)})`}function nh(e,t,n){if(!at(e))return;const r=Array.isArray(e.display)?e.display:Array.isArray(e.values)?e.values:[];if(r.length===0)return;const s=e.inclusive!==!1;return`${Nn}${t==="start"?s?"startAt":"startAfter":s?"endAt":"endBefore"}(${r.map(o=>Xr(o,n)).join(", ")})`}function XB(e,t){return(at(t?.scope)?t.scope:void 0)?.kind==="collection-group"?`collectionGroup(db, ${Ve(e)})`:`collection(db, ${Ve(e)})`}function ZB(e,t){const n=[],r=Array.isArray(e.filters)?e.filters:[];for(const a of r){const l=Ub(a,1,t);l!==void 0&&n.push(l)}const s=Array.isArray(e.orderBy)?e.orderBy:[];for(const a of s)!at(a)||typeof a.field!="string"||n.push(a.direction==="desc"?`${Nn}orderBy(${Ve(a.field)}, 'desc')`:`${Nn}orderBy(${Ve(a.field)})`);typeof e.limit=="number"&&n.push(e.limitFromEnd===!0?`${Nn}limitToLast(${String(e.limit)})`:`${Nn}limit(${String(e.limit)})`);const i=nh(e.start,"start",t);i!==void 0&&n.push(i);const o=nh(e.end,"end",t);return o!==void 0&&n.push(o),n}function rh(e,t,n){const r=XB(e,t),s=t===void 0?[]:ZB(t,n);return s.length===0?r:`query(${r},
|
|
150
|
+
${s.join(`,
|
|
151
|
+
`)})`}function e1(e){return at(e)?e.kind==="child"?typeof e.path=="string"?`.orderByChild(${Ve(e.path)})`:"":e.kind==="key"?".orderByKey()":e.kind==="value"?".orderByValue()":e.kind==="priority"?".orderByPriority()":"":""}const t1=new Set(["startAt","startAfter","endAt","endBefore","equalTo"]);function sh(e,t,n){const r=[];if(at(t)){r.push(e1(t.orderBy));const s=Array.isArray(t.bounds)?t.bounds:[];for(const o of s){if(!at(o)||typeof o.kind!="string"||!t1.has(o.kind))continue;const a=[Xr(o.value,n)];typeof o.key=="string"&&a.push(Ve(o.key)),r.push(`.${o.kind}(${a.join(", ")})`)}const i=t.limit;at(i)&&typeof i.n=="number"&&(i.kind==="limitToFirst"||i.kind==="limitToLast")&&r.push(`.${i.kind}(${String(i.n)})`)}return`ref(db, ${Ve(e)})${r.join("")}`}function n1(e){if(e.service==="database"){const r=typeof e.target=="string"?e.target:"";return r===""?void 0:{text:sh(r,e.query,!1),full:sh(r,e.query,!0)}}if(typeof e.target=="string")return;const t=e.target.collection;if(t==="")return;const n=at(e.query)?e.query:at(e.target.query)?e.target.query:void 0;return{text:rh(t,n,!1),full:rh(t,n,!0)}}function r1({value:e,clipboard:t}){const[n,r]=y.useState(!1),s=t??globalThis.navigator?.clipboard;return c.jsx("button",{type:"button",className:"traffic__listener-query-copy","data-pyric-query-copy":"","data-pyric-copy-value":e,"data-pyric-copy-failed":n?"":void 0,"aria-label":n?"Copy failed":"Copy the query",title:n?"Copy failed":"Copy the query",disabled:s===void 0,onClick:()=>{s!==void 0&&Promise.resolve(s.writeText(e)).then(()=>r(!1),()=>r(!0))},children:c.jsxs("svg",{className:"traffic__listener-query-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[c.jsx("rect",{x:"8",y:"8",width:"11",height:"11",rx:"1"}),c.jsx("path",{d:"M16 8V5H5v11h3"})]})})}function Bb({listener:e,clipboard:t}){const n=y.useMemo(()=>n1({service:e.service,target:e.target,query:e.query}),[e.service,e.target,e.query]);return n===void 0?null:c.jsxs("div",{className:"traffic__listener-query","data-pyric-query-block":"",children:[c.jsx("pre",{className:"traffic__listener-query-text","data-pyric-query-text":"",title:n.full===n.text?void 0:n.full,children:n.text}),c.jsx(r1,{value:n.full,clipboard:t})]})}const s1=new Intl.NumberFormat,i1=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function An(e){return s1.format(e)}function fr(e){return i1.format(e)}const o1=[{id:"incident",label:"",name:"Incidents"},{id:"target",label:"Target",name:"Target"},{id:"deliveries",label:"Deliveries",name:"Deliveries"},{id:"attached",label:"Attached",name:"Attached"},{id:"service",label:"Service",name:"Service"}];function a1(e,t){const n={};return e!==""&&(n.service=e),t!==""&&(n.targetPrefix=t),n}function c1(e,t){return e?.column!==t?"none":e.direction==="asc"?"ascending":"descending"}function l1({metric:e,label:t,value:n,unit:r}){return c.jsxs("span",{className:"traffic__listener-figure","data-pyric-inspector-figure":e,children:[c.jsx("span",{className:"traffic__listener-figure-label",children:t}),c.jsx("span",{className:"traffic__listener-figure-value",children:r===void 0?An(n):`${An(n)} ${r}`})]})}function u1({listener:e,row:t,events:n,now:r,onClose:s}){const[i,o]=y.useState(!1),a=y.useMemo(()=>kb(n,e.id),[n,e.id]),l=a[a.length-1],u=so(e.owners),d={service:e.service,attachedAt:e.attachedAt};d.owner=ro(e).label,u!==void 0&&(d.element=u);const h=t.incidents[0],f=jb({deliveries:a.length,snapshot:l===void 0?0:l.size,reads:Eb(a),service:e.service,single:typeof e.target=="string"&&e.service==="firestore"});return c.jsxs("div",{className:"traffic__inspector","data-pyric-listener-inspector":"",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("a",{className:"traffic__listener-inspector-target","data-pyric-inspector-title":"",href:$B(e.id),onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button!==0||(p.preventDefault(),Ae(Rb(e.id)))},children:t.target}),c.jsx("button",{type:"button",className:"traffic__inspector-close","data-pyric-inspector-close":"",onClick:s,"aria-label":"Close the listener inspector",children:"✕"})]}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-inspector-facts":"",children:Mb(d,r)}),c.jsx(Bb,{listener:e}),h===void 0?null:c.jsx(Lb,{incident:h,listener:e,events:n,now:r}),c.jsx("div",{className:"traffic__listener-figures",children:f.map(p=>c.jsx(l1,{metric:p.key,label:p.label,value:p.total,unit:p.unit},p.key))}),l===void 0?null:c.jsx($b,{delivery:l,service:e.service,expanded:i,onToggle:()=>o(p=>!p)})]})}function d1({events:e,window:t,selectedListenerId:n,initialTargetPrefix:r,hideStudio:s=!1,now:i}){const[o,a]=y.useState(""),[l,u]=y.useState(r??""),[d,h]=y.useState(void 0),[f,p]=y.useState(n),[m,g]=y.useState([]),b=y.useRef(null),w=y.useMemo(()=>{const N=Nc(e);return s?N.filter(A=>A.actor.kind!=="studio"):N},[e,s]),x=y.useMemo(()=>xb(e),[e]),v=y.useMemo(()=>_B(e,t),[e,t]),_=y.useMemo(()=>gB(aB(w,a1(o,l)),x,d,N=>v.get(N.id)??0),[w,o,l,x,d,v]),S=y.useMemo(()=>bB(_,x),[_,x]),k=y.useMemo(()=>xB(wB(_)),[_]),I=y.useMemo(()=>SB(e,w,t),[e,w,t]),O=y.useMemo(()=>new Set(Sb.map(N=>N.key).filter(N=>!m.includes(N))),[m]),P=N=>g(A=>A.includes(N)?A.filter(D=>D!==N):[...A,N]),R=i??Date.now(),E=y.useMemo(()=>{if(n!==void 0){for(const N of _)for(const A of N.rows)if(A.listeners.some(D=>D.id===n))return A.listener.id;return n}},[n,_]);y.useEffect(()=>{E!==void 0&&(p(E),b.current?.scrollIntoView({block:"center"}))},[E]);const j=y.useMemo(()=>_.map(N=>({...N,rows:N.rows.filter(A=>vB(A).some(D=>O.has(D)))})).filter(N=>N.rows.length>0),[_,O]);function $(N){const A=N.listener,D=A.id===f;return c.jsxs("div",{className:"traffic__listener-entry","data-pyric-listener-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__listener-row",ref:D?b:void 0,"data-pyric-listener-row":"","data-pyric-listener-id":A.id,"data-pyric-selected":D?"":void 0,"data-pyric-incident":N.incidents.length>0?"":void 0,onClick:()=>p(D?void 0:A.id),children:[c.jsx("span",{"data-col":"incident","aria-hidden":"true",children:N.incidents.length>0?"⚠":""}),c.jsxs("span",{"data-col":"target",title:N.target,children:[c.jsx("span",{className:"traffic__listener-target-text",children:N.target}),N.count>1?c.jsxs("span",{className:"traffic__listener-duplicate","data-pyric-listener-duplicate":"",children:["×",N.count]}):null]}),c.jsx("span",{"data-col":"deliveries",children:An(N.deliveryCount)}),c.jsx("span",{"data-col":"attached",children:El(A.attachedAt,R)}),c.jsx("span",{"data-col":"service",children:Tb(A.service)})]}),D?c.jsx(u1,{listener:A,row:N,events:e,now:R,onClose:()=>p(void 0)}):null]},N.key)}const C=KB(S);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listeners-view",children:c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:"Listener activity"}),c.jsx("h3",{className:"traffic__metric-headline",children:HB(S)}),C===void 0?null:c.jsx("p",{className:"traffic__metric-finding","data-pyric-listener-owner-fact":"",children:C})]}),c.jsx(pl,{series:k,visible:O,onToggle:P,formatValue:An,className:"traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--3"}),c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:"When deliveries happened"}),c.jsxs("span",{children:[fr(t.start),"–",fr(t.end)]})]}),I.total===0?c.jsx("p",{className:"traffic__empty",children:"No deliveries in this window."}):c.jsxs(c.Fragment,{children:[c.jsx(jg,{points:I.points,series:I.series,omitZeroSeries:!0,formatValue:An,formatTime:fr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:fr(t.start)}),c.jsx("span",{children:fr(t.end)})]})]})]}),c.jsxs("div",{className:"traffic__filters traffic__filters--listeners",role:"group","aria-label":"Listener filters",children:[c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Service"}),c.jsxs("select",{className:"traffic__filter-select",value:o,onChange:N=>a(N.target.value),children:[c.jsx("option",{value:"",children:"All"}),c.jsx("option",{value:"firestore",children:"Firestore"}),c.jsx("option",{value:"database",children:"Database"})]})]}),c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Target"}),c.jsx("input",{className:"traffic__filter-input",type:"text",value:l,onChange:N=>u(N.target.value)})]})]}),w.length===0?null:j.length===0?c.jsx("p",{className:"traffic__empty","data-pyric-listener-empty":"",children:"No listeners match these filters"}):c.jsxs("div",{className:"traffic__log traffic__listener-grid","data-pyric-listener-grid":"","data-pyric-ui":"traffic-listeners-log",children:[c.jsx("div",{className:"traffic__listener-header","data-pyric-listener-header":"",role:"row",children:o1.map(N=>c.jsxs("button",{type:"button",role:"columnheader",className:"traffic__listener-column","data-col":N.id,"aria-label":N.label===""?N.name:void 0,"aria-sort":c1(d,N.id),onClick:()=>h(A=>dB(A,N.id)),children:[N.label,d?.column===N.id?c.jsx("span",{"aria-hidden":"true",children:d.direction==="asc"?"↑":"↓"}):null]},N.id))}),j.map(N=>c.jsxs("div",{className:"traffic__listener-run",children:[c.jsxs("div",{className:"traffic__listener-group","data-pyric-listener-group":N.identity.key,children:[c.jsx("span",{"data-col":"owner",children:N.identity.label}),c.jsx("span",{"data-col":"count",children:An(N.listenerCount)})]}),N.rows.map(A=>$(A))]},N.identity.key))]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox listener events · listeners attached now, deliveries in this window"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsxs("p",{children:["A listener is attached when the sandbox recorded its ",c.jsx("code",{children:"attach"})," and has not recorded a ",c.jsx("code",{children:"detach"})," or an error for it since. The count is that fold, not the number of attach events."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Owners come from the attach, deliveries from the window."})," The owner is the React component the listener was opened in, else the tag the app gave it, else the target itself. Two listeners on the same target under the same owner are one thing attached twice, so they collapse into one row carrying"," ",c.jsx("code",{children:"×N"}),". Delivery counts cover the displayed window only; a listener with none is idle, not gone."]})]})]})]})]})})}const Fb={open:!1};function qb(e){const t=new URLSearchParams(e);if(t.get("view")!=="listeners")return Fb;const n={open:!0},r=t.get("listener");r!==null&&r!==""&&(n.listenerId=r);const s=t.get("target");return s!==null&&s!==""&&(n.targetPrefix=s),n}function f1(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))r!==void 0&&t.set(n,r);return qb(t.toString())}function h1(){return typeof window>"u"?Fb:qb(window.location.search)}const p1={open:!1};function m1(){return f1(Ke().query)}function y1({window:e,hideStudio:t,deepLink:n}){const r=Yt("active-listeners"),s=y.useSyncExternalStore(Jt,cl,()=>""),i=y.useMemo(()=>s===""?p1:m1(),[s]),o=n??i,a={events:r,window:e};return t!==void 0&&(a.hideStudio=t),o.listenerId!==void 0&&(a.selectedListenerId=o.listenerId),o.targetPrefix!==void 0&&(a.initialTargetPrefix=o.targetPrefix),c.jsx(d1,{...a})}function g1(e,t){return e===0?"No requests occurred in this interval.":e===1?t===1?"The request in this interval was denied.":"One request occurred in this interval; it was not denied.":t===0?`${e} requests occurred in this interval; none were denied.`:t===e?`All ${e} requests in this interval were denied.`:`${e} requests occurred in this interval; ${t} ${t===1?"was":"were"} denied.`}function b1(e,t){const n=e.filter(s=>s.at>=t.start&&s.at<t.end),r=n.reduce((s,i)=>s+(i.result==="deny"?1:0),0);return{window:t,events:n,total:n.length,denies:r,finding:g1(n.length,r)}}function Vb(e,t){return e?.start===t.start&&e.end===t.end?null:t}const w1=new Intl.NumberFormat;function v1(e){return w1.format(e)}function ih(e){return`${th(e.start)}–${th(e.end)}`}function x1(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 oh(){return c.jsx("a",{className:"traffic__listener-back",href:PB(),"data-pyric-page-back":"",onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),Ae(Nb()))},children:"← Listeners"})}function _1({events:e,listenerId:t,window:n,now:r}){const[s,i]=y.useState(null),[o,a]=y.useState(null),l=y.useMemo(()=>Nc(e).find(_=>_.id===t),[e,t]),u=y.useMemo(()=>kb(e,t),[e,t]),d=y.useMemo(()=>{if(l!==void 0)return _b(xb(e),l.target)[0]},[e,l]);if(l===void 0)return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(oh,{}),c.jsx("p",{className:"traffic__empty","data-pyric-listener-missing":"",children:"This listener is not attached in this session."})]});const h=r??Date.now(),f=so(l.owners),p={service:l.service,attachedAt:l.attachedAt};p.owner=ro(l).label,f!==void 0&&(p.element=f);const m=Bn(l.target),g=jb({deliveries:u.length,snapshot:u.length===0?0:u[u.length-1].size,reads:Eb(u),service:l.service,single:typeof l.target=="string"&&l.service==="firestore"}),b=RB(l.service),w=NB(u,m),x=s===null?u:Zf(u,s),v=u.map((_,S)=>({delivery:_,index:S})).filter(({delivery:_})=>s===null||_.at>=s.start&&_.at<s.end).reverse();return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(oh,{}),c.jsxs("div",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("section",{className:"traffic__metric-story","data-pyric-section":"header",children:[c.jsx("h3",{className:"traffic__metric-headline","data-pyric-page-title":"",children:m}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-page-facts":"",children:Mb(p,h)})]}),c.jsx(Bb,{listener:l}),d===void 0?null:c.jsx(Lb,{incident:d,listener:l,events:e,now:h}),c.jsxs("section",{"data-pyric-section":"cards",children:[c.jsx(pl,{series:CB(g),formatValue:IB(g,v1),className:`traffic__metric-cards traffic__metric-cards--journal${g.length===2?" traffic__metric-cards--2":""}`}),b===void 0?null:c.jsx("p",{className:"traffic__metric-source","data-pyric-metric-footnote":"",children:b})]}),u.length===0?null:c.jsxs("section",{className:"traffic__listener-section","data-pyric-section":"deliveries",children:[c.jsx(Eg,{events:w,window:n,brush:s??void 0,onBrush:_=>{i(S=>Vb(S,_)),a(null)},liveAt:n.end,bucketCount:36,className:"traffic__timeline",axis:_=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:x1(_.start,h)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:_=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:ih(_)}),c.jsx("strong",{children:eh(Zf(u,_))[0]})]})}),s===null?null:c.jsxs("p",{className:"traffic__listener-interval","data-pyric-interval":"",children:[c.jsx("span",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("span",{"data-pyric-interval-facts":"",children:[ih(s),...eh(x)].join(" · ")})]}),v.length===0?null:c.jsx("div",{className:"traffic__log","data-pyric-delivery-log":"",children:v.map(_=>c.jsx($b,{delivery:_.delivery,service:l.service,expanded:o===_.index,onToggle:()=>a(o===_.index?null:_.index)},_.index))})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox delivery events · every delivery this session recorded for this listener"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsx("p",{children:"Every delivery event carries the result set the callback received: a Firestore delivery carries the documents in callback order, and a database delivery carries the value at the target path, whose keys are child paths when that value is an object. The paths under a delivery are that result set, not a re-read of the store."}),c.jsxs("p",{children:[c.jsx("strong",{children:"The labels come from the previous delivery."})," A path is"," ",c.jsx("code",{children:"added"})," when the previous delivery did not carry it,"," ",c.jsx("code",{children:"modified"})," when it did and the data differs, and ",c.jsx("code",{children:"removed"})," ","when the previous delivery carried it and this one does not. A path whose data is identical is not listed. The first delivery is ",c.jsx("code",{children:"initial"}),": every path in it arrived, so it lists none."]}),c.jsx("p",{children:"Firestore charges a listener for the documents in its first snapshot, then for each document a later delivery adds or changes; a delivery that only drops documents costs nothing, and an empty first snapshot still costs one read. The estimate covers this session's deliveries, so a reconnect that re-read the result set and a second listener on the same query are not in it."})]})]})]})]})]})}function S1({listenerId:e,window:t}){const n=Yt();return c.jsx(_1,{events:n,listenerId:e,window:t})}const k1=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"},{id:"listeners",label:"Listeners"}];function E1(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":e==="listeners"?"listeners":"timeline"}function j1(e){return e.tab!=="traffic"?"timeline":Ab(e)!==void 0?"listeners":E1(e.query.view)}function C1(){return j1(Ke())}function I1(){const{tab:e,rest:t}=Ke();return Ab({tab:e,rest:t})}function R1(){return y.useSyncExternalStore(Jt,I1,()=>{})}function N1(){const e=y.useSyncExternalStore(Jt,C1,()=>"timeline"),t=y.useCallback(n=>{const r={...Ke().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Ae({tab:"traffic",query:r})},[]);return[e,t]}function A1(){const e=y.useSyncExternalStore(Jt,()=>Ke().query.hide==="studio",()=>!1),t=y.useCallback(()=>{const n={...Ke().query};n.hide==="studio"?delete n.hide:n.hide="studio",Ae({tab:"traffic",query:n})},[]);return[e,t]}function O1(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 ah(e){return`${Yr(e.start)}–${Yr(e.end)}`}function $1({event:e}){const t=Qn(e);return t?c.jsx("span",{className:"traffic__verdict","data-verdict":t,children:fb(t)}):null}function P1(){return y.useSyncExternalStore(Jt,()=>hb(Ke().query),()=>null)}const ea=100;function D1(){const e=JP(),[t,n]=N1(),r=R1(),[s,i]=A1(),o=y.useMemo(()=>kU(e,s),[e,s]),a=e.length-o.length,[l,u]=y.useState("all"),[d,h]=y.useState(null),f=P1(),[p,m]=y.useState(ea),g=C=>{Ae({tab:"traffic",query:RU(Ke().query,C)})},b=()=>{Ae({tab:"traffic",query:pb(Ke().query,null)})};y.useEffect(()=>{if(!f)return;const C=N=>{N.key==="Escape"&&b()};return globalThis.addEventListener("keydown",C),()=>globalThis.removeEventListener("keydown",C)},[f]);const w=y.useMemo(()=>{const C=Date.now();if(o.length===0)return{start:C-15*6e4,end:C};let N=1/0;for(const A of o)A.at<N&&(N=A.at);return{start:Math.min(N,C-6e4),end:C+1e3}},[o]),x=w.end,v=y.useMemo(()=>d?b1(o,d):null,[o,d]),_=v?.events??o,S=y.useMemo(()=>jU(_,l).sort((C,N)=>N.at-C.at),[_,l]),{items:k}=rT({events:S}),I=k.slice(0,p),O=k.length-I.length,P=o.length>=Ir,R=o.filter(C=>C.result==="deny").length,E=C=>c.jsx($1,{event:C}),j=C=>{if(Qo(C)){g(C.id);return}const N=Kf(C);N&&Ae(N)},$=f!=null&&I.some(C=>C.type!=="group"&&C.event.id===f);return c.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[c.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[k1.map(C=>c.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===C.id,onClick:()=>n(C.id),children:C.label},C.id)),c.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":s,onClick:i,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",s&&a>0?` (${a} hidden)`:""]})]}),r!==void 0?c.jsx(S1,{listenerId:r,window:w}):t==="billable"?c.jsx(tB,{events:o,window:w}):t==="rules"?c.jsx(nB,{events:o,window:w}):t==="listeners"?c.jsx(y1,{window:w,hideStudio:s}):c.jsxs(c.Fragment,{children:[c.jsx(Eg,{events:o,window:w,brush:d??void 0,onBrush:C=>{h(N=>Vb(N,C)),f&&b()},liveAt:w.end,bucketCount:36,className:"traffic__timeline",header:c.jsxs("div",{className:"traffic__tl-header",children:[c.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",P?` (showing latest ${Ir})`:""]}),R>0?c.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>u(C=>C==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[R," denied"]}):null,c.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:C=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:O1(C.start,x)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:C=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:ah(C)}),c.jsxs("strong",{children:[C.count," ",C.count===1?"request":"requests"]}),c.jsxs("span",{children:[C.denies," denied"]})]}),emptyState:c.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),v?c.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[c.jsxs("div",{className:"traffic__time-focus-story",children:[c.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("h3",{children:ah(v.window)}),c.jsx("p",{children:v.finding})]}),c.jsx("button",{type:"button",onClick:()=>h(null),children:"Show all traffic"})]}):null,c.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[c.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),EU.map(C=>c.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===C,onClick:()=>u(C),children:fb(C)},C))]}),f&&!$?c.jsx(Gf,{eventId:f,onClose:b},f):null,k.length===0?c.jsx("p",{className:"traffic__empty",children:v?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):c.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":v?"":void 0,children:[c.jsx("ul",{"data-pyric-traffic-log-items":"",children:I.map(C=>C.type==="group"?c.jsx("li",{"data-pyric-traffic-group-entry":"",children:c.jsx(vT,{group:C,onSelect:N=>{const A=N;if(Qo(A)){g(A.id);return}const D=Kf(A);D&&Ae(D)},renderClassification:N=>E(N),formatTime:Yr})},C.key):c.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":C.event.id,"data-verdict":Qn(C.event)??void 0,children:[c.jsx(kg,{event:C.event,selected:C.event.id===f,onSelect:N=>j(N),renderClassification:N=>E(N),formatTime:Yr}),C.event.id===f&&Qo(C.event)?c.jsx(Gf,{eventId:f,onClose:b},f):null]},C.event.id))}),O>0?c.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(C=>C+ea),children:["Show ",Math.min(O,ea)," more (",O," hidden)"]}):null]})]})]})}const ch=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],lh=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function jl(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`${ch[t%ch.length]}-${lh[(t>>>4)%lh.length]}`}function Cl(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState("");return y.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function T1(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async()=>t?t.exportState():null,[t])}function M1(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function L1(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState([]),s=y.useCallback(async()=>{if(!t){r([]);return}const l=await t.listStates();r(l.map(u=>u.name))},[t]);y.useEffect(()=>{s()},[s]);const i=y.useCallback(async l=>{t&&(await t.saveState(l),await s())},[t,s]),o=y.useCallback(async l=>{t&&await t.restoreState(l)},[t]),a=y.useCallback(async l=>{t&&(await t.deleteState(l),await s())},[t,s]);return{names:n,save:i,restore:o,remove:a}}function U1(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 B1(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function F1(e){const{provenance:t,identity:n}=U1(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:B1(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 q1(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=F1(e[r]);s&&n.push(s)}return n}const V1=20;function W1(e){Ae(e)}function Fn({target:e,className:t,children:n,title:r}){return c.jsx("a",{className:t,href:It(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),W1(e))},children:n})}function z1(){const e=Gt(),t=ms(),n=Cl();if(t.status==="loading"||e.status==="pending")return c.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(c.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(c.jsxs(Fn,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(c.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(c.jsxs(Fn,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),jl(n)]},"instance")),c.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function H1(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function K1(){const e=Yt(),t=y.useMemo(()=>q1(e,V1),[e]);return c.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[c.jsxs("header",{className:"studio-home__feed-head",children:[c.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),c.jsx(Fn,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?c.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):c.jsx("div",{className:"studio-home__feed-scroll",children:c.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[c.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),c.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),c.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:H1(n.at)})]});return c.jsx("li",{children:n.target?c.jsx(Fn,{className:"studio-home__feed-row",target:n.target,children:r}):c.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const G1=["firestore","auth","rtdb","storage","traffic"];function J1(){const e=Nt(),t=Yt(),n=y.useMemo(()=>{const r={};if(e.status==="ready"){const s=e.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return t.length&&(r.traffic=`${t.length} events`),r},[e,t]);return c.jsx("div",{className:"studio-home__tiles",children:G1.map(r=>{const s=pn.find(i=>i.id===r);return s?c.jsxs(Fn,{className:"studio-card studio-home__tile",target:{tab:r},children:[c.jsxs("span",{className:"studio-home__tile-top",children:[c.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?c.jsx("span",{className:"studio-badge",children:n[r]}):null]}),c.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function Y1(){const e=ms(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return c.jsxs(c.Fragment,{children:[c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Point Claude Code, Cursor, or any MCP client at this sandbox and its writes show up in the feed, attributed."}),c.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),c.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),c.jsx(Fn,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?c.jsxs("span",{className:"studio-home__tile-desc",children:["Your repo rules are deployed to this sandbox (",s.slice(0,8),"). Denials will appear in the feed and in Traffic."]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),c.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function Q1(){const e=Nt(),t=Yt(),n=Gt(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return c.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[c.jsxs("div",{className:"studio-home__hero",children:[c.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),c.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),c.jsx(ug,{exposeFocus:z$}),c.jsx(z1,{}),c.jsx("div",{className:"studio-home__body",children:r?c.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"})]}):s?c.jsx(Y1,{}):c.jsxs(c.Fragment,{children:[c.jsx(K1,{}),c.jsx(J1,{})]})})]})}function _e(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function bt(e){return _e(e).split("/").filter(Boolean)}function yc(e,t){return _e([...bt(e),...t.split("/").filter(Boolean)].join("/"))}function X1(e){const t=bt(e);return t.length<=1?"/":`/${t.slice(0,-1).join("/")}`}function Il(e,t){const n=bt(e),r=bt(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 Wb(e){if(e==null)return null;if(typeof e!="object")return e;const t=e;let n=!1;const r={};for(const[s,i]of Object.entries(t)){const o=Wb(i);if(o===null){n=!0;continue}o!==i&&(n=!0),r[s]=o}return Object.keys(r).length===0?null:n?r:e}function Z1(e){if(typeof e=="string")return JSON.stringify(e);if(e==null)return"null";if(typeof e=="object")try{return JSON.stringify(e)??"null"}catch{return"null"}return String(e)}function Rl(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function zb(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Hb(e,t){let n=e??null;for(const r of bt(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function eF(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function gc(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((o,a)=>gc(o,t[a]));if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n),i=Object.keys(r);return s.length!==i.length?!1:s.every(o=>o in r&&gc(n[o],r[o]))}function tF(e,t){const n=new Map,r=(s,i)=>{if(!Rl(s)){n.set(i,["leaf",s??null]);return}const o=zb(s);n.set(i,["parent",o.map(([a])=>a)]);for(const[a,l]of o)r(l,yc(i,a))};return r(e,_e(t)),n}function nF(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(/[?#].*$/,""),_e(t)}function rF(e){const t=bt(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const sF=["string","number","boolean","json"];function uh(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function iF(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function oF(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function aF(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 Kb(e){return{path:_e(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Gb(e,t){const n=Il(e.path,t);return n===null?null:Hb(e.value,n)}function cF(e,t){const n=_e(t);return n===e.path||e.expanded[n]===!0}function lF(e,t,n){const r=zb(Gb(e,t)),s=Math.min(r.length,e.pages[_e(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function dh(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const o=Il(t.path,s);o!==null&&Rl(Hb(t.value,o))?n[s]=i:r=!0}return r?n:e}function Jb(e,t){switch(t.type){case"navigate":{const n=_e(t.path);return n===e.path?e:Kb(n)}case"value":{if(_e(t.path)!==e.path)return e;const n={...e,status:"live",value:Wb(t.value),error:null};return n.expanded=dh(e.expanded,n),n.pages=dh(e.pages,n),n}case"error":return _e(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=_e(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=_e(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=_e(t.path);return Jb(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=_e(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const uF=50;function dF(e,t,n={}){const r=n.pageSize??uF,s=_e(t),[i,o]=y.useReducer(Jb,s,Kb),a=y.useMemo(()=>tF(i.value,i.path),[i.path,i.value]),l=xl({scope:i.path,entries:a,equals:gc,ready:i.status==="live"});i.path!==s&&o({type:"navigate",path:s}),y.useEffect(()=>{let g=!1;const b=e.subscribeValue(s,w=>{g||o({type:"value",path:s,value:w})},w=>{g||o({type:"error",path:s,message:w instanceof Error?w.message:String(w)})});return()=>{g=!0,b()}},[e,s]);const u=y.useCallback(g=>Gb(i,g),[i]),d=y.useCallback(g=>cF(i,g),[i]),h=y.useCallback(g=>lF(i,g,r),[i,r]),f=y.useCallback(g=>o({type:"toggle",path:g}),[]),p=y.useCallback(g=>o({type:"show-more",path:g,pageSize:r}),[r]),m=y.useCallback(g=>l.get(_e(g)),[l]);return y.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:h,toggle:f,showMore:p,updateAt:m}),[i,r,u,d,h,f,p,m])}function fF({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=_e(e),[o,a]=y.useState(!1),l=y.useRef(null);y.useEffect(()=>{o&&l.current?.select()},[o]);const u=f=>{f.preventDefault(),t(nF(l.current?.value??"")),a(!1)},d=()=>a(!1),h=rF(i);return c.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":o?"":void 0,"aria-label":"Database path",children:o?c.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?c.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,c.jsx("input",{ref:l,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:i,onBlur:d,onKeyDown:f=>{f.key==="Escape"&&d()},spellCheck:!1})]}):c.jsxs(c.Fragment,{children:[c.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[c.jsx("li",{"data-rtdb-crumb-item":!0,children:c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":h.length===0?"":void 0,"aria-current":h.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),h.map((f,p)=>{const m=p===h.length-1;return c.jsxs("li",{"data-rtdb-crumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":m?"":void 0,"aria-current":m?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),c.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>a(!0),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:c.jsx("path",{d:"M11.7 1.3a1 1 0 0 1 1.4 0l1.6 1.6a1 1 0 0 1 0 1.4l-8.5 8.5-3.4 1.1a.5.5 0 0 1-.63-.63l1.1-3.4 8.43-8.57ZM10.9 3.5l1.6 1.6 1.2-1.2-1.6-1.6-1.2 1.2Z"})})})]})})}function hF({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,o=bt(i.path),a=o.length===0?r:o[o.length-1];return c.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?c.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):c.jsx(Yb,{tree:e,api:t,onNavigate:n,path:i.path,label:a,isViewRoot:!0})})}function Yb({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const o=e.valueAt(r),a=Rl(o),l=e.isExpanded(r),u=e.updateAt(r),[d,h]=y.useState(!1),[f,p]=y.useState(!1),[m,g]=y.useState(!1),[b,w]=y.useState(null),x=async(S,k)=>{try{await S(),w(null),k()}catch(I){w(I instanceof Error?I.message:String(I))}},v=()=>{h(!0),g(!1),a&&!l&&e.toggle(r)},_=a&&l?e.childrenAt(r):null;return c.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":a?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":a&&l?"":void 0,children:[c.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[a&&!i?c.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:c.jsx("path",{d:"M1 0l6 4-6 4z"})})}):c.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),c.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),c.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":eF(o),title:"Edit value",onClick:()=>{p(!0),g(!1)},children:Z1(o)})]}),c.jsx("span",{"data-rtdb-actions":!0,children:m?c.jsxs("span",{"data-rtdb-confirm":!0,children:[c.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",a?" subtree":"","?"]}),c.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void x(()=>t.remove(r),()=>g(!1)),children:"Delete"}),c.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${fh(r)}`,title:"Add child",onClick:v,children:"+"}),c.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${fh(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),b?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:b}):null,f?c.jsx(hh,{initialType:uh(o),initialText:iF(o,uh(o)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:S=>x(()=>t.set(r,S),()=>p(!1))}):null,d?c.jsx(hh,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>h(!1),onSubmit:(S,k)=>x(()=>t.set(yc(r,k),S),()=>h(!1))}):null,_?c.jsxs("ul",{"data-rtdb-children":!0,children:[_.entries.map(([S])=>c.jsx("li",{children:c.jsx(Yb,{tree:e,api:t,onNavigate:n,path:yc(r,S),label:S})},S)),_.hiddenCount>0?c.jsx("li",{"data-rtdb-show-more-item":!0,children:c.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",_.hiddenCount," hidden)"]})}):null]}):null]})}function fh(e){const t=bt(e);return t.length===0?"root":t[t.length-1]}function hh({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const o=y.useRef(null),a=y.useRef(null),[l,u]=y.useState(t),[d,h]=y.useState(null),f=m=>{m.preventDefault();const g=o.current?.value??"";if(e){const w=oF(g);if(w){h(w);return}}const b=aF(l,a.current?.value??"");if(!b.ok){h(b.error);return}h(null),s(b.value,e?g.trim():void 0)},p=m=>{m.key==="Escape"&&i()};return c.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?c.jsx("input",{ref:o,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,c.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:m=>u(m.currentTarget.value),onKeyDown:p,children:sF.map(m=>c.jsx("option",{value:m,children:m},m))}),l==="boolean"?c.jsxs("select",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]}):c.jsx("input",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),c.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),c.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?c.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}const Qb="rtdb";function pF(e){return e.tab!==Qb?"/":_e(e.rest.join("/"))}function mF(e){return{tab:Qb,rest:bt(e)}}function yF(){const e=y.useSyncExternalStore(Jt,()=>pF(Ke()),()=>"/"),t=y.useCallback(n=>{Ae(mF(n))},[]);return[e,t]}function gF(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return c.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),c.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),c.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?c.jsx(wF,{live:t}):c.jsx(bF,{})]})}function bF(){return c.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[c.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),c.jsx("p",{className:"mx-auto mt-3 max-w-md text-sm leading-relaxed text-muted",children:"The RTDB viewer goes live once Studio connects to the shared sandbox worker."})]})}function wF({live:e}){const t=jl(Cl()),n=y.useMemo(()=>({set:(r,s)=>e.setRtdbValue(r,s),remove:r=>e.deleteRtdbValue(r),subscribeValue:(r,s,i)=>e.subscribeRtdbValue(r,s,i)}),[e]);return c.jsx(vF,{api:n,instanceLabel:t?`${t}-sandbox`:"sandbox"})}function vF({api:e,instanceLabel:t}){const[n,r]=yF(),{viewRoot:s,missingTail:i,tree:o}=xF(e,n),a=y.useRef(null);return y.useEffect(()=>{if(s==="/")return;const l=a.current;l&&typeof l.scrollIntoView=="function"&&l.scrollIntoView({block:"nearest"})},[s]),c.jsxs("div",{className:"rtdb",ref:a,children:[c.jsx(fF,{className:"rtdb__pathbar",path:n,onNavigate:r,rootLabel:t,inputPrefix:t}),i?c.jsxs("p",{className:"rtdb__missing","data-rtdb-missing":"",children:["This path does not exist. Showing ",c.jsx("code",{children:s}),", the nearest path that does; ",c.jsx("code",{children:i})," is not in the database."]}):null,c.jsx(hF,{className:"rtdb__tree",tree:o,api:e,onNavigate:r,rootLabel:t})]})}function xF(e,t){const[n,r]=y.useState({requested:t,root:t}),s=n.requested===t?n:{requested:t,root:t};s!==n&&r(s);const i=s.root,o=dF(e,i),{path:a,status:l,value:u}=o.state;y.useEffect(()=>{a===i&&l==="live"&&u==null&&i!=="/"&&r({requested:t,root:X1(i)})},[a,l,u,i,t]);const d=i===t?null:Il(i,t);return{viewRoot:i,missingTail:d&&bt(d).length>0?d:null,tree:o}}function _F(){const e=Nt();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??st,s=e.firestoreApi?.setDoc??Zs;let i=0;const o=[];for(const a of t)try{await s(r(n,a.path),a.data),i++}catch(l){o.push(`${a.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:o}},[e])}function SF(){const e=Nt();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=e.handles.auth,r=e.authApi?.createUser??xe.createUser;let s=0;const i=[];for(const o of t)try{await r(n,o.request),s++}catch(a){const l=o.request.uid??o.request.email??"<auto>";i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}return{created:s,errors:i}},[e])}function kF(){const e=Nt(),t=lt(),n=t.status==="ready"?t.env.live:void 0;return y.useCallback(async()=>{if(e.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await e.handles.sandbox.resetAll();r.push(...s?.errors??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[e,n])}function EF(){const e=kF(),t=_F(),n=SF(),r=Gt();return y.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:o}=await Cm(async()=>{const{applySeed:a,deploySeedRules:l}=await import("./seed.B4vza_Bv.js");return{applySeed:a,deploySeedRules:l}},__vite__mapDeps([3,1,4,2,5]));o(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),o=i?.seed;o&&await t(Object.entries(o).map(([l,u])=>({path:l,data:u})));const a=i?.authUsers;Array.isArray(a)&&await n(a.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function jF(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 Ls(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function CF(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Ls(e.collections,"collection")),e.users&&t.push(Ls(e.users,"user")),e.objects&&t.push(Ls(e.objects,"file")),e.rtdbKeys&&t.push(Ls(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function io(){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 IF(){return c.jsxs("svg",{...io(),children:[c.jsx("path",{d:"M12 4v10"}),c.jsx("path",{d:"M8 10l4 4 4-4"}),c.jsx("path",{d:"M4 19h16"})]})}function RF(){return c.jsxs("svg",{...io(),children:[c.jsx("path",{d:"M12 14V4"}),c.jsx("path",{d:"M8 8l4-4 4 4"}),c.jsx("path",{d:"M4 19h16"})]})}function NF(){return c.jsxs("svg",{...io(),children:[c.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),c.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),c.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),c.jsx("path",{d:"M7 8.4v7.2"}),c.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function AF(){return c.jsxs("svg",{...io(),children:[c.jsx("path",{d:"M4 5v5h5"}),c.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Us({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return c.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[c.jsxs("span",{className:"studio-sandbox__action-top",children:[e,c.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),c.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function OF(){const e=EF(),t=T1(),n=M1(),r=L1(),s=ms(),i=y.useRef(null),o=jl(Cl()),[a,l]=y.useState(!1),[u,d]=y.useState(!1),[h,f]=y.useState(!1),[p,m]=y.useState(!1),[g,b]=y.useState(""),w=lg(),{ensure:x}=w;y.useEffect(()=>x(),[x]);const v=jF(w.entries),_=CF(v),S=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",k=async()=>{const j=await t();if(!j||typeof document>"u")return;const $=URL.createObjectURL(new Blob([j],{type:"application/json"})),C=document.createElement("a");C.href=$,C.download=`pyric-sandbox-${o||"export"}.json`,C.click(),URL.revokeObjectURL($)},I=async j=>{const $=j.target.files?.[0];if(j.target.value="",!!$&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await $.text())}finally{d(!1)}}},O=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},P=async()=>{const j=g.trim();j&&(await r.save(j),b(""),m(!1))},R=async j=>{typeof window<"u"&&!window.confirm(`Restore saved state "${j}"? This replaces the current sandbox state.`)||await r.restore(j)},E=async j=>{typeof window<"u"&&!window.confirm(`Delete saved state "${j}"?`)||await r.remove(j)};return c.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),c.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),c.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),c.jsx("div",{className:"studio-settings__grid",children:c.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[c.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),c.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[c.jsx("span",{className:"studio-sandbox__instance mono",children:o||"local"}),c.jsx("span",{className:"studio-sandbox__inventory",children:_}),c.jsx("span",{className:"studio-sandbox__persist",children:S})]}),c.jsxs("div",{className:"studio-sandbox__actions",children:[c.jsx(Us,{glyph:c.jsx(IF,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void k()}),c.jsx(Us,{glyph:c.jsx(RF,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),c.jsx(Us,{glyph:c.jsx(NF,{}),name:"Save state",caption:"Keeps a copy you can return to.",onClick:()=>m(j=>!j)}),c.jsx(Us,{glyph:c.jsx(AF,{}),name:a?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:a,danger:!0,onClick:()=>f(!0)})]}),c.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:I}),p?c.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:j=>{j.preventDefault(),P()},children:[c.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"saved state name","aria-label":"Saved state name",autoFocus:!0,onChange:j=>b(j.target.value),onKeyDown:j=>{j.key==="Escape"&&(m(!1),b(""))}}),c.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>{m(!1),b("")},children:"Cancel"})]}):null,h?c.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[c.jsx("span",{className:"studio-sandbox__confirm-copy",children:v&&_!=="empty — no data yet"?`This erases ${_}.`:"This erases everything in this sandbox."}),c.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[c.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void O(),children:"Erase and reseed"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.names.length>0?c.jsx("div",{className:"studio-settings__saved-states",children:r.names.map(j=>c.jsxs("div",{className:"studio-settings__saved-state",children:[c.jsx("span",{className:"mono",children:j}),c.jsxs("span",{className:"studio-settings__saved-state-actions",children:[c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void R(j),children:"Restore"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void E(j),children:"Delete"})]})]},j))}):c.jsx("p",{className:"studio-sandbox__saved-states-empty",children:"No saved states yet. Save state keeps this exact sandbox to come back to."})]})})]})}function Bs(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 $F(e){const t=e.stateDiff;if(!t)return"No state evidence";if(!t.changed)return e.mutation.output!==void 0?"Read result captured":"No state change";if(t.before&&t.after&&typeof t.before=="object"&&typeof t.after=="object"&&!Array.isArray(t.before)&&!Array.isArray(t.after)){const n=t.before,r=t.after,i=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(o=>JSON.stringify(n[o])!==JSON.stringify(r[o]));if(i.length>0&&i.length<=3)return i.map(o=>`${o}: ${Bs(n[o])} -> ${Bs(r[o])}`).join(", ")}return`${Bs(t.before)} -> ${Bs(t.after)}`}function PF(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:$F(t),supported:t.qualification.supported}))}function DF(e){const t=e.mutation.events.find(o=>o.result==="allow"||o.result==="deny"||o.result==="unsupported");if(!t)return null;const n=t.result,r={id:t.id??`${e.probeId}-decision`,at:t.at??0,result:n,method:t.method??t.op??e.mutation.operation.method,service:t.service??e.mutation.operation.service,path:t.path??e.mutation.operation.path,auth:t.auth??null,reasons:t.reasons??[],origin:t.origin??"user",unsupported:n==="unsupported"};t.queryProof&&(r.queryProof=t.queryProof),t.matchedRule&&(r.matchedRule=t.matchedRule),t.evaluatedRule&&(r.evaluatedRule=t.evaluatedRule),t.rules&&(r.rules=t.rules),t.resourceBefore&&(r.resourceBefore=t.resourceBefore);const s=t.request,i=s?.resourceData??s?.data;return i!==void 0&&(r.resourceData=i),r}const TF="pyric:assurance-campaign",MF="pyric-assurance-v1",bc=new Set;let ph=!1,mh;function yh(e){for(const t of bc)t(e)}function gh(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function LF(){if(!(ph||typeof document>"u")){ph=!0,globalThis.addEventListener(TF,e=>{const t=e.detail;gh(t)&&yh(t)});try{mh=new BroadcastChannel(MF),mh.onmessage=e=>{gh(e.data)&&yh(e.data)}}catch{}}}function UF(e){return LF(),bc.add(e),()=>bc.delete(e)}function ta(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 BF=[ta({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"}}),ta({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"}),ta({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"}}})],pq=BF.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const wc="pyric:assurance:campaigns",Xb="pyric:assurance:campaign:";function FF(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function qF(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(wc)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${Xb}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(FF);return t.length,t}catch{return[]}}function VF(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(wc)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(wc,JSON.stringify(n)),sessionStorage.setItem(`${Xb}${e.campaignId}`,JSON.stringify(e))}catch{}}function WF(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 zF(){const[e,t]=y.useState(qF);return y.useEffect(()=>{const r=UF(s=>{VF(s),t(i=>WF(i,s))});return()=>{r()}},[]),e}function HF(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function KF(e){return e.replaceAll("-"," ")}function bh({value:e}){return c.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function GF(){return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),c.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function wh({attachment:e}){return e?c.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[c.jsxs("span",{children:[c.jsx("strong",{children:e.source.origin}),"read-only clone"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function JF({campaigns:e}){const t=zF(),n=e??t,r=Ke().query,[s,i]=y.useState(r.campaign??n.find(v=>v.report)?.campaignId??n[0]?.campaignId??""),o=n.find(v=>v.campaignId===s)??n[0],a=y.useMemo(()=>o?.report?PF(o.report):[],[o]),[l,u]=y.useState(r.probe??a[0]?.id??"");if(y.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),y.useEffect(()=>{a.some(v=>v.id===l)||u(a[0]?.id??"")},[a,l]),!o)return c.jsx(GF,{});const d=o.context?.attachment,h=o.report;if(!h)return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:o.campaignId}),c.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),c.jsxs("p",{children:[o.observations.length," known-good operation(s) and"," ",o.probes.length," probe(s) are available."]}),c.jsx(wh,{attachment:d}),d?.coverageGaps.length?c.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.service}),v.reason]},v.code))}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=a.find(v=>v.id===l)??a[0],p=h.results.find(v=>v.probeId===f?.id),m=p?DF(p):null,g=o.verifications?.at(-1),b=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function w(v){i(v);const S=n.find(k=>k.campaignId===v)?.report?.results[0]?.probeId??"";u(S),Jr({tab:"assurance",query:{campaign:v,probe:S||void 0}})}function x(v){u(v.id),Jr({tab:"assurance",query:{campaign:o.campaignId,probe:v.id}})}return c.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[c.jsxs("header",{className:"assurance-surface__header",children:[c.jsxs("div",{children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-title",children:o.campaignId})]}),c.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?c.jsxs("label",{children:[c.jsx("span",{children:"Campaign"}),c.jsx("select",{value:o.campaignId,onChange:v=>w(v.target.value),children:n.map(v=>c.jsx("option",{value:v.campaignId,children:v.campaignId},v.campaignId))})]}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),c.jsx(wh,{attachment:d}),c.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Controls"}),c.jsxs("strong",{children:[h.summary.controlsPassed,"/",h.summary.probes]})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Counterexamples"}),c.jsx("strong",{children:h.summary.localCounterexamples})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Candidate signals"}),c.jsx("strong",{children:h.summary.candidateSignals})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Engine gaps"}),c.jsx("strong",{children:h.summary.engineGaps})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Coverage gaps"}),c.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?c.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${b?"passed":"failed"}`,role:"status",children:[c.jsx("strong",{children:b?"Candidate rules verified":"Candidate rules need review"}),c.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),c.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?c.jsxs("div",{className:"assurance-coverage-band",children:[c.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),c.jsx("span",{children:d.coverageGaps.map(v=>`${v.service}: ${v.reason}`).join(" ")})]}):null,c.jsxs("div",{className:"assurance-workspace",children:[c.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),c.jsx("span",{children:h.targetHash})]}),c.jsxs("div",{className:"assurance-table",role:"table",children:[c.jsxs("div",{className:"assurance-table__header",role:"row",children:[c.jsx("span",{role:"columnheader",children:"Operation"}),c.jsx("span",{role:"columnheader",children:"Actor"}),c.jsx("span",{role:"columnheader",children:"Expected"}),c.jsx("span",{role:"columnheader",children:"Observed"}),c.jsx("span",{role:"columnheader",children:"Impact"})]}),a.map(v=>c.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":v.id===f?.id,onClick:()=>x(v),role:"row",children:[c.jsxs("span",{role:"cell",children:[c.jsx("small",{children:v.service}),v.operation]}),c.jsx("span",{role:"cell",children:v.actor}),c.jsx("span",{role:"cell",className:`assurance-verdict ${v.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:v.expected}),c.jsx("span",{role:"cell",className:`assurance-verdict ${HF(v.expected,v.observed)}`,children:v.observed}),c.jsx("span",{role:"cell",children:v.impact})]},v.id))]})]}),p?c.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsxs("div",{children:[c.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:KF(p.classification)}),c.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),c.jsx("span",{children:p.actorEvidence.reachability})]}),c.jsxs("dl",{className:"assurance-facts",children:[c.jsxs("div",{children:[c.jsx("dt",{children:"Invariant"}),c.jsx("dd",{children:p.invariant.statement})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Mutation"}),c.jsx("dd",{children:p.mutationSpec.description})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Actor"}),c.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Fidelity"}),c.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(v=>!v.supported)?c.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(v=>!v.supported).map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.id}),v.reason]},v.id))}):null,p.stateDiff?c.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[c.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),c.jsxs("div",{className:"assurance-evidence__diff",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Before"}),c.jsx(bh,{value:p.stateDiff.before})]}),c.jsxs("div",{children:[c.jsx("span",{children:"After"}),c.jsx(bh,{value:p.stateDiff.after})]})]})]}):null,m?c.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[c.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),c.jsx(yb,{denial:m})]}):c.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function vh(){return Ji()}function Zb(){return`${Ji()}docs`}function xh(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function YF(){const[e,t]=y.useState(!1);return y.useEffect(()=>{let n=!0;return fetch(`${Zb()}/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 QF({id:e}){const t=B$(e),n=Gt(),r=[`route #${t.id}`];return n.status==="ready"?(r.push(`events: ${n.events.length}`),r.push("dev-seed: ready")):n.status==="pending"?r.push("dev-seed: seeding…"):n.status==="error"?r.push("dev-seed: error"):r.push("dev-seed: off"),c.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[c.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),c.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),c.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),c.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>c.jsx("span",{children:s},s))})]})}function XF({id:e}){switch(e){case"home":return c.jsx(Q1,{});case"firestore":return c.jsx(uU,{});case"auth":return c.jsx(gU,{});case"storage":return c.jsx(dU,{});case"rtdb":return c.jsx(gF,{});case"traffic":return c.jsx(D1,{});case"assurance":return c.jsx(JF,{});case"settings":return c.jsx(OF,{});default:return c.jsx(QF,{id:e})}}function ZF(){const[e,t]=W$(U$,"home"),n=u=>t(u),[r,s]=y.useState(!1),i=YF(),[o]=y.useState(()=>h1());y.useEffect(()=>{if(!o.open)return;const u={view:"listeners"};o.listenerId!==void 0&&(u.listener=o.listenerId),o.targetPrefix!==void 0&&(u.target=o.targetPrefix),Jr({tab:"traffic",query:u})},[]);const a=e==="home";y.useEffect(()=>{const u=d=>{if(K$(d)){if(r){d.preventDefault(),s(!1);return}if(a){H$()&&d.preventDefault();return}d.preventDefault(),s(!0)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a,r]),y.useEffect(()=>{a&&s(!1)},[a]),y.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const l=pn.filter(u=>u.id!=="home");return c.jsxs("div",{className:"studio","data-surface":e,children:[c.jsxs("header",{className:"studio__chrome",children:[c.jsx("div",{className:"studio__bar",children:c.jsxs("div",{className:"studio__chrome-inner",children:[c.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[c.jsx("a",{className:"studio__brand",href:vh(),"aria-label":"Pyric",children:"pyric"}),c.jsx("a",{className:"studio__nav-tab",href:vh(),children:"Home"}),i?c.jsx("a",{className:"studio__nav-tab",href:Zb(),children:"Docs"}):null,c.jsx("a",{className:"studio__nav-tab",href:It({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:xh(()=>n("home")),children:"Studio"})]}),c.jsx(tT,{})]})}),c.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:c.jsx("div",{className:"studio__chrome-inner",children:c.jsx("div",{className:"studio__nav",children:l.map(u=>c.jsx("a",{className:"studio__nav-tab",href:It({tab:u.id}),"aria-current":u.id===e?"page":void 0,onClick:xh(()=>n(u.id)),children:u.label},u.id))})})})]}),c.jsx("main",{className:"studio__content","data-surface":e,children:c.jsx("div",{className:"studio__surface-slot","data-active":"true",children:c.jsx(XF,{id:e})})}),r?c.jsx(jP,{onClose:()=>s(!1)}):null]})}function eq(){return c.jsx(P$,{children:c.jsx(_I,{children:c.jsx(R$,{mode:"local",children:c.jsx(ZF,{})})})})}function mq(){return c.jsx(y.StrictMode,{children:c.jsx(eq,{})})}export{mq as S,hq as a,mE as b,Mr as r,xe as s,IC as u};
|