@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
package/dist/serve/site-ui/_astro/{sandbox-controls.Bp5PoonS.js → sandbox-controls.Bv6lfpIe.js}
RENAMED
|
@@ -6,24 +6,24 @@ var Ur={exports:{}},Fn={};/**
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var Qo;function
|
|
10
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Br(t.slice(2,4));case"u":return t.charAt(2)==="{"?Br(t.slice(3,-1)):Br(t.slice(2,6));default:return t.charAt(1)}else return t}function no(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function Iu(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const
|
|
9
|
+
*/var Qo;function Xd(){if(Qo)return Fn;Qo=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(s,r,i){var o=null;if(i!==void 0&&(o=""+i),r.key!==void 0&&(o=""+r.key),"key"in r){i={};for(var a in r)a!=="key"&&(i[a]=r[a])}else i=r;return r=i.ref,{$$typeof:t,type:s,key:o,ref:r!==void 0?r:null,props:i}}return Fn.Fragment=e,Fn.jsx=n,Fn.jsxs=n,Fn}var Yo;function ef(){return Yo||(Yo=1,Ur.exports=Xd()),Ur.exports}var K0=ef();function Be(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function Yt(t,e){if(!t)throw new Error(e||"Assertion failed")}function di(t,e,n){let s;Object.defineProperty(t,e,{get(){return s||(s=n.call(this)),s}})}function vu(t,e){const n=[];for(;e-- >0;)n.push(t());return n}function wu(t,e){return new Array(e+1).join(t)}function Ar(t,e){return vu(()=>t,e)}function fi(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n];t.lastIndexOf(s)!==n&&e.indexOf(s)<0&&e.push(s)}return e}function Su(t){const e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function nn(t){const e=t[0];return e===e.toUpperCase()}function Au(t){return!nn(t)}function ku(t,e,n){return t.length<e?wu(" ",e-t.length)+t:t}function hn(){this.strings=[]}hn.prototype.append=function(t){this.strings.push(t)};hn.prototype.contents=function(){return this.strings.join("")};const Br=t=>String.fromCodePoint(parseInt(t,16));function Eu(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
10
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Br(t.slice(2,4));case"u":return t.charAt(2)==="{"?Br(t.slice(3,-1)):Br(t.slice(2,6));default:return t.charAt(1)}else return t}function no(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function Iu(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const tf=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:hn,abstract:Be,assert:Yt,checkNotNull:Iu,copyWithoutDuplicates:Su,defineLazyProperty:di,getDuplicates:fi,isLexical:Au,isSyntactic:nn,padLeft:ku,repeat:Ar,repeatFn:vu,repeatStr:wu,unescapeCodePoint:Eu,unexpectedObjToString:no},Symbol.toStringTag,{value:"Module"})),_u=t=>new RegExp(String.raw`\p{${t}}`,"u"),hi=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map(t=>[t,_u(t)]));hi.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Xo=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,_u(t)]));class U{constructor(){if(this.constructor===U)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const $e=Object.create(U.prototype),Pe=Object.create(U.prototype);class Me extends U{constructor(e){super(),this.obj=e}}class je extends U{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}}class Fe extends U{constructor(e){super(),this.index=e}}class Ie extends U{constructor(e){super(),this.terms=e}}class kr extends Ie{constructor(e,n,s){const r=e.rules[n].body;super([s,r]),this.superGrammar=e,this.name=n,this.body=s}}class Er extends Ie{constructor(e,n,s,r){const i=e.rules[n].body;super([...s,i,...r]),this.superGrammar=e,this.ruleName=n,this.expansionPos=s.length}}class Ce extends U{constructor(e){super(),this.factors=e}}class ze extends U{constructor(e){super(),this.expr=e}}class pn extends ze{}class Nn extends ze{}class $t extends ze{}pn.prototype.operator="*";Nn.prototype.operator="+";$t.prototype.operator="?";pn.prototype.minNumMatches=0;Nn.prototype.minNumMatches=1;$t.prototype.minNumMatches=0;pn.prototype.maxNumMatches=Number.POSITIVE_INFINITY;Nn.prototype.maxNumMatches=Number.POSITIVE_INFINITY;$t.prototype.maxNumMatches=1;class Le extends U{constructor(e){super(),this.expr=e}}class We extends U{constructor(e){super(),this.expr=e}}class Ze extends U{constructor(e){super(),this.expr=e}}class te extends U{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return nn(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ne extends U{constructor(e){if(super(),this.categoryOrProp=e,e in hi)this.pattern=hi[e];else if(e in Xo)this.pattern=Xo[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function ye(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function pi(){return ye("Interval sources don't match")}function nf(t){const e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function sf(t,e,n){const s=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return ye(s,n)}function rf(t,e){return ye("Grammar "+t.name+" is already declared in this namespace")}function of(t){return ye(`Grammar '${t.name}' does not support incremental parsing`)}function xu(t,e,n){return ye("Rule "+t+" is not declared in grammar "+e,n)}function af(t,e,n){return ye("Cannot override rule "+t+" because it is not declared in "+e,n)}function cf(t,e,n){return ye("Cannot extend rule "+t+" because it is not declared in "+e,n)}function ea(t,e,n,s){let r="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(r+=" (originally declared in '"+n+"')"),ye(r,s)}function Cu(t,e,n,s){return ye("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",s)}function uf(t,e,n,s){return ye("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",s)}function ta(t,e,n){return ye("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function lf(t,e){return ye("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const df="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function ff(t,e){return ye("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function hf(t){const{ruleName:e}=t;return ye(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+df,t.source)}function pf(t){return ye("applySyntactic is not required here (in a syntactic context)",t.source)}function na(t,e){return ye("Incorrect argument type: expected "+t,e.source)}function mf(t){return ye("'...' can appear at most once in a rule body",t.source)}function gf(t){const e=t._node;Yt(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const n=t.children.slice(1,-1).map(r=>r.source),s=n[0].coverageWith(...n.slice(1));return ye(`U+${s.contents} is not a valid Unicode code point`,s)}function Ou(t,e){const n=e.length>0?e[e.length-1].args:[];let r="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const i=e.map(o=>new te(o.ruleName,o.args)).join(`
|
|
11
11
|
`);r+=`
|
|
12
12
|
Application stack (most recent application last):
|
|
13
|
-
`+i}return ye(r,t.expr.source)}function Tu(t,e,n,s){return ye("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",s.source)}function
|
|
14
|
-
- `),t[0].interval)}function
|
|
13
|
+
`+i}return ye(r,t.expr.source)}function Tu(t,e,n,s){return ye("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",s.source)}function yf(t){const e=t.map(n=>n.message);return ye(["Errors:"].concat(e).join(`
|
|
14
|
+
- `),t[0].interval)}function bf(t,e,n,s){let r=s.slice(0,-1).map(c=>{const u=" "+c[0].name+" > "+c[1];return c.length===3?u+" for '"+c[2]+"'":u}).join(`
|
|
15
15
|
`);r+=`
|
|
16
16
|
`+e+" > "+t;let i="";t==="_iter"&&(i=[`
|
|
17
17
|
NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
|
|
18
18
|
`));const o=[`Missing semantic action for '${t}' in ${n} '${e}'.${i}`,"Action stack (most recent call last):",r].join(`
|
|
19
|
-
`),a=ye(o);return a.name="missingSemanticAction",a}function
|
|
20
|
-
`);const i=
|
|
19
|
+
`),a=ye(o);return a.name="missingSemanticAction",a}function vf(t){if(t.length===1)throw t[0];if(t.length>1)throw yf(t)}function wf(t){let e=0;return t.map(s=>{const r=s.toString();return e=Math.max(e,r.length),r}).map(s=>ku(s,e))}function sa(t,e,n){const s=t.length,r=t.slice(0,n),i=t.slice(n+e.length);return(r+e+i).substr(0,s)}function Sf(...t){const e=this,{offset:n}=e,{repeatStr:s}=tf,r=new hn;r.append("Line "+e.lineNum+", col "+e.colNum+`:
|
|
20
|
+
`);const i=wf([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),o=(l,d,f)=>{r.append(f+i[l]+" | "+d+`
|
|
21
21
|
`)};e.prevLine!=null&&o(0,e.prevLine," "),o(1,e.line,"> ");const a=e.line.length;let c=s(" ",a+1);for(let l=0;l<t.length;++l){let d=t[l][0],f=t[l][1];Yt(d>=0&&d<=f,"range start must be >= 0 and <= end");const p=n-e.colNum+1;d=Math.max(0,d-p),f=Math.min(f-p,a),c=sa(c,s("~",f-d),d)}const u=2+i[1].length+3;return r.append(s(" ",u)),c=sa(c,"^",e.colNum-1),r.append(c.replace(/ +$/,"")+`
|
|
22
|
-
`),e.nextLine!=null&&o(2,e.nextLine," "),r.contents()}let mi=[];function Ru(t){mi.push(t)}function
|
|
22
|
+
`),e.nextLine!=null&&o(2,e.nextLine," "),r.contents()}let mi=[];function Ru(t){mi.push(t)}function Af(t){mi.forEach(e=>{e(t)}),mi=null}function so(t,e){let n=1,s=1,r=0,i=0,o=null,a=null,c=-1;for(;r<e;){const d=t.charAt(r++);d===`
|
|
23
23
|
`?(n++,s=1,c=i,i=r):d!=="\r"&&s++}let u=t.indexOf(`
|
|
24
24
|
`,i);if(u===-1)u=t.length;else{const d=t.indexOf(`
|
|
25
|
-
`,u+1);o=d===-1?t.slice(u):t.slice(u,d),o=o.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(a=t.slice(c,i).replace(/\r?\n$/,""));const l=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:s,line:l,prevLine:a,nextLine:o,toString:
|
|
26
|
-
`)}}),e.contents()}}Wt.prototype.SKIP={};Object.keys(gi).forEach(t=>{const e=gi[t];Object.defineProperty(Wt.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});U.prototype.allowsSkippingPrecedingSpace=Be("allowsSkippingPrecedingSpace");$e.allowsSkippingPrecedingSpace=Pe.allowsSkippingPrecedingSpace=te.prototype.allowsSkippingPrecedingSpace=Me.prototype.allowsSkippingPrecedingSpace=je.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=function(){return!0};Ie.prototype.allowsSkippingPrecedingSpace=ze.prototype.allowsSkippingPrecedingSpace=Ze.prototype.allowsSkippingPrecedingSpace=We.prototype.allowsSkippingPrecedingSpace=Le.prototype.allowsSkippingPrecedingSpace=Fe.prototype.allowsSkippingPrecedingSpace=Ce.prototype.allowsSkippingPrecedingSpace=function(){return!1};let Hn;Ru(t=>{Hn=t});let zs;U.prototype.assertAllApplicationsAreValid=function(t,e){zs=0,this._assertAllApplicationsAreValid(t,e)};U.prototype._assertAllApplicationsAreValid=Be("_assertAllApplicationsAreValid");$e._assertAllApplicationsAreValid=Pe._assertAllApplicationsAreValid=Me.prototype._assertAllApplicationsAreValid=je.prototype._assertAllApplicationsAreValid=Fe.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=function(t,e){};Ze.prototype._assertAllApplicationsAreValid=function(t,e){zs++,this.expr._assertAllApplicationsAreValid(t,e),zs--};Ie.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};Ce.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};ze.prototype._assertAllApplicationsAreValid=Le.prototype._assertAllApplicationsAreValid=We.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};te.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const s=e.rules[this.ruleName],r=nn(t)&&zs===0;if(!s)throw xu(this.ruleName,e.name,this.source);if(!n&&nn(this.ruleName)&&!r)throw cf(this.ruleName,this);const i=this.args.length,o=s.formals.length;if(i!==o)throw rf(this.ruleName,o,i,this.source);const a=Hn&&s===Hn.rules.applySyntactic;if(Hn&&s===Hn.rules.caseInsensitive&&!(this.args[0]instanceof Me))throw na('a Terminal (e.g. "abc")',this.args[0]);if(a){const u=this.args[0];if(!(u instanceof te))throw na("a syntactic rule application",u);if(!nn(u.ruleName))throw uf(u);if(r)throw lf(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,a),u.getArity()!==1)throw of(this.ruleName,u)})};U.prototype.assertChoicesHaveUniformArity=Be("assertChoicesHaveUniformArity");$e.assertChoicesHaveUniformArity=Pe.assertChoicesHaveUniformArity=Me.prototype.assertChoicesHaveUniformArity=je.prototype.assertChoicesHaveUniformArity=Fe.prototype.assertChoicesHaveUniformArity=Ze.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=function(t){};Ie.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){const s=this.terms[n];s.assertChoicesHaveUniformArity();const r=s.getArity();if(e!==r)throw Tu(t,e,r,s)}};kr.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw Tu(t,n,e,this.terms[0])};Ce.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};ze.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Le.prototype.assertChoicesHaveUniformArity=function(t){};We.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};te.prototype.assertChoicesHaveUniformArity=function(t){};U.prototype.assertIteratedExprsAreNotNullable=Be("assertIteratedExprsAreNotNullable");$e.assertIteratedExprsAreNotNullable=Pe.assertIteratedExprsAreNotNullable=Me.prototype.assertIteratedExprsAreNotNullable=je.prototype.assertIteratedExprsAreNotNullable=Fe.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=function(t){};Ie.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Ce.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};ze.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw Ou(this,[])};$t.prototype.assertIteratedExprsAreNotNullable=Le.prototype.assertIteratedExprsAreNotNullable=We.prototype.assertIteratedExprsAreNotNullable=Ze.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};te.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class io{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class mn extends io{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Rf extends io{constructor(e,n,s,r){super(r),this.ruleName=e,this.children=n,this.childOffsets=s}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return Au(this.ctorName)}isSyntactic(){return nn(this.ctorName)}}class Mu extends io{constructor(e,n,s,r){super(s),this.children=e,this.childOffsets=n,this.optional=r}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}U.prototype.eval=Be("eval");$e.eval=function(t){const{inputStream:e}=t,n=e.pos,s=e.nextCodePoint();return s!==void 0?(t.pushBinding(new mn(String.fromCodePoint(s).length),n),!0):(t.processFailure(n,this),!1)};Pe.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new mn(0),n),!0):(t.processFailure(n,this),!1)};Me.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new mn(this.obj.length),n),!0):(t.processFailure(n,this),!1)};je.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return s!==void 0&&this.from.codePointAt(0)<=s&&s<=this.to.codePointAt(0)?(t.pushBinding(new mn(String.fromCodePoint(s).length),n),!0):(t.processFailure(n,this),!1)};Fe.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};Ze.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};Ie.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Ce.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const n=this.factors[e];if(!t.eval(n))return!1}return!0};ze.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=this.getArity(),r=[],i=[];for(;r.length<s;)r.push([]),i.push([]);let o=0,a=n,c;for(;o<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===a)throw Ou(this,t._applicationStack);a=e.pos,o++;const f=t._bindings.splice(t._bindings.length-s,s),p=t._bindingOffsets.splice(t._bindingOffsets.length-s,s);for(c=0;c<f.length;c++)r[c].push(f[c]),i[c].push(p[c])}if(o<this.minNumMatches)return!1;let u=t.posToOffset(n),l=0;if(o>0){const f=r[s-1],p=i[s-1],h=p[p.length-1]+f[f.length-1].matchLength;u=i[0][0],l=h-u}const d=this instanceof $t;for(c=0;c<r.length;c++)t._bindings.push(new Mu(r[c],i[c],l,d)),t._bindingOffsets.push(u);return!0};Le.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const s=t.eval(this.expr);return t.popFailuresInfo(),s?(t.processFailure(n,this),!1):(e.pos=n,!0)};We.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};te.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],s=this.substituteParams(n),r=t.getCurrentPosInfo();if(r.isActive(s))return s.handleCycle(t);const i=s.toMemoKey(),o=r.memo[i];if(o&&r.shouldUseMemoizedResult(o)){if(t.hasNecessaryInfo(o))return t.useMemoizedResult(t.inputStream.pos,o);delete r.memo[i]}return s.reallyEval(t)};te.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,s=this.toMemoKey();let r=e.memo[s];return n&&n.headApplication.toMemoKey()===s?r.updateInvolvedApplicationMemoKeys():r||(r=e.memoize(s,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,r)),t.useMemoizedResult(t.inputStream.pos,r)};te.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,s=t.getCurrentPosInfo(),r=t.grammar.rules[this.ruleName],{body:i}=r,{description:o}=r;t.enterApplication(s,this),o&&t.pushFailuresInfo();const a=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=s.currentLeftRecursion,l=this.toMemoKey(),d=u&&u.headApplication.toMemoKey()===l;let f;t.doNotMemoize?t.doNotMemoize=!1:d?(c=this.growSeedResult(i,t,n,u,c),s.endLeftRecursion(),f=u,f.examinedLength=e.examinedLength-n,f.rightmostFailureOffset=t._getRightmostFailureOffset(),s.memoize(l,f)):(!u||!u.isInvolved(l))&&(f=s.memoize(l,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const p=!!c;if(o&&(t.popFailuresInfo(),p||t.processFailure(n,this),f&&(f.failuresAtRightmostPosition=t.cloneRecordedFailures(),f.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&f){const h=t.getTraceEntry(n,this,p,p?[c]:[]);d&&(Yt(h.terminatingLREntry!=null||!p),h.isHeadOfLeftRecursion=!0),f.traceEntry=h}return e.examinedLength=Math.max(e.examinedLength,a),t.exitApplication(s,c),p};te.prototype.evalOnce=function(t,e){const{inputStream:n}=e,s=n.pos;if(e.eval(t)){const r=t.getArity(),i=e._bindings.splice(e._bindings.length-r,r),o=e._bindingOffsets.splice(e._bindingOffsets.length-r,r),a=n.pos-s;return new Rf(this.ruleName,i,o,a)}else return!1};te.prototype.growSeedResult=function(t,e,n,s,r){if(!r)return!1;const{inputStream:i}=e;for(;;){if(s.matchLength=i.pos-n,s.value=r,s.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const o=e.trace[e.trace.length-1];s.traceEntry=new Wt(e.input,n,i.pos,this,!0,[r],[o.clone()])}if(i.pos=n,r=this.evalOnce(t,e),i.pos-n<=s.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&s.traceEntry.recordLRTermination(e.trace.pop(),r),i.pos=n+s.matchLength,s.value};Ne.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=e.nextCodePoint();if(s!==void 0&&s<=wf){const r=String.fromCodePoint(s);if(this.pattern.test(r))return t.pushBinding(new mn(r.length),n),!0}return t.processFailure(n,this),!1};U.prototype.getArity=Be("getArity");$e.getArity=Pe.getArity=Me.prototype.getArity=je.prototype.getArity=Fe.prototype.getArity=te.prototype.getArity=Ne.prototype.getArity=function(){return 1};Ie.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Ce.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};ze.prototype.getArity=function(){return this.expr.getArity()};Le.prototype.getArity=function(){return 0};We.prototype.getArity=Ze.prototype.getArity=function(){return this.expr.getArity()};function lt(t,e){const n={};if(t.source&&e){const s=t.source.relativeTo(e);n.sourceInterval=[s.startIdx,s.endIdx]}return n}U.prototype.outputRecipe=Be("outputRecipe");$e.outputRecipe=function(t,e){return["any",lt(this,e)]};Pe.outputRecipe=function(t,e){return["end",lt(this,e)]};Me.prototype.outputRecipe=function(t,e){return["terminal",lt(this,e),this.obj]};je.prototype.outputRecipe=function(t,e){return["range",lt(this,e),this.from,this.to]};Fe.prototype.outputRecipe=function(t,e){return["param",lt(this,e),this.index]};Ie.prototype.outputRecipe=function(t,e){return["alt",lt(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};kr.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Er.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),s=this.terms.slice(this.expansionPos+1);return["splice",lt(this,e),n.map(r=>r.outputRecipe(t,e)),s.map(r=>r.outputRecipe(t,e))]};Ce.prototype.outputRecipe=function(t,e){return["seq",lt(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};pn.prototype.outputRecipe=Nn.prototype.outputRecipe=$t.prototype.outputRecipe=Le.prototype.outputRecipe=We.prototype.outputRecipe=Ze.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),lt(this,e),this.expr.outputRecipe(t,e)]};te.prototype.outputRecipe=function(t,e){return["app",lt(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};Ne.prototype.outputRecipe=function(t,e){return["unicodeChar",lt(this,e),this.categoryOrProp]};U.prototype.introduceParams=Be("introduceParams");$e.introduceParams=Pe.introduceParams=Me.prototype.introduceParams=je.prototype.introduceParams=Fe.prototype.introduceParams=Ne.prototype.introduceParams=function(t){return this};Ie.prototype.introduceParams=function(t){return this.terms.forEach((e,n,s)=>{s[n]=e.introduceParams(t)}),this};Ce.prototype.introduceParams=function(t){return this.factors.forEach((e,n,s)=>{s[n]=e.introduceParams(t)}),this};ze.prototype.introduceParams=Le.prototype.introduceParams=We.prototype.introduceParams=Ze.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};te.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Fe(e).withSource(this.source)}else return this.args.forEach((n,s,r)=>{r[s]=n.introduceParams(t)}),this};U.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};U.prototype._isNullable=Be("_isNullable");$e._isNullable=je.prototype._isNullable=Fe.prototype._isNullable=Nn.prototype._isNullable=Ne.prototype._isNullable=function(t,e){return!1};Pe._isNullable=function(t,e){return!0};Me.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};Ie.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};Ce.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};pn.prototype._isNullable=$t.prototype._isNullable=Le.prototype._isNullable=We.prototype._isNullable=function(t,e){return!0};Ze.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};te.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:s}=t.rules[this.ruleName],r=s.substituteParams(this.args);e[n]=!1,e[n]=r._isNullable(t,e)}return e[n]};U.prototype.substituteParams=Be("substituteParams");$e.substituteParams=Pe.substituteParams=Me.prototype.substituteParams=je.prototype.substituteParams=Ne.prototype.substituteParams=function(t){return this};Fe.prototype.substituteParams=function(t){return Iu(t[this.index])};Ie.prototype.substituteParams=function(t){return new Ie(this.terms.map(e=>e.substituteParams(t)))};Ce.prototype.substituteParams=function(t){return new Ce(this.factors.map(e=>e.substituteParams(t)))};ze.prototype.substituteParams=Le.prototype.substituteParams=We.prototype.substituteParams=Ze.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};te.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new te(this.ruleName,e)}};function ia(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function oo(t){const e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let s=1;t.forEach((r,i)=>{r===n&&(t[i]=r+"_"+s++)})})}U.prototype.toArgumentNameList=Be("toArgumentNameList");$e.toArgumentNameList=function(t,e){return["any"]};Pe.toArgumentNameList=function(t,e){return["end"]};Me.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};je.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return ia(n)||(n="_"+n),ia(n)||(n="$"+t),[n]};Ie.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(i=>i.toArgumentNameList(t,!0)),s=[],r=n[0].length;for(let i=0;i<r;i++){const o=[];for(let c=0;c<this.terms.length;c++)o.push(n[c][i]);const a=Su(o);s.push(a.join("_or_"))}return e||oo(s),s};Ce.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(s=>{const r=s.toArgumentNameList(t,!0);n=n.concat(r),t+=r.length}),e||oo(n),n};ze.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(s=>s[s.length-1]==="s"?s+"es":s+"s");return e||oo(n),n};$t.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};Le.prototype.toArgumentNameList=function(t,e){return[]};We.prototype.toArgumentNameList=Ze.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};te.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ne.prototype.toArgumentNameList=function(t,e){return["$"+t]};Fe.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};U.prototype.toDisplayString=Be("toDisplayString");Ie.prototype.toDisplayString=Ce.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};$e.toDisplayString=Pe.toDisplayString=ze.prototype.toDisplayString=Le.prototype.toDisplayString=We.prototype.toDisplayString=Ze.prototype.toDisplayString=Me.prototype.toDisplayString=je.prototype.toDisplayString=Fe.prototype.toDisplayString=function(){return this.toString()};te.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ne.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function Lf(t){return t==="description"||t==="string"||t==="code"}class Je{constructor(e,n,s){if(!Lf(s))throw new Error("invalid Failure type: "+s);this.pexpr=e,this.text=n,this.type=s,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Je(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}U.prototype.toFailure=Be("toFailure");$e.toFailure=function(t){return new Je(this,"any object","description")};Pe.toFailure=function(t){return new Je(this,"end of input","description")};Me.prototype.toFailure=function(t){return new Je(this,this.obj,"string")};je.prototype.toFailure=function(t){return new Je(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Le.prototype.toFailure=function(t){const e=this.expr===$e?"nothing":"not "+this.expr.toFailure(t);return new Je(this,e,"description")};We.prototype.toFailure=function(t){return this.expr.toFailure(t)};te.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Je(this,e,"description")};Ne.prototype.toFailure=function(t){return new Je(this,"a Unicode ["+this.categoryOrProp+"] character","description")};Ie.prototype.toFailure=function(t){const n="("+this.terms.map(s=>s.toFailure(t)).join(" or ")+")";return new Je(this,n,"description")};Ce.prototype.toFailure=function(t){const n="("+this.factors.map(s=>s.toFailure(t)).join(" ")+")";return new Je(this,n,"description")};ze.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Je(this,e,"description")};U.prototype.toString=Be("toString");$e.toString=function(){return"any"};Pe.toString=function(){return"end"};Me.prototype.toString=function(){return JSON.stringify(this.obj)};je.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Fe.prototype.toString=function(){return"$"+this.index};Ze.prototype.toString=function(){return"#("+this.expr.toString()+")"};Ie.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Ce.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};ze.prototype.toString=function(){return this.expr+this.operator};Le.prototype.toString=function(){return"~"+this.expr};We.prototype.toString=function(){return"&"+this.expr};te.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ne.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class ao extends U{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return Yt(n instanceof Me,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,s=n.pos,r=this._getString(e);return n.matchString(r,!0)?(e.pushBinding(new mn(r.length),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}substituteParams(e){return new ao(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Je(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let Du;Ru(t=>{Du=t.rules.applySyntactic.body});const zr=new te("spaces");class Nf{constructor(e,n,s){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Ir(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],s!==void 0&&(this.positionToRecordFailures=s,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){const s=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,s)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(zr),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==zr?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new Sf),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const s=this.currentApplication();s&&(n=n.substituteParams(s.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const s=e.toKey();this.recordedFailures[s]?this.recordedFailures[s].isFluffy()&&!e.isFluffy()&&this.recordedFailures[s].clearFluffy():this.recordedFailures[s]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(s=>{this.recordFailure(e[s],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){const s=this.memoTable[e];if(s&&n instanceof te){const r=s.memo[n.toMemoKey()];if(r&&r.traceEntry){const i=r.traceEntry.cloneWithExpr(n);return i.isMemoized=!0,i}}return null}getTraceEntry(e,n,s,r){if(n instanceof te){const i=this.currentApplication(),o=i?i.args:[];n=n.substituteParams(o)}return this.getMemoizedTraceEntry(e,n)||new Wt(this.input,e,this.inputStream.pos,n,s,r,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);const s=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,s),this.recordedFailures&&this.positionToRecordFailures===s&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){const{inputStream:n}=this,s=this._bindings.length,r=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const o=n.pos,a=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const l=this._bindings.slice(s),d=this.getTraceEntry(a,e,u,l);d.isImplicitSpaces=e===zr,d.isRootNode=e===this.startExpr,c.push(d),this.trace=c}return u?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(l=>{this.recordedFailures[l].makeFluffy()}):(n.pos=o,this.truncateBindings(s),this.userData=r),this.recordedFailures&&this.recordFailures(i,!1),e===Du&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(s=>this.recordedFailures[s]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new Lu(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Mf{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,s){const r=this._input,i=this._memoTable;if(e<0||e>r.length||n<0||n>r.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=r.slice(0,e)+s+r.slice(n),this._input!==r&&i.length>0&&(this._isMemoTableStale=!0);const o=i.slice(n);i.length=e;for(let a=0;a<s.length;a++)i.push(void 0);for(const a of o)i.push(a);for(let a=0;a<e;a++){const c=i[a];c&&c.clearObsoleteEntries(a,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){const s={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!s.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw tf(this.grammar);const r=new Nf(this,e,s.positionToRecordFailures);return s.tracing?r.getTrace():r.getMatchResult()}_getStartExpr(e){const n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const s=this.grammar.parseApplication(n);return new Ce([s,Pe])}}const Kn=[],yi=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class oa{constructor(e,n,s){this._node=e,this.source=n,this._baseInterval=s,e.isNonterminal()&&Yt(n===s),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){const s=this._node.childAt(e),r=this._node.childOffsets[e],i=this._baseInterval.subInterval(r,s.matchLength),o=s.isNonterminal()?i:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(s,i,o)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const n=e||[],s=n.map(o=>o._node),r=new Mu(s,[],-1,!1),i=this._semantics.wrap(r,null,null);return i._childWrappers=n,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class Ke{constructor(e,n){const s=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:oa){constructor(r,i,o){super(r,i,o),s.checkActionDictsIfHaventAlready(),this._semantics=s}toString(){return"[semantics wrapper for "+s.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const r in this.attributes)Object.defineProperty(this.attributeKeys,r,{value:ra(r)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(r){return r.super!==Ke.BuiltInSemantics._getSemantics()}let s=`(function(g) {
|
|
25
|
+
`,u+1);o=d===-1?t.slice(u):t.slice(u,d),o=o.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(a=t.slice(c,i).replace(/\r?\n$/,""));const l=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:s,line:l,prevLine:a,nextLine:o,toString:Sf}}function ro(t,e,...n){return so(t,e).toString(...n)}const ra=(()=>{let t=0;return e=>""+e+t++})();class De{constructor(e,n,s){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=n,this.endIdx=s}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return De.coverage(...e,this)}collapsedLeft(){return new De(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new De(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return so(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return ro(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw pi();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new De(this.sourceString,this.startIdx,e.startIdx),new De(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new De(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new De(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw pi();return Yt(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new De(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,s=this.endIdx-e.match(/\s*$/)[0].length;return new De(this.sourceString,n,s)}subInterval(e,n){const s=this.startIdx+e;return new De(this.sourceString,s,s+n)}}De.coverage=function(t,...e){let{startIdx:n,endIdx:s}=t;for(const r of e){if(r.sourceString!==t.sourceString)throw pi();n=Math.min(n,r.startIdx),s=Math.max(s,r.endIdx)}return new De(t.sourceString,n,s)};const kf=65535,Ef=1114111;class Ir{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){const e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){const e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){const e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){const e=this.source.slice(this.pos++).codePointAt(0);return e>kf&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let s;if(n){for(s=0;s<e.length;s++){const r=this.next(),i=e[s];if(r==null||r.toUpperCase()!==i.toUpperCase())return!1}return!0}for(s=0;s<e.length;s++)if(this.next()!==e[s])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new De(this.source,e,n||this.pos)}}class Lu{constructor(e,n,s,r,i,o,a){this.matcher=e,this.input=n,this.startExpr=s,this._cst=r,this._cstOffset=i,this._rightmostFailurePosition=o,this._rightmostFailures=a,this.failed()&&(di(this,"message",function(){const c="Expected "+this.getExpectedText();return ro(this.input,this.getRightmostFailurePosition())+c}),di(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=so(this.input,this.getRightmostFailurePosition());return"Line "+u.lineNum+", col "+u.colNum+": "+c}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new hn;let n=this.getRightmostFailures();n=n.filter(s=>!s.isFluffy());for(let s=0;s<n.length;s++)s>0&&(s===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[s].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new De(this.input,e,e)}}class If{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,n){n.isLeftRecursion=!0,n.headApplication=e,n.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=n;const{applicationMemoKeyStack:s}=this,r=s.indexOf(e.toMemoKey())+1,i=s.slice(r);n.isInvolved=function(o){return i.indexOf(o)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let o=r;o<s.length;o++){const a=s[o];this.isInvolved(a)||i.push(a)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:n}=this;for(let s=0;s<n.length;s++){const r=n[s];if(e.isInvolved(r))return!1}return!0}memoize(e,n){return this.memo[e]=n,this.maxExaminedLength=Math.max(this.maxExaminedLength,n.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,n.rightmostFailureOffset),n}clearObsoleteEntries(e,n){if(e+this.maxExaminedLength<=n)return;const{memo:s}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(s).forEach(r=>{const i=s[r];e+i.examinedLength>n?delete s[r]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const _f="✗",xf="✓",Cf="⋅",Of="⇒",Tf="␉",Rf="␊",Lf="␍",gi={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function Nf(t){return Ar(" ",t).join("")}function Mf(t,e,n){const s=Nu(t.slice(e,e+n));return s.length<n?s+Ar(" ",n-s.length).join(""):s}function Nu(t){return typeof t=="string"?t.replace(/ /g,Cf).replace(/\t/g,Tf).replace(/\n/g,Rf).replace(/\r/g,Lf):String(t)}class Wt{constructor(e,n,s,r,i,o,a){this.input=e,this.pos=this.pos1=n,this.pos2=s,this.source=new De(e,n,s),this.expr=r,this.bindings=o,this.children=a||[],this.terminatingLREntry=null,this._flags=i?gi.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const n=new Wt(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return n.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,n.isImplicitSpaces=this.isImplicitSpaces,n.isMemoized=this.isMemoized,n.isRootNode=this.isRootNode,n.terminatesLR=this.terminatesLR,n.terminatingLREntry=this.terminatingLREntry,n}recordLRTermination(e,n){this.terminatingLREntry=new Wt(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let s=e;typeof s=="function"&&(s={enter:s});function r(i,o,a){let c=!0;s.enter&&s.enter.call(n,i,o,a)===Wt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{r(u,i,a+1)}),s.exit&&s.exit.call(n,i,o,a))}this.isRootNode?this.children.forEach(i=>{r(i,null,0)}):r(this,null,0)}toString(){const e=new hn;return this.walk((n,s,r)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(Mf(n.input,n.pos,10)+Nf(r*2+1)),e.append((n.succeeded?xf:_f)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){const o=Nu(n.source.contents);e.append(" "+Of+" "),e.append(typeof o=="string"?'"'+o+'"':o)}e.append(`
|
|
26
|
+
`)}}),e.contents()}}Wt.prototype.SKIP={};Object.keys(gi).forEach(t=>{const e=gi[t];Object.defineProperty(Wt.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});U.prototype.allowsSkippingPrecedingSpace=Be("allowsSkippingPrecedingSpace");$e.allowsSkippingPrecedingSpace=Pe.allowsSkippingPrecedingSpace=te.prototype.allowsSkippingPrecedingSpace=Me.prototype.allowsSkippingPrecedingSpace=je.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=function(){return!0};Ie.prototype.allowsSkippingPrecedingSpace=ze.prototype.allowsSkippingPrecedingSpace=Ze.prototype.allowsSkippingPrecedingSpace=We.prototype.allowsSkippingPrecedingSpace=Le.prototype.allowsSkippingPrecedingSpace=Fe.prototype.allowsSkippingPrecedingSpace=Ce.prototype.allowsSkippingPrecedingSpace=function(){return!1};let Hn;Ru(t=>{Hn=t});let zs;U.prototype.assertAllApplicationsAreValid=function(t,e){zs=0,this._assertAllApplicationsAreValid(t,e)};U.prototype._assertAllApplicationsAreValid=Be("_assertAllApplicationsAreValid");$e._assertAllApplicationsAreValid=Pe._assertAllApplicationsAreValid=Me.prototype._assertAllApplicationsAreValid=je.prototype._assertAllApplicationsAreValid=Fe.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=function(t,e){};Ze.prototype._assertAllApplicationsAreValid=function(t,e){zs++,this.expr._assertAllApplicationsAreValid(t,e),zs--};Ie.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};Ce.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};ze.prototype._assertAllApplicationsAreValid=Le.prototype._assertAllApplicationsAreValid=We.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};te.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const s=e.rules[this.ruleName],r=nn(t)&&zs===0;if(!s)throw xu(this.ruleName,e.name,this.source);if(!n&&nn(this.ruleName)&&!r)throw ff(this.ruleName,this);const i=this.args.length,o=s.formals.length;if(i!==o)throw uf(this.ruleName,o,i,this.source);const a=Hn&&s===Hn.rules.applySyntactic;if(Hn&&s===Hn.rules.caseInsensitive&&!(this.args[0]instanceof Me))throw na('a Terminal (e.g. "abc")',this.args[0]);if(a){const u=this.args[0];if(!(u instanceof te))throw na("a syntactic rule application",u);if(!nn(u.ruleName))throw hf(u);if(r)throw pf(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,a),u.getArity()!==1)throw lf(this.ruleName,u)})};U.prototype.assertChoicesHaveUniformArity=Be("assertChoicesHaveUniformArity");$e.assertChoicesHaveUniformArity=Pe.assertChoicesHaveUniformArity=Me.prototype.assertChoicesHaveUniformArity=je.prototype.assertChoicesHaveUniformArity=Fe.prototype.assertChoicesHaveUniformArity=Ze.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=function(t){};Ie.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){const s=this.terms[n];s.assertChoicesHaveUniformArity();const r=s.getArity();if(e!==r)throw Tu(t,e,r,s)}};kr.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw Tu(t,n,e,this.terms[0])};Ce.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};ze.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Le.prototype.assertChoicesHaveUniformArity=function(t){};We.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};te.prototype.assertChoicesHaveUniformArity=function(t){};U.prototype.assertIteratedExprsAreNotNullable=Be("assertIteratedExprsAreNotNullable");$e.assertIteratedExprsAreNotNullable=Pe.assertIteratedExprsAreNotNullable=Me.prototype.assertIteratedExprsAreNotNullable=je.prototype.assertIteratedExprsAreNotNullable=Fe.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=function(t){};Ie.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Ce.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};ze.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw Ou(this,[])};$t.prototype.assertIteratedExprsAreNotNullable=Le.prototype.assertIteratedExprsAreNotNullable=We.prototype.assertIteratedExprsAreNotNullable=Ze.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};te.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class io{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class mn extends io{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Df extends io{constructor(e,n,s,r){super(r),this.ruleName=e,this.children=n,this.childOffsets=s}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return Au(this.ctorName)}isSyntactic(){return nn(this.ctorName)}}class Mu extends io{constructor(e,n,s,r){super(s),this.children=e,this.childOffsets=n,this.optional=r}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}U.prototype.eval=Be("eval");$e.eval=function(t){const{inputStream:e}=t,n=e.pos,s=e.nextCodePoint();return s!==void 0?(t.pushBinding(new mn(String.fromCodePoint(s).length),n),!0):(t.processFailure(n,this),!1)};Pe.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new mn(0),n),!0):(t.processFailure(n,this),!1)};Me.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new mn(this.obj.length),n),!0):(t.processFailure(n,this),!1)};je.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return s!==void 0&&this.from.codePointAt(0)<=s&&s<=this.to.codePointAt(0)?(t.pushBinding(new mn(String.fromCodePoint(s).length),n),!0):(t.processFailure(n,this),!1)};Fe.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};Ze.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};Ie.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Ce.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const n=this.factors[e];if(!t.eval(n))return!1}return!0};ze.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=this.getArity(),r=[],i=[];for(;r.length<s;)r.push([]),i.push([]);let o=0,a=n,c;for(;o<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===a)throw Ou(this,t._applicationStack);a=e.pos,o++;const f=t._bindings.splice(t._bindings.length-s,s),p=t._bindingOffsets.splice(t._bindingOffsets.length-s,s);for(c=0;c<f.length;c++)r[c].push(f[c]),i[c].push(p[c])}if(o<this.minNumMatches)return!1;let u=t.posToOffset(n),l=0;if(o>0){const f=r[s-1],p=i[s-1],h=p[p.length-1]+f[f.length-1].matchLength;u=i[0][0],l=h-u}const d=this instanceof $t;for(c=0;c<r.length;c++)t._bindings.push(new Mu(r[c],i[c],l,d)),t._bindingOffsets.push(u);return!0};Le.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const s=t.eval(this.expr);return t.popFailuresInfo(),s?(t.processFailure(n,this),!1):(e.pos=n,!0)};We.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};te.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],s=this.substituteParams(n),r=t.getCurrentPosInfo();if(r.isActive(s))return s.handleCycle(t);const i=s.toMemoKey(),o=r.memo[i];if(o&&r.shouldUseMemoizedResult(o)){if(t.hasNecessaryInfo(o))return t.useMemoizedResult(t.inputStream.pos,o);delete r.memo[i]}return s.reallyEval(t)};te.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,s=this.toMemoKey();let r=e.memo[s];return n&&n.headApplication.toMemoKey()===s?r.updateInvolvedApplicationMemoKeys():r||(r=e.memoize(s,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,r)),t.useMemoizedResult(t.inputStream.pos,r)};te.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,s=t.getCurrentPosInfo(),r=t.grammar.rules[this.ruleName],{body:i}=r,{description:o}=r;t.enterApplication(s,this),o&&t.pushFailuresInfo();const a=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=s.currentLeftRecursion,l=this.toMemoKey(),d=u&&u.headApplication.toMemoKey()===l;let f;t.doNotMemoize?t.doNotMemoize=!1:d?(c=this.growSeedResult(i,t,n,u,c),s.endLeftRecursion(),f=u,f.examinedLength=e.examinedLength-n,f.rightmostFailureOffset=t._getRightmostFailureOffset(),s.memoize(l,f)):(!u||!u.isInvolved(l))&&(f=s.memoize(l,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const p=!!c;if(o&&(t.popFailuresInfo(),p||t.processFailure(n,this),f&&(f.failuresAtRightmostPosition=t.cloneRecordedFailures(),f.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&f){const h=t.getTraceEntry(n,this,p,p?[c]:[]);d&&(Yt(h.terminatingLREntry!=null||!p),h.isHeadOfLeftRecursion=!0),f.traceEntry=h}return e.examinedLength=Math.max(e.examinedLength,a),t.exitApplication(s,c),p};te.prototype.evalOnce=function(t,e){const{inputStream:n}=e,s=n.pos;if(e.eval(t)){const r=t.getArity(),i=e._bindings.splice(e._bindings.length-r,r),o=e._bindingOffsets.splice(e._bindingOffsets.length-r,r),a=n.pos-s;return new Df(this.ruleName,i,o,a)}else return!1};te.prototype.growSeedResult=function(t,e,n,s,r){if(!r)return!1;const{inputStream:i}=e;for(;;){if(s.matchLength=i.pos-n,s.value=r,s.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const o=e.trace[e.trace.length-1];s.traceEntry=new Wt(e.input,n,i.pos,this,!0,[r],[o.clone()])}if(i.pos=n,r=this.evalOnce(t,e),i.pos-n<=s.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&s.traceEntry.recordLRTermination(e.trace.pop(),r),i.pos=n+s.matchLength,s.value};Ne.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,s=e.nextCodePoint();if(s!==void 0&&s<=Ef){const r=String.fromCodePoint(s);if(this.pattern.test(r))return t.pushBinding(new mn(r.length),n),!0}return t.processFailure(n,this),!1};U.prototype.getArity=Be("getArity");$e.getArity=Pe.getArity=Me.prototype.getArity=je.prototype.getArity=Fe.prototype.getArity=te.prototype.getArity=Ne.prototype.getArity=function(){return 1};Ie.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Ce.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};ze.prototype.getArity=function(){return this.expr.getArity()};Le.prototype.getArity=function(){return 0};We.prototype.getArity=Ze.prototype.getArity=function(){return this.expr.getArity()};function lt(t,e){const n={};if(t.source&&e){const s=t.source.relativeTo(e);n.sourceInterval=[s.startIdx,s.endIdx]}return n}U.prototype.outputRecipe=Be("outputRecipe");$e.outputRecipe=function(t,e){return["any",lt(this,e)]};Pe.outputRecipe=function(t,e){return["end",lt(this,e)]};Me.prototype.outputRecipe=function(t,e){return["terminal",lt(this,e),this.obj]};je.prototype.outputRecipe=function(t,e){return["range",lt(this,e),this.from,this.to]};Fe.prototype.outputRecipe=function(t,e){return["param",lt(this,e),this.index]};Ie.prototype.outputRecipe=function(t,e){return["alt",lt(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};kr.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Er.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),s=this.terms.slice(this.expansionPos+1);return["splice",lt(this,e),n.map(r=>r.outputRecipe(t,e)),s.map(r=>r.outputRecipe(t,e))]};Ce.prototype.outputRecipe=function(t,e){return["seq",lt(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};pn.prototype.outputRecipe=Nn.prototype.outputRecipe=$t.prototype.outputRecipe=Le.prototype.outputRecipe=We.prototype.outputRecipe=Ze.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),lt(this,e),this.expr.outputRecipe(t,e)]};te.prototype.outputRecipe=function(t,e){return["app",lt(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};Ne.prototype.outputRecipe=function(t,e){return["unicodeChar",lt(this,e),this.categoryOrProp]};U.prototype.introduceParams=Be("introduceParams");$e.introduceParams=Pe.introduceParams=Me.prototype.introduceParams=je.prototype.introduceParams=Fe.prototype.introduceParams=Ne.prototype.introduceParams=function(t){return this};Ie.prototype.introduceParams=function(t){return this.terms.forEach((e,n,s)=>{s[n]=e.introduceParams(t)}),this};Ce.prototype.introduceParams=function(t){return this.factors.forEach((e,n,s)=>{s[n]=e.introduceParams(t)}),this};ze.prototype.introduceParams=Le.prototype.introduceParams=We.prototype.introduceParams=Ze.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};te.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Fe(e).withSource(this.source)}else return this.args.forEach((n,s,r)=>{r[s]=n.introduceParams(t)}),this};U.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};U.prototype._isNullable=Be("_isNullable");$e._isNullable=je.prototype._isNullable=Fe.prototype._isNullable=Nn.prototype._isNullable=Ne.prototype._isNullable=function(t,e){return!1};Pe._isNullable=function(t,e){return!0};Me.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};Ie.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};Ce.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};pn.prototype._isNullable=$t.prototype._isNullable=Le.prototype._isNullable=We.prototype._isNullable=function(t,e){return!0};Ze.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};te.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:s}=t.rules[this.ruleName],r=s.substituteParams(this.args);e[n]=!1,e[n]=r._isNullable(t,e)}return e[n]};U.prototype.substituteParams=Be("substituteParams");$e.substituteParams=Pe.substituteParams=Me.prototype.substituteParams=je.prototype.substituteParams=Ne.prototype.substituteParams=function(t){return this};Fe.prototype.substituteParams=function(t){return Iu(t[this.index])};Ie.prototype.substituteParams=function(t){return new Ie(this.terms.map(e=>e.substituteParams(t)))};Ce.prototype.substituteParams=function(t){return new Ce(this.factors.map(e=>e.substituteParams(t)))};ze.prototype.substituteParams=Le.prototype.substituteParams=We.prototype.substituteParams=Ze.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};te.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new te(this.ruleName,e)}};function ia(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function oo(t){const e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let s=1;t.forEach((r,i)=>{r===n&&(t[i]=r+"_"+s++)})})}U.prototype.toArgumentNameList=Be("toArgumentNameList");$e.toArgumentNameList=function(t,e){return["any"]};Pe.toArgumentNameList=function(t,e){return["end"]};Me.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};je.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return ia(n)||(n="_"+n),ia(n)||(n="$"+t),[n]};Ie.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(i=>i.toArgumentNameList(t,!0)),s=[],r=n[0].length;for(let i=0;i<r;i++){const o=[];for(let c=0;c<this.terms.length;c++)o.push(n[c][i]);const a=Su(o);s.push(a.join("_or_"))}return e||oo(s),s};Ce.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(s=>{const r=s.toArgumentNameList(t,!0);n=n.concat(r),t+=r.length}),e||oo(n),n};ze.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(s=>s[s.length-1]==="s"?s+"es":s+"s");return e||oo(n),n};$t.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};Le.prototype.toArgumentNameList=function(t,e){return[]};We.prototype.toArgumentNameList=Ze.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};te.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ne.prototype.toArgumentNameList=function(t,e){return["$"+t]};Fe.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};U.prototype.toDisplayString=Be("toDisplayString");Ie.prototype.toDisplayString=Ce.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};$e.toDisplayString=Pe.toDisplayString=ze.prototype.toDisplayString=Le.prototype.toDisplayString=We.prototype.toDisplayString=Ze.prototype.toDisplayString=Me.prototype.toDisplayString=je.prototype.toDisplayString=Fe.prototype.toDisplayString=function(){return this.toString()};te.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ne.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function $f(t){return t==="description"||t==="string"||t==="code"}class Je{constructor(e,n,s){if(!$f(s))throw new Error("invalid Failure type: "+s);this.pexpr=e,this.text=n,this.type=s,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Je(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}U.prototype.toFailure=Be("toFailure");$e.toFailure=function(t){return new Je(this,"any object","description")};Pe.toFailure=function(t){return new Je(this,"end of input","description")};Me.prototype.toFailure=function(t){return new Je(this,this.obj,"string")};je.prototype.toFailure=function(t){return new Je(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Le.prototype.toFailure=function(t){const e=this.expr===$e?"nothing":"not "+this.expr.toFailure(t);return new Je(this,e,"description")};We.prototype.toFailure=function(t){return this.expr.toFailure(t)};te.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Je(this,e,"description")};Ne.prototype.toFailure=function(t){return new Je(this,"a Unicode ["+this.categoryOrProp+"] character","description")};Ie.prototype.toFailure=function(t){const n="("+this.terms.map(s=>s.toFailure(t)).join(" or ")+")";return new Je(this,n,"description")};Ce.prototype.toFailure=function(t){const n="("+this.factors.map(s=>s.toFailure(t)).join(" ")+")";return new Je(this,n,"description")};ze.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Je(this,e,"description")};U.prototype.toString=Be("toString");$e.toString=function(){return"any"};Pe.toString=function(){return"end"};Me.prototype.toString=function(){return JSON.stringify(this.obj)};je.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Fe.prototype.toString=function(){return"$"+this.index};Ze.prototype.toString=function(){return"#("+this.expr.toString()+")"};Ie.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Ce.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};ze.prototype.toString=function(){return this.expr+this.operator};Le.prototype.toString=function(){return"~"+this.expr};We.prototype.toString=function(){return"&"+this.expr};te.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ne.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class ao extends U{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return Yt(n instanceof Me,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,s=n.pos,r=this._getString(e);return n.matchString(r,!0)?(e.pushBinding(new mn(r.length),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}substituteParams(e){return new ao(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Je(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let Du;Ru(t=>{Du=t.rules.applySyntactic.body});const zr=new te("spaces");class Pf{constructor(e,n,s){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Ir(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],s!==void 0&&(this.positionToRecordFailures=s,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){const s=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,s)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(zr),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==zr?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new If),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const s=this.currentApplication();s&&(n=n.substituteParams(s.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const s=e.toKey();this.recordedFailures[s]?this.recordedFailures[s].isFluffy()&&!e.isFluffy()&&this.recordedFailures[s].clearFluffy():this.recordedFailures[s]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(s=>{this.recordFailure(e[s],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){const s=this.memoTable[e];if(s&&n instanceof te){const r=s.memo[n.toMemoKey()];if(r&&r.traceEntry){const i=r.traceEntry.cloneWithExpr(n);return i.isMemoized=!0,i}}return null}getTraceEntry(e,n,s,r){if(n instanceof te){const i=this.currentApplication(),o=i?i.args:[];n=n.substituteParams(o)}return this.getMemoizedTraceEntry(e,n)||new Wt(this.input,e,this.inputStream.pos,n,s,r,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);const s=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,s),this.recordedFailures&&this.positionToRecordFailures===s&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){const{inputStream:n}=this,s=this._bindings.length,r=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const o=n.pos,a=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const l=this._bindings.slice(s),d=this.getTraceEntry(a,e,u,l);d.isImplicitSpaces=e===zr,d.isRootNode=e===this.startExpr,c.push(d),this.trace=c}return u?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(l=>{this.recordedFailures[l].makeFluffy()}):(n.pos=o,this.truncateBindings(s),this.userData=r),this.recordedFailures&&this.recordFailures(i,!1),e===Du&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(s=>this.recordedFailures[s]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new Lu(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class jf{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,s){const r=this._input,i=this._memoTable;if(e<0||e>r.length||n<0||n>r.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=r.slice(0,e)+s+r.slice(n),this._input!==r&&i.length>0&&(this._isMemoTableStale=!0);const o=i.slice(n);i.length=e;for(let a=0;a<s.length;a++)i.push(void 0);for(const a of o)i.push(a);for(let a=0;a<e;a++){const c=i[a];c&&c.clearObsoleteEntries(a,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){const s={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!s.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw of(this.grammar);const r=new Pf(this,e,s.positionToRecordFailures);return s.tracing?r.getTrace():r.getMatchResult()}_getStartExpr(e){const n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const s=this.grammar.parseApplication(n);return new Ce([s,Pe])}}const Kn=[],yi=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class oa{constructor(e,n,s){this._node=e,this.source=n,this._baseInterval=s,e.isNonterminal()&&Yt(n===s),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){const s=this._node.childAt(e),r=this._node.childOffsets[e],i=this._baseInterval.subInterval(r,s.matchLength),o=s.isNonterminal()?i:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(s,i,o)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const n=e||[],s=n.map(o=>o._node),r=new Mu(s,[],-1,!1),i=this._semantics.wrap(r,null,null);return i._childWrappers=n,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class Ke{constructor(e,n){const s=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:oa){constructor(r,i,o){super(r,i,o),s.checkActionDictsIfHaventAlready(),this._semantics=s}toString(){return"[semantics wrapper for "+s.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const r in this.attributes)Object.defineProperty(this.attributeKeys,r,{value:ra(r)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(r){return r.super!==Ke.BuiltInSemantics._getSemantics()}let s=`(function(g) {
|
|
27
27
|
`;if(n(this)){s+=" var semantics = "+this.super.toRecipe(!0)+"(g";const r=this.super.grammar;let i=this.grammar;for(;i!==r;)s+=".superGrammar",i=i.superGrammar;s+=`);
|
|
28
28
|
`,s+=" return g.extendSemantics(semantics)"}else s+=" return g.createSemantics()";return["Operation","Attribute"].forEach(r=>{const i=this[r.toLowerCase()+"s"];Object.keys(i).forEach(o=>{const{actionDict:a,formals:c,builtInDefault:u}=i[o];let l=o;c.length>0&&(l+="("+c.join(", ")+")");let d;n(this)&&this.super[r.toLowerCase()+"s"][o]?d="extend"+r:d="add"+r,s+=`
|
|
29
29
|
.`+d+"("+JSON.stringify(l)+", {";const f=[];Object.keys(a).forEach(p=>{if(a[p]!==u){let h=a[p].toString().trim();h=h.replace(/^.*\(/,"function("),f.push(`
|
|
@@ -34,11 +34,11 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
34
34
|
var semantics = `+s+`(grammar);
|
|
35
35
|
return semantics;
|
|
36
36
|
});
|
|
37
|
-
`),s}addOperationOrAttribute(e,n,s){const r=e+"s",i=aa(n,e),{name:o}=i,{formals:a}=i;this.assertNewName(o,e);const c=
|
|
38
|
-
`));throw o.problems=r,o}}_topDownActionArity(e){return ca.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){const n={};this.source&&(n.source=this.source.contents);let s=null;this.defaultStartRule&&(s=this.defaultStartRule);const r={};Object.keys(this.rules).forEach(a=>{const c=this.rules[a],{body:u}=c,l=!this.superGrammar||!this.superGrammar.rules[a];let d;l?d="define":d=u instanceof kr?"extend":"override";const f={};if(c.source&&this.source){const m=c.source.relativeTo(this.source);f.sourceInterval=[m.startIdx,m.endIdx]}const p=l?c.description:null,h=u.outputRecipe(c.formals,this.source);r[a]=[d,f,p,c.formals,h]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const o=[...["grammar",n,this.name].map(JSON.stringify),i,...[s,r].map(JSON.stringify)];return
|
|
37
|
+
`),s}addOperationOrAttribute(e,n,s){const r=e+"s",i=aa(n,e),{name:o}=i,{formals:a}=i;this.assertNewName(o,e);const c=Ff(e,o,d),u={_default:c};Object.keys(s).forEach(f=>{u[f]=s[f]});const l=e==="operation"?new ss(o,a,u,c):new bi(o,u,c);l.checkActionDict(this.grammar),this[r][o]=l;function d(...f){const p=this._semantics[r][o];if(arguments.length!==p.formals.length)throw new Error("Invalid number of arguments passed to "+o+" "+e+" (expected "+p.formals.length+", got "+arguments.length+")");const h=Object.create(null);for(const[b,y]of Object.entries(f)){const w=p.formals[b];h[w]=y}const m=this.args;this.args=h;const g=p.execute(this._semantics,this);return this.args=m,g}e==="operation"?(this.Wrapper.prototype[o]=d,this.Wrapper.prototype[o].toString=function(){return"["+o+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,o,{get:d,configurable:!0}),Object.defineProperty(this.attributeKeys,o,{value:ra(o)}))}extendOperationOrAttribute(e,n,s){const r=e+"s";if(aa(n,"attribute"),!(this.super&&n in this.super[r]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(yi(this[r],n))throw new Error("Cannot extend "+e+" '"+n+"' again");const i=this[r][n].formals,o=this[r][n].actionDict,a=Object.create(o);Object.keys(s).forEach(c=>{a[c]=s[c]}),this[r][n]=e==="operation"?new ss(n,i,a):new bi(n,a),this[r][n].checkActionDict(this.grammar)}assertNewName(e,n){if(yi(oa.prototype,e))throw new Error("Cannot add "+n+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+n+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+n+" '"+e+"': an attribute with that name already exists")}wrap(e,n,s){const r=s||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,r)}}function aa(t,e){if(!Ke.prototypeGrammar)return Yt(t.indexOf("(")===-1),{name:t,formals:[]};const n=Ke.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return Ke.prototypeGrammarSemantics(n).parse()}function Ff(t,e,n){return function(...s){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(o=>this.args[o]);if(!this.isIteration()&&s.length===1)return n.apply(s[0],i);throw bf(this.ctorName,e,t,Kn)}}Ke.createSemantics=function(t,e){const n=new Ke(t,e!==void 0?e:Ke.BuiltInSemantics._getSemantics()),s=function(i){if(!(i instanceof Lu))throw new TypeError("Semantics expected a MatchResult, but got "+no(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());const o=i._cst;if(o.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+o.grammar.name+"' with a semantics for '"+t.name+"'");const a=new Ir(i.input);return n.wrap(o,a.interval(i._cstOffset,i.input.length))};return s.addOperation=function(r,i){return n.addOperationOrAttribute("operation",r,i),s},s.extendOperation=function(r,i){return n.extendOperationOrAttribute("operation",r,i),s},s.addAttribute=function(r,i){return n.addOperationOrAttribute("attribute",r,i),s},s.extendAttribute=function(r,i){return n.extendOperationOrAttribute("attribute",r,i),s},s._getActionDict=function(r){const i=n.operations[r]||n.attributes[r];if(!i)throw new Error('"'+r+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},s._remove=function(r){let i;return r in n.operations?(i=n.operations[r],delete n.operations[r]):r in n.attributes&&(i=n.attributes[r],delete n.attributes[r]),delete n.Wrapper.prototype[r],i},s.getOperationNames=function(){return Object.keys(n.operations)},s.getAttributeNames=function(){return Object.keys(n.attributes)},s.getGrammar=function(){return n.grammar},s.toRecipe=function(r){return n.toRecipe(r)},s.toString=n.toString.bind(n),s._getSemantics=function(){return n},s};class ss{constructor(e,n,s,r){this.name=e,this.formals=n,this.actionDict=s,this.builtInDefault=r}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{const{ctorName:s}=n._node;let r=this.actionDict[s];return r?(Kn.push([this,s]),r.apply(n,n._children())):n.isNonterminal()&&(r=this.actionDict._nonterminal,r)?(Kn.push([this,"_nonterminal",s]),r.apply(n,n._children())):(Kn.push([this,"default action",s]),this.actionDict._default.apply(n,n._children()))}finally{Kn.pop()}}}ss.prototype.typeName="operation";class bi extends ss{constructor(e,n,s){super(e,[],n,s)}execute(e,n){const s=n._node,r=e.attributeKeys[this.name];return yi(s,r)||(s[r]=ss.prototype.execute.call(this,e,n)),s[r]}}bi.prototype.typeName="attribute";const ca=["_iter","_terminal","_nonterminal","_default"];function ua(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const qf=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let $u,Pu;class qe{constructor(e,n,s,r){if(this.name=e,this.superGrammar=n,this.rules=s,r){if(!(r in s))throw new Error("Invalid start rule: '"+r+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=r}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new jf(this)}isBuiltIn(){return this===qe.ProtoBuiltInRules||this===qe.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const n=ua(this),s=ua(e);return n.length===s.length&&n.every((r,i)=>r.description===s[i].description&&r.formals.join(",")===s[i].formals.join(",")&&r.body.toString()===s[i].body.toString())}match(e,n){const s=this.matcher();return s.replaceInputRange(0,0,e),s.match(n)}trace(e,n){const s=this.matcher();return s.replaceInputRange(0,0,e),s.trace(n)}createSemantics(){return Ke.createSemantics(this)}extendSemantics(e){return Ke.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,s){const r=[];for(const i in s){const o=s[i];if(!ca.includes(i)&&!(i in this.rules)){r.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof o!="function"){r.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=o.length,u=this._topDownActionArity(i);if(c!==u){let l;i==="_iter"||i==="_nonterminal"?l=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:l=`expected ${u}, got ${c}`,r.push(`Semantic action '${i}' has the wrong arity: ${l}`)}}if(r.length>0){const i=r.map(a=>"- "+a),o=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...i].join(`
|
|
38
|
+
`));throw o.problems=r,o}}_topDownActionArity(e){return ca.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){const n={};this.source&&(n.source=this.source.contents);let s=null;this.defaultStartRule&&(s=this.defaultStartRule);const r={};Object.keys(this.rules).forEach(a=>{const c=this.rules[a],{body:u}=c,l=!this.superGrammar||!this.superGrammar.rules[a];let d;l?d="define":d=u instanceof kr?"extend":"override";const f={};if(c.source&&this.source){const m=c.source.relativeTo(this.source);f.sourceInterval=[m.startIdx,m.endIdx]}const p=l?c.description:null,h=u.outputRecipe(c.formals,this.source);r[a]=[d,f,p,c.formals,h]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const o=[...["grammar",n,this.name].map(JSON.stringify),i,...[s,r].map(JSON.stringify)];return qf(`[${o.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new hn;e.append("{");let n=!0;for(const s in this.rules){const{body:r}=this.rules[s];n?n=!1:e.append(","),e.append(`
|
|
39
39
|
`),e.append(" "),this.addSemanticActionTemplate(s,r,e)}return e.append(`
|
|
40
40
|
}`),e.contents()}addSemanticActionTemplate(e,n,s){s.append(e),s.append(": function(");const r=this._topDownActionArity(e);s.append(Ar("_",r).join(", ")),s.append(`) {
|
|
41
|
-
`),s.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new te(e);else{const r=$u.match(e,"Base_application");n=Pu(r,{})}if(!(n.ruleName in this.rules))throw xu(n.ruleName,this.name);const{formals:s}=this.rules[n.ruleName];if(s.length!==n.args.length){const{source:r}=this.rules[n.ruleName];throw Cu(n.ruleName,s.length,n.args.length,r)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}qe.ProtoBuiltInRules=new qe("ProtoBuiltInRules",void 0,{any:{body:$e,formals:[],description:"any character",primitive:!0},end:{body:Pe,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new ao(new Fe(0)),formals:["str"],primitive:!0},lower:{body:new Ne("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ne("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ne("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new pn(new te("space")),formals:[]},space:{body:new je("\0"," "),formals:[],description:"a space"}});qe.initApplicationParser=function(t,e){$u=t,Pu=e};class la{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?qe.ProtoBuiltInRules:qe.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const s=this.ensureSuperGrammar().rules[e];if(!s)throw
|
|
41
|
+
`),s.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new te(e);else{const r=$u.match(e,"Base_application");n=Pu(r,{})}if(!(n.ruleName in this.rules))throw xu(n.ruleName,this.name);const{formals:s}=this.rules[n.ruleName];if(s.length!==n.args.length){const{source:r}=this.rules[n.ruleName];throw Cu(n.ruleName,s.length,n.args.length,r)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}qe.ProtoBuiltInRules=new qe("ProtoBuiltInRules",void 0,{any:{body:$e,formals:[],description:"any character",primitive:!0},end:{body:Pe,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new ao(new Fe(0)),formals:["str"],primitive:!0},lower:{body:new Ne("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ne("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ne("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new pn(new te("space")),formals:[]},space:{body:new je("\0"," "),formals:[],description:"a space"}});qe.initApplicationParser=function(t,e){$u=t,Pu=e};class la{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?qe.ProtoBuiltInRules:qe.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const s=this.ensureSuperGrammar().rules[e];if(!s)throw af(e,this.superGrammar.name,n);return s}installOverriddenOrExtendedRule(e,n,s,r){const i=fi(n);if(i.length>0)throw ta(e,i,r);const o=this.ensureSuperGrammar().rules[e],a=o.formals,c=a?a.length:0;if(n.length!==c)throw Cu(e,c,n.length,r);return this.install(e,n,s,o.description,r)}install(e,n,s,r,i,o=!1){return this.rules[e]={body:s.introduceParams(n),formals:n,description:r,source:i,primitive:o},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new Ir(e).interval(0,e.length),this}build(){const e=new qe(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const n=[];let s=!1;return Object.keys(e.rules).forEach(r=>{const{body:i}=e.rules[r];try{i.assertChoicesHaveUniformArity(r)}catch(o){n.push(o)}try{i.assertAllApplicationsAreValid(r,e)}catch(o){n.push(o),s=!0}}),s||Object.keys(e.rules).forEach(r=>{const{body:i}=e.rules[r];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(o){n.push(o)}}),n.length>0&&vf(n),this.source&&(e.source=this.source),e}define(e,n,s,r,i,o){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw ea(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw ea(e,this.name,this.name,i);const a=fi(n);if(a.length>0)throw ta(e,a,i);return this.install(e,n,s,r,i,o)}override(e,n,s,r,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,n,s,i),this}extend(e,n,s,r,i){if(!this.ensureSuperGrammar().rules[e])throw cf(e,this.superGrammar.name,i);const a=new kr(this.superGrammar,e,s);return a.source=s.source,this.installOverriddenOrExtendedRule(e,n,a,i),this}}class Ws{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new la(e)}grammar(e,n,s,r,i){const o=new la(n);return s&&o.withSuperGrammar(s instanceof qe?s:this.fromRecipe(s)),r&&o.withDefaultStartRule(r),e&&e.source&&o.withSource(e.source),this.currentDecl=o,Object.keys(i).forEach(a=>{this.currentRuleName=a;const c=i[a],u=c[0],l=c[1],d=c[2],f=c[3],p=this.fromRecipe(c[4]);let h;o.source&&l&&l.sourceInterval&&(h=o.source.subInterval(l.sourceInterval[0],l.sourceInterval[1]-l.sourceInterval[0])),o[u](a,f,p,d,h)}),this.currentRuleName=this.currentDecl=null,o.build()}terminal(e){return new Me(e)}range(e,n){return new je(e,n)}param(e){return new Fe(e)}alt(...e){let n=[];for(let s of e)s instanceof U||(s=this.fromRecipe(s)),s instanceof Ie?n=n.concat(s.terms):n.push(s);return n.length===1?n[0]:new Ie(n)}seq(...e){let n=[];for(let s of e)s instanceof U||(s=this.fromRecipe(s)),s instanceof Ce?n=n.concat(s.factors):n.push(s);return n.length===1?n[0]:new Ce(n)}star(e){return e instanceof U||(e=this.fromRecipe(e)),new pn(e)}plus(e){return e instanceof U||(e=this.fromRecipe(e)),new Nn(e)}opt(e){return e instanceof U||(e=this.fromRecipe(e)),new $t(e)}not(e){return e instanceof U||(e=this.fromRecipe(e)),new Le(e)}lookahead(e){return e instanceof U||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new Le(new Le(e)):new We(e)}lex(e){return e instanceof U||(e=this.fromRecipe(e)),new Ze(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(s){return s instanceof U?s:this.fromRecipe(s)},this)),new te(e,n)}splice(e,n){return new Er(this.currentDecl.superGrammar,this.currentRuleName,e.map(s=>this.fromRecipe(s)),n.map(s=>this.fromRecipe(s)))}fromRecipe(e){const n=e[0]==="grammar"?e.slice(1):e.slice(2),s=this[e[0]](...n),r=e[1];return r&&r.sourceInterval&&this.currentDecl&&s.withSource(this.currentDecl.sourceInterval(...r.sourceInterval)),s}}function co(t){return typeof t=="function"?t.call(new Ws):(typeof t=="string"&&(t=JSON.parse(t)),new Ws().fromRecipe(t))}const uo=co(["grammar",{source:`BuiltInRules {
|
|
42
42
|
|
|
43
43
|
alnum (an alpha-numeric character)
|
|
44
44
|
= letter
|
|
@@ -79,7 +79,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
79
79
|
|
|
80
80
|
// Allows a syntactic rule application within a lexical context.
|
|
81
81
|
applySyntactic<app> = app
|
|
82
|
-
}`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);qe.BuiltInRules=uo;
|
|
82
|
+
}`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);qe.BuiltInRules=uo;Af(qe.BuiltInRules);const lo=co(["grammar",{source:`Ohm {
|
|
83
83
|
|
|
84
84
|
Grammars
|
|
85
85
|
= Grammar*
|
|
@@ -208,7 +208,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
208
208
|
`],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
|
|
209
209
|
`]],["range",{sourceInterval:[1639,1660]},"\0",""]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
|
|
210
210
|
`]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
|
|
211
|
-
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Wr=Object.create(U.prototype);function da(t,e){for(const n in t)if(n===e)return!0;return!1}function ju(t,e,n,s){const r=new Ws(s);let i,o,a,c=!1;return(n||lo).createSemantics().addOperation("visit",{Grammars(d){return d.children.map(f=>f.visit())},Grammar(d,f,p,h,m){const g=d.visit();i=r.newGrammar(g),f.child(0)&&f.child(0).visit(),h.children.map(y=>y.visit());const b=i.build();if(b.source=this.source.trimmed(),da(e,g))throw
|
|
211
|
+
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Wr=Object.create(U.prototype);function da(t,e){for(const n in t)if(n===e)return!0;return!1}function ju(t,e,n,s){const r=new Ws(s);let i,o,a,c=!1;return(n||lo).createSemantics().addOperation("visit",{Grammars(d){return d.children.map(f=>f.visit())},Grammar(d,f,p,h,m){const g=d.visit();i=r.newGrammar(g),f.child(0)&&f.child(0).visit(),h.children.map(y=>y.visit());const b=i.build();if(b.source=this.source.trimmed(),da(e,g))throw rf(b);return e[g]=b,b},SuperGrammar(d,f){const p=f.visit();if(p==="null")i.withSuperGrammar(null);else{if(!e||!da(e,p))throw sf(p,e,f.source);i.withSuperGrammar(e[p])}},Rule_define(d,f,p,h,m){o=d.visit(),a=f.children.map(w=>w.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==qe.ProtoBuiltInRules&&i.withDefaultStartRule(o);const g=m.visit(),b=p.children.map(w=>w.visit())[0],y=this.source.trimmed();return i.define(o,a,g,b,y)},Rule_override(d,f,p,h){o=d.visit(),a=f.children.map(b=>b.visit())[0]||[];const m=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(o,m),c=!0;const g=h.visit();return c=!1,i.override(o,a,g,null,m)},Rule_extend(d,f,p,h){o=d.visit(),a=f.children.map(b=>b.visit())[0]||[];const m=h.visit(),g=this.source.trimmed();return i.extend(o,a,m,null,g)},RuleBody(d,f){return r.alt(...f.visit()).withSource(this.source)},OverrideRuleBody(d,f){const p=f.visit(),h=p.indexOf(Wr);if(h>=0){const m=p.slice(0,h),g=p.slice(h+1);return g.forEach(b=>{if(b===Wr)throw mf(b)}),new Er(i.superGrammar,o,m,g).withSource(this.source)}else return r.alt(...p).withSource(this.source)},Formals(d,f,p){return f.visit()},Params(d,f,p){return f.visit()},Alt(d){return r.alt(...d.visit()).withSource(this.source)},TopLevelTerm_inline(d,f){const p=o+"_"+f.visit(),h=d.visit(),m=this.source.trimmed(),g=!(i.superGrammar&&i.superGrammar.rules[p]);c&&!g?i.override(p,a,h,null,m):i.define(p,a,h,null,m);const b=a.map(y=>r.app(y));return r.app(p,b).withSource(h.source)},OverrideTopLevelTerm_superSplice(d){return Wr},Seq(d){return r.seq(...d.children.map(f=>f.visit())).withSource(this.source)},Iter_star(d,f){return r.star(d.visit()).withSource(this.source)},Iter_plus(d,f){return r.plus(d.visit()).withSource(this.source)},Iter_opt(d,f){return r.opt(d.visit()).withSource(this.source)},Pred_not(d,f){return r.not(f.visit()).withSource(this.source)},Pred_lookahead(d,f){return r.lookahead(f.visit()).withSource(this.source)},Lex_lex(d,f){return r.lex(f.visit()).withSource(this.source)},Base_application(d,f){const p=f.children.map(h=>h.visit())[0]||[];return r.app(d.visit(),p).withSource(this.source)},Base_range(d,f,p){return r.range(d.visit(),p.visit()).withSource(this.source)},Base_terminal(d){return r.terminal(d.visit()).withSource(this.source)},Base_paren(d,f,p){return f.visit()},ruleDescr(d,f,p){return f.visit()},ruleDescrText(d){return this.sourceString.trim()},caseName(d,f,p,h,m){return p.visit()},name(d,f){return this.sourceString},nameFirst(d){},nameRest(d){},terminal(d,f,p){return f.children.map(h=>h.visit()).join("")},oneCharTerminal(d,f,p){return f.visit()},escapeChar(d){try{return Eu(this.sourceString)}catch(f){throw f instanceof RangeError&&f.message.startsWith("Invalid code point ")?gf(d):f}},NonemptyListOf(d,f,p){return[d.visit()].concat(p.children.map(h=>h.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const Uf=co(["grammar",{source:`OperationsAndAttributes {
|
|
212
212
|
|
|
213
213
|
AttributeSignature =
|
|
214
214
|
name
|
|
@@ -230,7 +230,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
230
230
|
= "_"
|
|
231
231
|
| alnum
|
|
232
232
|
|
|
233
|
-
}`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);
|
|
233
|
+
}`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);Bf(qe.BuiltInRules);zf(Uf);function Bf(t){const e={empty(){return this.iteration()},nonEmpty(n,s,r){return this.iteration([n].concat(r.children))},self(...n){return this}};Ke.BuiltInSemantics=Ke.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function zf(t){Ke.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(s=>s.parse())[0]||[]}},Formals(e,n,s){return n.asIteration().children.map(r=>r.parse())},name(e,n){return this.sourceString}}),Ke.prototypeGrammar=t}function Wf(t){let e=0;const n=[0],s=()=>n[n.length-1],r={},i=/( *).*(?:$|\r?\n|\r)/g;let o;for(;(o=i.exec(t))!=null;){const[a,c]=o;if(a.length===0)break;const u=c.length,l=s(),d=e+u;if(u>l)n.push(u),r[d]=1;else if(u<l){const f=n.length;for(;s()!==u;)n.pop();r[d]=-1*(f-n.length)}e+=a.length}return n.length>1&&(r[e]=1-n.length),r}const Fu="an indented block",qu="a dedent",fa=1114112;class Vf extends Ir{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),fa):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),fa):super.nextCodePoint()}}class ha extends U{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,s=e.userData;e.doNotMemoize=!0;const r=n.pos,i=this.isIndent?1:-1;return(s[r]||0)*i>0?(e.userData=Object.create(s),e.userData[r]-=i,e.pushBinding(new mn(0),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,n){}_isNullable(e,n){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const n=this.isIndent?Fu:qu;return new Je(this,n,"description")}}const Gf=new te("indent"),Hf=new te("dedent"),Kf=new Er(uo,"any",[Gf,Hf],[]),Zf=new Ws().newGrammar("IndentationSensitive").withSuperGrammar(uo).define("indent",[],new ha(!0),Fu,void 0,!0).define("dedent",[],new ha(!1),qu,void 0,!0).extend("any",[],Kf,"any character",void 0).build();Object.assign(Zf,{_matchStateInitializer(t){t.userData=Wf(t.input),t.inputStream=new Vf(t)},supportsIncrementalParsing:!1});qe.initApplicationParser(lo,ju);const Jf=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function Qf(t,e,n){const s=lo.match(t,"Grammars");if(s.failed())throw nf(s);return ju(s,e,void 0,n)}function Yf(t,e,n){const s=Xf(t,e,n),r=Object.keys(s);if(r.length===0)throw new Error("Missing grammar definition");if(r.length>1){const o=s[r[1]].source;throw new Error(ro(o.sourceString,o.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return s[r[0]]}function Xf(t,e,n){const s=Object.create({});if(typeof t!="string")if(Jf(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+no(t));return Qf(t,s,n),s}function eh(t,e){return Yf(t,e)}const th=`FirestoreRules {
|
|
234
234
|
// === Top-level ===
|
|
235
235
|
// Syntactic rules (capitalized) auto-skip spaces between terms.
|
|
236
236
|
// Lexical rules (lowercase) do NOT skip spaces.
|
|
@@ -493,27 +493,27 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
493
493
|
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
494
494
|
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
495
495
|
}
|
|
496
|
-
`,Uu=new WeakMap;function ks(t){return Uu.get(t)??0}function fo(t){Uu.set(t,ks(t)+1)}const Vs=128,Bu=new Set(["if","return","in","is","let"]),
|
|
497
|
-
`,f+2);f=g===-1?d:g;continue}if(m===42){const g=t.indexOf("*/",f+2);f=g===-1?d:g+2;continue}}if(h!==41&&h!==93&&h!==125&&h!==44&&p(),h===39||h===34){f=eh(t,f,h,!e.multilineStrings),i="operand",u="";continue}if(e.regexLiterals&&h===47&&i!=="word"&&i!=="operand"){for(f=th(t,f);f<d&&qn(t.charCodeAt(f));)f++;i="operand",u="";continue}if(qn(h)&&h!==36){const m=f;for(;f<d&&qn(t.charCodeAt(f));)f++;const g=i==="word"&&o==="function"&&!a&&u==="";o=t.slice(m,f),a=u===".";const b=i;i=h>=48&&h<=57||!a&&Yf.has(o)?"operand":"word",c=g&&i==="word"&&!Bu.has(o),o==="match"&&!a&&b!=="slash"&&(l=s.length),u="";continue}if(h===36){const m=t.charCodeAt(f+1);if(m!==40&&qn(m)){const g=f;for(f++;f<d&&qn(t.charCodeAt(f));)f++;o=t.slice(g,f),a=u===".",i="word",u="";continue}i="dollar",u="$",f++;continue}if(h===40||h===91||h===123){const m=h===40?"(":h===91?"[":"{";let g;m==="{"&&l!==null&&s.length===l?(g="block",i!=="slash"&&(l=null)):g=Xf(m,i,o,a),pa.has(g)&&r++;const y=g==="call"&&c&&u==="",w={char:m,kind:g,open:f,close:-1,depth:s.length+1,levels:r,items:0};y&&(w.declaration=!0),i==="slash"&&(w.afterSlash=!0),c=!1,n.push(w),s.push({span:w,commas:0,tail:!1}),i="other",u=m,f++;continue}if(h===41||h===93||h===125){const m=s.pop();m!==void 0&&(m.span.close=f,m.span.items=m.commas+(m.tail?1:0),pa.has(m.span.kind)&&r--),h===125&&l!==null&&s.length<l&&(l=null),i="operand",u="",f++;continue}if(h===59&&l!==null&&s.length<=l&&(l=null),h===44){const m=s[s.length-1];m!==void 0&&(m.commas++,m.tail=!1)}i=h===47?"slash":"other",u=t[f],f++}for(const h of s)h.span.items=h.commas+(h.tail?1:0);return n}function Xf(t,e,n,s){const r=e==="word"&&(s||!Bu.has(n));return t==="("?e==="dollar"?"interpolation":r?s?"method":"call":"group":t==="["?r||e==="operand"?"index":"list":r||e==="operand"||e==="slash"?"block":"map"}function eh(t,e,n,s){const r=t.length;let i=e+1;for(;i<r;){const o=t.charCodeAt(i);if(o===92){i+=2;continue}if(o===n)return i+1;if(s&&(o===10||o===13))return i;i++}return r}function th(t,e){const n=t.length;let s=e+1,r=!1;for(;s<n;){const i=t.charCodeAt(s);if(i===92){s+=2;continue}if(i===10||i===13)return s;if(r){i===93&&(r=!1),s++;continue}if(i===91){r=!0,s++;continue}if(i===47)return s+1;s++}return n}function ho(t){let e="",n=0,s=!1,r=!1;for(;n<t.length;){const i=t[n];if(i==="\\"){const o=t[n+1];if(o===void 0){e+="\\";break}if(!s&&o==="A"){e+="^",n+=2;continue}if(!s&&o==="z"){e+="$",n+=2;continue}if((o==="x"||o==="u")&&t[n+2]==="{"){const a=t.indexOf("}",n+3);if(a!==-1){const c=t.slice(n+3,a);if(/^[0-9A-Fa-f]+$/.test(c)){e+=String.fromCodePoint(parseInt(c,16)),n=a+1,r=!1;continue}}}e+=t.slice(n,n+2),n+=2,r=!1;continue}if(s){if(i==="]"&&r){e+="\\]",n++,r=!1;continue}i==="]"&&(s=!1),e+=i,n++,r=!1;continue}if(i==="["){s=!0,e+="[",n++,t[n]==="^"&&(e+="^",n++),r=!0;continue}if(i==="("&&t[n+1]==="?"){const o=t.slice(n+2),a=/^P<([A-Za-z_][A-Za-z0-9_]*)>/.exec(o);if(a){e+=`(?<${a[1]}>`,n+=2+a[0].length;continue}const c=/^([imsU-]+):/.exec(o);if(c){e+="(?:",n+=2+c[0].length;continue}const u=/^([imsU-]+)\)/.exec(o);if(u){const l=t[n+2+u[0].length];if(l==="*"||l==="+"||l==="?"||l==="{")throw new Error("Nothing to repeat after inline flag group");e+="(?:)",n+=2+u[0].length;continue}}e+=i,n++}return e}const Zn=21,Wu=11,po=99,nh="Maximum allowed variable count of 10 for a given function has been reached.",Vu="Expression is too complex to evaluate safely.",Gu="Missing 'match' keyword before path.",sh="Invalid glob match expression. Only one glob match is permitted in a match declaration path.";function rh(t){return`Maximum allowed call depth of 20 is reached for [${t.join("->")}] call stack.`}function ih(t){return`Function ${t} is already defined.`}function mo(t){const e=dh(t),n=[],s=t.service.name!=="firebase.storage";t.version!=="1"&&t.version!=="2"&&t.version!=="2+modules"?n.push({code:"UNSUPPORTED_RULES_VERSION",message:`Unsupported rules version ${t.version}.`,line:t.loc?.line??1}):s&&(t.version==="2+modules"||(t.imports?.length??0)>0)&&n.push({code:"UNRESOLVED_MODULES",message:"Rules source uses '2+modules' or import statements that must be resolved before compilation.",line:t.loc?.line??1});for(const i of e){const o=i.fn;if(o.lets.length>Wu){const a=o.returnLoc??o.loc;n.push({code:"LET_LIMIT",message:nh,..._r(a),...o.returnLoc===void 0?{}:{column:o.returnLoc.col},functionName:o.name})}for(const a of o.lets)Vr(n,a.value,a.loc?.line??o.loc?.line,o.name),Ps(n,a.value,a.loc?.line??o.loc?.line,s,o.name);Vr(n,o.body,o.loc?.line,o.name),Ps(n,o.body,o.returnLoc?.line??o.loc?.line,s,o.name)}const r=i=>{for(const o of i.allows)Vr(n,o.condition,o.loc?.line),Ps(n,o.condition,o.loc?.line,s);for(const o of i.children)r(o)};return r(t.service.match),n.push(...fh(e)),n.push(...oh(t)),n.push(...Hu(t.service.match,0)),n.sort((i,o)=>(i.line??0)-(o.line??0))}function Hu(t,e){const n=t.path.segments.filter(r=>r.type==="recursive").length,s=n>0&&e+n>1?[{code:"GLOB_MATCH_COUNT",message:sh,..._r(t.loc)}]:[];for(const r of t.children)s.push(...Hu(r,e+n));return s}function oh(t){const e=[],n=(r,i)=>{const o=new Set;for(const a of r)o.has(a.name)&&e.push({code:"FUNCTION_REDEFINED",message:ih(a.name),..._r(a.loc),functionName:a.name,scope:i}),o.add(a.name)},s=r=>{n(r.functions,r.path.raw);for(const i of r.children)s(i)};return n(t.functions??[],"global scope"),n(t.service.functions??[],`service ${t.service.name}`),s(t.service.match),e}function ah(t){return t.map(e=>e.line===void 0?e.message:`Line ${e.line}: ${e.message}`).join(" ")}function _r(t){return t===void 0?{}:{line:t.line}}function Vr(t,e,n,s){const r=uh(e);for(let i=0;i<r;i++)t.push({code:"NESTING_DEPTH",message:Vu,...n===void 0?{}:{line:n},...s===void 0?{}:{functionName:s}})}function ch(t){if(/\\[1-9]/.test(t)||/\(\?<?[=!]/.test(t))return!1;try{return new RegExp(`^(?:${ho(t)})$`),!0}catch{return!1}}function Ps(t,e,n,s,r){if(e.type==="binaryOp"&&e.slashStartsPath&&t.push({code:"SLASH_STARTS_PATH",message:Gu,...n===void 0?{}:{line:n},...r===void 0?{}:{functionName:r}}),s&&e.type==="methodCall"&&e.method==="matches"&&e.args.length===1){const i=e.args[0];i?.type==="literal"&&typeof i.value=="string"&&!ch(i.value)&&t.push({code:"INVALID_REGEX_PATTERN",message:`Invalid regular expression pattern. Pattern: ${i.value}.`,...n===void 0?{}:{line:n},...r===void 0?{}:{functionName:r}})}for(const i of go(e))Ps(t,i,n,s,r)}function uh(t){return Ku(t,1)}function ma(t,e,n){for(let s=e;s<n;s++){const r=t.charCodeAt(s);if(r!==32&&r!==9&&r!==10&&r!==13)return!1}return!0}function ga(t){const e=zu(t,{comments:!0,regexLiterals:!1,multilineStrings:!1});let n,s,r=-1;for(let i=0;i<e.length;i++){const o=e[i];if(o.open<r)continue;if(o.depth>Vs)return{offset:o.open,expected:`brackets nested at most ${Vs} levels deep`};if(o.levels<po||o.items===0)continue;const a=o.close===-1?t.length:o.close,c=t.slice(o.open+1,a),u=o.kind==="map"?"a:1":"1",l=Array.from({length:o.items},()=>u).join(",");if(c.replace(/[\n\r]/g,"").length<l.length)continue;let d=0;const f=c.replace(/[^\n\r]/g,()=>d<l.length?l[d++]:" ");if(n??=[],n.push(t.slice(Math.max(r,0),o.open+1),f),r=a===t.length?1/0:a,o.close!==-1){let p=i;for(;p+1<e.length;){const g=e[p],b=e[p+1],y=(g.kind==="group"||g.kind==="list")&&g.items===1,w=b.close!==-1&&b.open>g.open&&b.close<g.close,v=(b.kind==="group"||b.kind==="list"||b.kind==="map")&&b.items>=1;if(!y||!w||!v||!ma(t,g.open+1,b.open)||!ma(t,b.close+1,g.close))break;p++}const h=e[p];let m=t.slice(h.open,h.close+1);h.kind==="call"&&(m=`[${t.slice(h.open+1,h.close)}]`),s??=[],s.push({offset:h.open,text:m})}}return n===void 0?{source:t}:(r!==1/0&&n.push(t.slice(r)),{source:n.join(""),...s===void 0?{}:{elided:s}})}function Ku(t,e){const n=e+ks(t);if(n>po)return 1;const s=lh(t)?n+1:n;let r=0;for(const i of go(t))r+=Ku(i,s);return r}function lh(t){switch(t.type){case"binaryOp":case"inExpr":case"isExpr":case"listLiteral":case"mapLiteral":case"functionCall":return!0;default:return!1}}function go(t){switch(t.type){case"literal":case"identifier":return[];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end];case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args}}function dh(t){const e=[],n=[],s=(o,a)=>{const c={names:new Map,parent:a};for(const u of o){const l={fn:u,callees:[]};e.push(l),c.names.set(u.name,l),n.push({node:l,scope:c})}return c},r=s(t.service.functions??[],s(t.functions??[],void 0)),i=(o,a)=>{const c=s(o.functions,a);for(const u of o.children)i(u,c)};i(t.service.match,r);for(const{node:o,scope:a}of n){const c=new Set,u=l=>{if(l.type==="functionCall")for(let d=a;d;d=d.parent){const f=d.names.get(l.name);if(f!==void 0){c.has(f)||(c.add(f),o.callees.push(f));break}}for(const d of go(l))u(d)};for(const l of o.fn.lets)u(l.value);u(o.fn.body)}return e}function fh(t){const e=new Map,n=new Set,s=u=>{const l=e.get(u);if(l!==void 0)return l;if(n.has(u))return 1/0;n.add(u);let d=0;for(const f of u.callees)d=Math.max(d,s(f));return n.delete(u),e.set(u,d+1),d+1},r=new Set;for(const u of t)for(const l of u.callees)l!==u&&r.add(l);const i=new Set,o=u=>{if(!i.has(u)){i.add(u);for(const l of u.callees)o(l)}},a=[];for(const u of t)r.has(u)||(a.push(u),o(u));for(const u of t)i.has(u)||s(u)!==1/0||(a.push(u),o(u));const c=[];for(const u of a){if(s(u)<=Zn)continue;const l=[u];for(;l.length<=Zn;){const f=l[l.length-1];let p=f.callees[0];for(const h of f.callees)s(h)>s(p)&&(p=h);l.push(p)}const d=l[Zn];c.push({code:"CALL_DEPTH",message:rh(l.slice(0,Zn).map(f=>f.fn.name)),..._r(d.fn.loc),functionName:d.fn.name})}return c}const rs=new WeakMap;function bn(t){return rs.get(t)}function hh(t,e){rs.set(t,e)}const Gs=new WeakMap;function Zu(t){return Gs.get(t)??rs.get(t)}function Ju(t,e){Gs.set(t,e)}function B0(t,e){const n=rs.get(t);n!==void 0&&rs.set(e,n);const s=Gs.get(t);s!==void 0&&Gs.set(e,s)}function ph(t){return`line ${t.line}, column ${t.column}`}class Qu{lineOffset;firstLineColumnOffset;lineStarts=[0];constructor(e,n,s){this.lineOffset=n,this.firstLineColumnOffset=s;for(let r=0;r<e.length;r++)e.charCodeAt(r)===10&&this.lineStarts.push(r+1)}at(e){let n=0,s=this.lineStarts.length-1;for(;n<s;){const i=n+s+1>>1;this.lineStarts[i]<=e?n=i:s=i-1}const r=e-this.lineStarts[n]+1;return{line:n+1+this.lineOffset,column:n===0?r+this.firstLineColumnOffset:r}}}const yo=24,Cn="ǂǂ",an=`${Cn}wǂ`,mh=t=>t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t===450;function vi(t,e){if(!(t.length<=e.length)&&!/[\n\r]/.test(t.slice(0,e.length)))return e+t.slice(e.length).replace(/[^\n\r]/g," ")}function gh(t,e,n){if(e.close===-1)return;let s=32;switch(e.open>0&&(s=t.charCodeAt(e.open-1)),e.kind){case"group":case"list":case"map":{if(e.afterSlash||s===47||e.items===0)return;const r=t.slice(e.open,e.close+1),i=vi(r,mh(s)?` ${n}`:n);return i===void 0?void 0:{name:n,kind:"expr",start:e.open,original:r,replacement:i,text:r,prefix:0}}case"interpolation":case"call":case"method":case"index":{if(e.items===0||e.declaration)return;const r=t.slice(e.open+1,e.close),i=vi(` ${r}`,` ${n}`)?.slice(1);if(i===void 0)return;if(e.kind==="interpolation")return{name:n,kind:"expr",start:e.open+1,original:r,replacement:i,text:r,prefix:0};const o=e.kind==="index"?"index":"args",a=`${an}${t.slice(e.open,e.close+1)}`;return{name:n,kind:o,start:e.open+1,original:r,replacement:i,text:a,prefix:an.length+1}}default:return}}function yh(t,e=yo){if(t.indexOf(Cn,t.startsWith(an)?an.length:0)!==-1)return;const n=Math.max(e,2),s=zu(t,{comments:!0,regexLiterals:!1,multilineStrings:!1}),r=[],i=[];let o=0;for(const a of s){if(a.depth<n||a.open<o)continue;const c=gh(t,a,`${Cn}${r.length}ǂ`);c!==void 0&&(i.push(t.slice(o,c.start),c.replacement),o=c.start+c.original.length,r.push(c))}if(r.length!==0)return i.push(t.slice(o)),{text:i.join(""),segments:r}}function is(t){if(typeof t!="object"||t===null)return;const e=t;if(!(e.type!=="identifier"||typeof e.name!="string"||!e.name.startsWith(Cn)))return e.name===an?void 0:e.name}function ya(t){return t.type==="identifier"&&t.name===an}function bh(t){return is(t)!==void 0}function vh(t,e){const n=new Set,s=new WeakSet,r=c=>e.get(c)?.segment.kind,i=(c,u)=>{const l=e.get(c);if(!(l===void 0||l.segment.kind!==u||n.has(c)))return n.add(c),s.add(l.ast),l},o=is(t);if(o!==void 0){const c=i(o,"expr");return c===void 0||n.size!==e.size?void 0:ba(t,c.ast)}const a=[t];for(;a.length>0;){const c=a.pop();if(!(s.has(c)||ArrayBuffer.isView(c))){if(!wh(c,r,i)||c.type==="pathLiteral"&&!Sh(c,e))return;for(const u of Object.keys(c)){const l=c[u];if(typeof l!="object"||l===null)continue;const d=is(l);if(d===void 0){a.push(l);continue}if(u==="key"&&"value"in c&&!("type"in c))return;const f=i(d,"expr");if(f===void 0)return;c[u]=ba(l,f.ast)}}}return n.size===e.size?t:void 0}function ba(t,e){const n=ks(t);for(let r=0;r<n;r++)fo(e);const s=Zu(t);return n>0&&s!==void 0&&e.type==="binaryOp"&&e.op==="&&"&&Ju(e,s),e}function wh(t,e,n){if(t.type==="functionCall"||t.type==="methodCall"){const s=t.args;if(s.length!==1)return!0;const r=is(s[0]);if(r===void 0||e(r)!=="args")return!0;const i=n(r,"args")?.ast;return i===void 0||i.type!=="functionCall"||i.name!==an?!1:(t.args=i.args,!0)}if(t.type==="bracketAccess"){const s=is(t.index);if(s===void 0||e(s)!=="index")return!0;const r=n(s,"index")?.ast;return r===void 0?!1:r.type==="bracketAccess"&&ya(r.object)?(t.index=r.index,!0):r.type==="sliceAccess"&&ya(r.object)?(delete t.index,t.type="sliceAccess",t.start=r.start,t.end=r.end,!0):!1}return!0}function Sh(t,e){let n=t.raw;if(!n.includes(Cn))return!0;for(const{segment:s}of e.values())n.includes(s.name)&&(n=n.split(s.replacement).join(s.original));return t.raw=n,!n.includes(Cn)}function Ah(t){return t.length<4||/[\n\r]/.test(t.slice(-2))?vi(t,"(!1)"):`(!${t.slice(2,-2).replace(/[^\n\r]/g," ")}1)`}function kh(t,e){const n=[];let s=0;for(const r of e){let i;r.kind==="expr"&&(i=Ah(r.original)),n.push(t.slice(s,r.start),i??r.replacement),s=r.start+r.original.length}return n.push(t.slice(s)),n.join("")}function Yu(t,e,n,s=0,r=0,i=yo){const o=yh(t,i);if(o===void 0)return n(t,e,s,r);const a=n(o.text,e,s,r);if(!a.ok)return a;const c=new Map;for(const l of o.segments){const d=s+l.start-r,f=Yu(l.text,"Expr",n,d,l.prefix,i);if(!f.ok)return f;c.set(l.name,{segment:l,ast:f.ast})}const u=vh(a.ast,c);if(u===void 0){const l=n(kh(t,o.segments),e,s,r);return l.ok?n(t,e,s,r):l}return{ok:!0,ast:u}}const wi=Jf(Qf),Xu=wi.createSemantics();let Lt=null;function K(t,e){return Lt!==null&&hh(t,Lt.at(e.source.startIdx)),t}function va(t,e){return Lt!==null&&Ju(t,Lt.at(e.source.startIdx)),t}Xu.addOperation("toAST",{RulesFile_versionFirst(t,e,n,s){return{imports:e.children.map(r=>r.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:n.children.map(r=>r.toAST()),service:s.toAST()}},RulesFile_importsFirst(t,e,n,s){return{imports:t.children.map(r=>r.toAST()),version:e.toAST(),functions:n.children.map(r=>r.toAST()),service:s.toAST()}},ImportDecl(t,e,n,s,r,i,o,a){const{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{functions:n.asIteration().children.map(l=>l.sourceString),module:o.toAST().value,loc:{line:c,col:u}}},RulesVersion(t,e,n,s){return n.toAST().value},ServiceBlock(t,e,n,s,r,i,o){const{lineNum:a,colNum:c}=t.source.getLineAndColumn();return{name:e.sourceString,functions:[...s.children.map(u=>u.toAST()),...i.children.map(u=>u.toAST())],match:r.toAST(),loc:{line:a,col:c}}},DocumentsMatch(t,e,n,s,r){const{lineNum:i,colNum:o}=t.source.getLineAndColumn();return{...s.toAST(),path:Aa(e.sourceString),loc:{line:i,col:o}}},MatchBody(t){const e=[],n=[],s=[];for(const r of t.children){const i=r.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?n.push(i):i._kind==="match"&&s.push(i)}return{functions:e,allows:n,children:s}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,s,r){const{functions:i,allows:o,children:a}=s.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:Aa(e.sourceString),functions:i,allows:o,children:a,loc:{line:c,col:u}}},AllowStatement(t,e,n,s,r,i){const{lineNum:o,colNum:a}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:r.toAST(),loc:{line:o,col:a}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(s=>s.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,s,r,i,o,a,c){const{lets:u,expr:l,returnLoc:d}=a.toAST(),{lineNum:f,colNum:p}=e.source.getLineAndColumn();return{_kind:"function",name:n.sourceString,parameters:r.toAST(),exported:t.sourceString.trim()==="export",lets:u,body:l,returnLoc:d,loc:{line:f,col:p}}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){const{lineNum:n,colNum:s}=e.child(1).source.getLineAndColumn();return{lets:t.children.map(r=>r.toAST()),expr:e.toAST(),returnLoc:{line:n,col:s}}},LetBinding(t,e,n,s,r){const{lineNum:i,colNum:o}=t.source.getLineAndColumn();return K({name:e.sourceString,value:s.toAST(),loc:{line:i,col:o}},this)},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,s,r){return K({type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:r.toAST()},this)},LogicalOr_or(t,e,n){return K({type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()},e)},LogicalAnd_and(t,e,n){return va(K({type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()},e),this)},InIsExpr_in(t,e,n){return K({type:"inExpr",element:t.toAST(),collection:n.toAST()},e)},InIsExpr_is(t,e,n){return K({type:"isExpr",value:t.toAST(),typeName:n.sourceString},e)},Equality_eq(t,e,n){return K({type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()},e)},Equality_neq(t,e,n){return K({type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()},e)},Comparison_gte(t,e,n){return K({type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()},e)},Comparison_lte(t,e,n){return K({type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()},e)},Comparison_gt(t,e,n){return K({type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()},e)},Comparison_lt(t,e,n){return K({type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()},e)},Additive_add(t,e,n){return K({type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()},e)},Additive_sub(t,e,n){return K({type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()},e)},Multiplicative_mul(t,e,n){return K({type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()},e)},Multiplicative_div(t,e,n){const s=e.source,r=s.sourceString.charAt(s.endIdx);return K({type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST(),.../\s/.test(r)?{}:{slashStartsPath:!0}},e)},Multiplicative_mod(t,e,n){return K({type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()},e)},UnaryExpr_not(t,e){return K({type:"unaryOp",op:"!",operand:e.toAST()},this)},UnaryExpr_neg(t,e){return K({type:"unaryOp",op:"-",operand:e.toAST()},this)},PostfixExpr_methodCall(t,e,n,s,r,i){return K({type:"methodCall",object:t.toAST(),method:n.sourceString,args:r.asIteration().children.map(o=>o.toAST())},this)},PostfixExpr_memberAccess(t,e,n){return K({type:"memberAccess",object:t.toAST(),property:n.sourceString},this)},PostfixExpr_bracketAccess(t,e,n,s){return K({type:"bracketAccess",object:t.toAST(),index:n.toAST()},this)},PostfixExpr_sliceAccess(t,e,n,s,r,i){return K({type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:r.toAST()},this)},Primary_paren(t,e,n){const s=e.toAST();return fo(s),(s.type==="binaryOp"&&s.op==="&&"||bh(s))&&va(s,this),s},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,s){return K({type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(r=>r.toAST())},this)},PathLiteral(t,e,n){const s=[];for(const r of e.children)s.push(r.toAST());return s.push(n.toAST()),K({type:"pathLiteral",raw:this.sourceString,segments:s},this)},PathLitContSegment_interpolation(t,e,n){return e.toAST()},PathLitContSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitContSegment_parenLiteral(t){return t.sourceString.slice(0,-1)},PathLitContSegment_literal(t){return t.sourceString.slice(0,-1)},PathLitSegment_interpolation(t,e,n){return e.toAST()},PathLitSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,n){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,n,s){return K({type:"listLiteral",elements:e.asIteration().children.map(r=>r.toAST())},this)},MapLiteral(t,e,n,s){return K({type:"mapLiteral",entries:e.asIteration().children.map(r=>r.toAST())},this)},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return K({type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString},this)},number_int(t){return K({type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString},this)},string_single(t,e,n){return K({type:"literal",value:wa(e.sourceString),raw:this.sourceString},this)},string_double(t,e,n){return K({type:"literal",value:wa(e.sourceString),raw:this.sourceString},this)},bytes_single(t,e,n,s){return K({type:"literal",value:Sa(n.sourceString),raw:this.sourceString},this)},bytes_double(t,e,n,s){return K({type:"literal",value:Sa(n.sourceString),raw:this.sourceString},this)},bool_true(t){return K({type:"literal",value:!0,raw:"true"},this)},bool_false(t){return K({type:"literal",value:!1,raw:"false"},this)},null(t){return K({type:"literal",value:null,raw:"null"},this)},ident(t,e){return K({type:"identifier",name:this.sourceString},this)},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});const Eh={"\\":92,"'":39,'"':34,n:10,r:13,t:9,b:8,f:12};function el(t,e,n){let s=0,r=0;for(;r<t.length;){if(t[r]!=="\\"){r++;continue}r>s&&e(t.slice(s,r));const i=t[r+1];i==="x"?(n(parseInt(t.slice(r+2,r+4),16)),r+=4):i==="u"?(n(parseInt(t.slice(r+2,r+6),16)),r+=6):i>="0"&&i<="3"?(n(parseInt(t.slice(r+1,r+4),8)),r+=4):(n(Eh[i]),r+=2),s=r}t.length>s&&e(t.slice(s))}function wa(t){let e="";return el(t,n=>{e+=n},n=>{e+=String.fromCharCode(n)}),e}function Sa(t){const e=[],n=new TextEncoder;return el(t,s=>{e.push(...n.encode(s))},s=>{e.push(s)}),new Uint8Array(e)}function Aa(t){const e=[],n=t.split("/").filter(Boolean);for(const s of n)if(s.startsWith("{")&&s.endsWith("}")){const r=s.slice(1,-1);r.endsWith("=**")?e.push({type:"recursive",name:r.slice(0,-3)}):e.push({type:"wildcard",name:r})}else e.push({type:"literal",value:s});return{raw:t,segments:e}}function tl(t,e,n=0){const s=t,r=n+(s.getRightmostFailurePosition?.()??0),i=s.getExpectedText?.()??"",o=s.getInterval?.();let a=s.message??"Parse error";return o!==void 0&&(s.input!==e||n!==0)&&(a=`${new o.constructor(e,r,r).getLineAndColumnMessage()}Expected ${i}`),bo(e,r,i,a)}function bo(t,e,n,s){let r=1,i=-1;for(let u=0;u<e&&u<t.length;u++)t.charCodeAt(u)===10&&(r++,i=u);const o=e-i;let a=t.indexOf(`
|
|
498
|
-
`,e);a===-1&&(a=t.length);const c=t.slice(e,Math.min(a,e+40));return{line:r,column:o,offset:e,expected:n,actual:c,message:s}}function ka(t,e){const n=bo(t,e.offset,e.expected,"");return n.message=`Line ${n.line}, col ${n.column}: Brackets nest more than ${Vs} levels deep: the rules parser reads at most ${Vs}, a limit of this parser, not of production.`,n}function
|
|
496
|
+
`,Uu=new WeakMap;function ks(t){return Uu.get(t)??0}function fo(t){Uu.set(t,ks(t)+1)}const Vs=128,Bu=new Set(["if","return","in","is","let"]),nh=new Set(["true","false","null"]),pa=new Set(["group","call","list","map"]),qn=t=>t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t===36;function zu(t,e){const n=[],s=[];let r=0,i="none",o="",a=!1,c=!1,u="",l=null;const d=t.length;let f=0;const p=()=>{const h=s[s.length-1];h!==void 0&&(h.tail=!0)};for(;f<d;){const h=t.charCodeAt(f);if(h===32||h===9||h===10||h===13){f++;continue}if(e.comments&&h===47){const m=t.charCodeAt(f+1);if(m===47){const g=t.indexOf(`
|
|
497
|
+
`,f+2);f=g===-1?d:g;continue}if(m===42){const g=t.indexOf("*/",f+2);f=g===-1?d:g+2;continue}}if(h!==41&&h!==93&&h!==125&&h!==44&&p(),h===39||h===34){f=rh(t,f,h,!e.multilineStrings),i="operand",u="";continue}if(e.regexLiterals&&h===47&&i!=="word"&&i!=="operand"){for(f=ih(t,f);f<d&&qn(t.charCodeAt(f));)f++;i="operand",u="";continue}if(qn(h)&&h!==36){const m=f;for(;f<d&&qn(t.charCodeAt(f));)f++;const g=i==="word"&&o==="function"&&!a&&u==="";o=t.slice(m,f),a=u===".";const b=i;i=h>=48&&h<=57||!a&&nh.has(o)?"operand":"word",c=g&&i==="word"&&!Bu.has(o),o==="match"&&!a&&b!=="slash"&&(l=s.length),u="";continue}if(h===36){const m=t.charCodeAt(f+1);if(m!==40&&qn(m)){const g=f;for(f++;f<d&&qn(t.charCodeAt(f));)f++;o=t.slice(g,f),a=u===".",i="word",u="";continue}i="dollar",u="$",f++;continue}if(h===40||h===91||h===123){const m=h===40?"(":h===91?"[":"{";let g;m==="{"&&l!==null&&s.length===l?(g="block",i!=="slash"&&(l=null)):g=sh(m,i,o,a),pa.has(g)&&r++;const y=g==="call"&&c&&u==="",w={char:m,kind:g,open:f,close:-1,depth:s.length+1,levels:r,items:0};y&&(w.declaration=!0),i==="slash"&&(w.afterSlash=!0),c=!1,n.push(w),s.push({span:w,commas:0,tail:!1}),i="other",u=m,f++;continue}if(h===41||h===93||h===125){const m=s.pop();m!==void 0&&(m.span.close=f,m.span.items=m.commas+(m.tail?1:0),pa.has(m.span.kind)&&r--),h===125&&l!==null&&s.length<l&&(l=null),i="operand",u="",f++;continue}if(h===59&&l!==null&&s.length<=l&&(l=null),h===44){const m=s[s.length-1];m!==void 0&&(m.commas++,m.tail=!1)}i=h===47?"slash":"other",u=t[f],f++}for(const h of s)h.span.items=h.commas+(h.tail?1:0);return n}function sh(t,e,n,s){const r=e==="word"&&(s||!Bu.has(n));return t==="("?e==="dollar"?"interpolation":r?s?"method":"call":"group":t==="["?r||e==="operand"?"index":"list":r||e==="operand"||e==="slash"?"block":"map"}function rh(t,e,n,s){const r=t.length;let i=e+1;for(;i<r;){const o=t.charCodeAt(i);if(o===92){i+=2;continue}if(o===n)return i+1;if(s&&(o===10||o===13))return i;i++}return r}function ih(t,e){const n=t.length;let s=e+1,r=!1;for(;s<n;){const i=t.charCodeAt(s);if(i===92){s+=2;continue}if(i===10||i===13)return s;if(r){i===93&&(r=!1),s++;continue}if(i===91){r=!0,s++;continue}if(i===47)return s+1;s++}return n}function ho(t){let e="",n=0,s=!1,r=!1;for(;n<t.length;){const i=t[n];if(i==="\\"){const o=t[n+1];if(o===void 0){e+="\\";break}if(!s&&o==="A"){e+="^",n+=2;continue}if(!s&&o==="z"){e+="$",n+=2;continue}if((o==="x"||o==="u")&&t[n+2]==="{"){const a=t.indexOf("}",n+3);if(a!==-1){const c=t.slice(n+3,a);if(/^[0-9A-Fa-f]+$/.test(c)){e+=String.fromCodePoint(parseInt(c,16)),n=a+1,r=!1;continue}}}e+=t.slice(n,n+2),n+=2,r=!1;continue}if(s){if(i==="]"&&r){e+="\\]",n++,r=!1;continue}i==="]"&&(s=!1),e+=i,n++,r=!1;continue}if(i==="["){s=!0,e+="[",n++,t[n]==="^"&&(e+="^",n++),r=!0;continue}if(i==="("&&t[n+1]==="?"){const o=t.slice(n+2),a=/^P<([A-Za-z_][A-Za-z0-9_]*)>/.exec(o);if(a){e+=`(?<${a[1]}>`,n+=2+a[0].length;continue}const c=/^([imsU-]+):/.exec(o);if(c){e+="(?:",n+=2+c[0].length;continue}const u=/^([imsU-]+)\)/.exec(o);if(u){const l=t[n+2+u[0].length];if(l==="*"||l==="+"||l==="?"||l==="{")throw new Error("Nothing to repeat after inline flag group");e+="(?:)",n+=2+u[0].length;continue}}e+=i,n++}return e}const Zn=21,Wu=11,po=99,oh="Maximum allowed variable count of 10 for a given function has been reached.",Vu="Expression is too complex to evaluate safely.",Gu="Missing 'match' keyword before path.",ah="Invalid glob match expression. Only one glob match is permitted in a match declaration path.";function ch(t){return`Maximum allowed call depth of 20 is reached for [${t.join("->")}] call stack.`}function uh(t){return`Function ${t} is already defined.`}function mo(t){const e=mh(t),n=[],s=t.service.name!=="firebase.storage";t.version!=="1"&&t.version!=="2"&&t.version!=="2+modules"?n.push({code:"UNSUPPORTED_RULES_VERSION",message:`Unsupported rules version ${t.version}.`,line:t.loc?.line??1}):s&&(t.version==="2+modules"||(t.imports?.length??0)>0)&&n.push({code:"UNRESOLVED_MODULES",message:"Rules source uses '2+modules' or import statements that must be resolved before compilation.",line:t.loc?.line??1});for(const i of e){const o=i.fn;if(o.lets.length>Wu){const a=o.returnLoc??o.loc;n.push({code:"LET_LIMIT",message:oh,..._r(a),...o.returnLoc===void 0?{}:{column:o.returnLoc.col},functionName:o.name})}for(const a of o.lets)Vr(n,a.value,a.loc?.line??o.loc?.line,o.name),Ps(n,a.value,a.loc?.line??o.loc?.line,s,o.name);Vr(n,o.body,o.loc?.line,o.name),Ps(n,o.body,o.returnLoc?.line??o.loc?.line,s,o.name)}const r=i=>{for(const o of i.allows)Vr(n,o.condition,o.loc?.line),Ps(n,o.condition,o.loc?.line,s);for(const o of i.children)r(o)};return r(t.service.match),n.push(...gh(e)),n.push(...lh(t)),n.push(...Hu(t.service.match,0)),n.sort((i,o)=>(i.line??0)-(o.line??0))}function Hu(t,e){const n=t.path.segments.filter(r=>r.type==="recursive").length,s=n>0&&e+n>1?[{code:"GLOB_MATCH_COUNT",message:ah,..._r(t.loc)}]:[];for(const r of t.children)s.push(...Hu(r,e+n));return s}function lh(t){const e=[],n=(r,i)=>{const o=new Set;for(const a of r)o.has(a.name)&&e.push({code:"FUNCTION_REDEFINED",message:uh(a.name),..._r(a.loc),functionName:a.name,scope:i}),o.add(a.name)},s=r=>{n(r.functions,r.path.raw);for(const i of r.children)s(i)};return n(t.functions??[],"global scope"),n(t.service.functions??[],`service ${t.service.name}`),s(t.service.match),e}function dh(t){return t.map(e=>e.line===void 0?e.message:`Line ${e.line}: ${e.message}`).join(" ")}function _r(t){return t===void 0?{}:{line:t.line}}function Vr(t,e,n,s){const r=hh(e);for(let i=0;i<r;i++)t.push({code:"NESTING_DEPTH",message:Vu,...n===void 0?{}:{line:n},...s===void 0?{}:{functionName:s}})}function fh(t){if(/\\[1-9]/.test(t)||/\(\?<?[=!]/.test(t))return!1;try{return new RegExp(`^(?:${ho(t)})$`),!0}catch{return!1}}function Ps(t,e,n,s,r){if(e.type==="binaryOp"&&e.slashStartsPath&&t.push({code:"SLASH_STARTS_PATH",message:Gu,...n===void 0?{}:{line:n},...r===void 0?{}:{functionName:r}}),s&&e.type==="methodCall"&&e.method==="matches"&&e.args.length===1){const i=e.args[0];i?.type==="literal"&&typeof i.value=="string"&&!fh(i.value)&&t.push({code:"INVALID_REGEX_PATTERN",message:`Invalid regular expression pattern. Pattern: ${i.value}.`,...n===void 0?{}:{line:n},...r===void 0?{}:{functionName:r}})}for(const i of go(e))Ps(t,i,n,s,r)}function hh(t){return Ku(t,1)}function ma(t,e,n){for(let s=e;s<n;s++){const r=t.charCodeAt(s);if(r!==32&&r!==9&&r!==10&&r!==13)return!1}return!0}function ga(t){const e=zu(t,{comments:!0,regexLiterals:!1,multilineStrings:!1});let n,s,r=-1;for(let i=0;i<e.length;i++){const o=e[i];if(o.open<r)continue;if(o.depth>Vs)return{offset:o.open,expected:`brackets nested at most ${Vs} levels deep`};if(o.levels<po||o.items===0)continue;const a=o.close===-1?t.length:o.close,c=t.slice(o.open+1,a),u=o.kind==="map"?"a:1":"1",l=Array.from({length:o.items},()=>u).join(",");if(c.replace(/[\n\r]/g,"").length<l.length)continue;let d=0;const f=c.replace(/[^\n\r]/g,()=>d<l.length?l[d++]:" ");if(n??=[],n.push(t.slice(Math.max(r,0),o.open+1),f),r=a===t.length?1/0:a,o.close!==-1){let p=i;for(;p+1<e.length;){const g=e[p],b=e[p+1],y=(g.kind==="group"||g.kind==="list")&&g.items===1,w=b.close!==-1&&b.open>g.open&&b.close<g.close,v=(b.kind==="group"||b.kind==="list"||b.kind==="map")&&b.items>=1;if(!y||!w||!v||!ma(t,g.open+1,b.open)||!ma(t,b.close+1,g.close))break;p++}const h=e[p];let m=t.slice(h.open,h.close+1);h.kind==="call"&&(m=`[${t.slice(h.open+1,h.close)}]`),s??=[],s.push({offset:h.open,text:m})}}return n===void 0?{source:t}:(r!==1/0&&n.push(t.slice(r)),{source:n.join(""),...s===void 0?{}:{elided:s}})}function Ku(t,e){const n=e+ks(t);if(n>po)return 1;const s=ph(t)?n+1:n;let r=0;for(const i of go(t))r+=Ku(i,s);return r}function ph(t){switch(t.type){case"binaryOp":case"inExpr":case"isExpr":case"listLiteral":case"mapLiteral":case"functionCall":return!0;default:return!1}}function go(t){switch(t.type){case"literal":case"identifier":return[];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end];case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args}}function mh(t){const e=[],n=[],s=(o,a)=>{const c={names:new Map,parent:a};for(const u of o){const l={fn:u,callees:[]};e.push(l),c.names.set(u.name,l),n.push({node:l,scope:c})}return c},r=s(t.service.functions??[],s(t.functions??[],void 0)),i=(o,a)=>{const c=s(o.functions,a);for(const u of o.children)i(u,c)};i(t.service.match,r);for(const{node:o,scope:a}of n){const c=new Set,u=l=>{if(l.type==="functionCall")for(let d=a;d;d=d.parent){const f=d.names.get(l.name);if(f!==void 0){c.has(f)||(c.add(f),o.callees.push(f));break}}for(const d of go(l))u(d)};for(const l of o.fn.lets)u(l.value);u(o.fn.body)}return e}function gh(t){const e=new Map,n=new Set,s=u=>{const l=e.get(u);if(l!==void 0)return l;if(n.has(u))return 1/0;n.add(u);let d=0;for(const f of u.callees)d=Math.max(d,s(f));return n.delete(u),e.set(u,d+1),d+1},r=new Set;for(const u of t)for(const l of u.callees)l!==u&&r.add(l);const i=new Set,o=u=>{if(!i.has(u)){i.add(u);for(const l of u.callees)o(l)}},a=[];for(const u of t)r.has(u)||(a.push(u),o(u));for(const u of t)i.has(u)||s(u)!==1/0||(a.push(u),o(u));const c=[];for(const u of a){if(s(u)<=Zn)continue;const l=[u];for(;l.length<=Zn;){const f=l[l.length-1];let p=f.callees[0];for(const h of f.callees)s(h)>s(p)&&(p=h);l.push(p)}const d=l[Zn];c.push({code:"CALL_DEPTH",message:ch(l.slice(0,Zn).map(f=>f.fn.name)),..._r(d.fn.loc),functionName:d.fn.name})}return c}const rs=new WeakMap;function bn(t){return rs.get(t)}function yh(t,e){rs.set(t,e)}const Gs=new WeakMap;function Zu(t){return Gs.get(t)??rs.get(t)}function Ju(t,e){Gs.set(t,e)}function Z0(t,e){const n=rs.get(t);n!==void 0&&rs.set(e,n);const s=Gs.get(t);s!==void 0&&Gs.set(e,s)}function bh(t){return`line ${t.line}, column ${t.column}`}class Qu{lineOffset;firstLineColumnOffset;lineStarts=[0];constructor(e,n,s){this.lineOffset=n,this.firstLineColumnOffset=s;for(let r=0;r<e.length;r++)e.charCodeAt(r)===10&&this.lineStarts.push(r+1)}at(e){let n=0,s=this.lineStarts.length-1;for(;n<s;){const i=n+s+1>>1;this.lineStarts[i]<=e?n=i:s=i-1}const r=e-this.lineStarts[n]+1;return{line:n+1+this.lineOffset,column:n===0?r+this.firstLineColumnOffset:r}}}const yo=24,Cn="ǂǂ",an=`${Cn}wǂ`,vh=t=>t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t===450;function vi(t,e){if(!(t.length<=e.length)&&!/[\n\r]/.test(t.slice(0,e.length)))return e+t.slice(e.length).replace(/[^\n\r]/g," ")}function wh(t,e,n){if(e.close===-1)return;let s=32;switch(e.open>0&&(s=t.charCodeAt(e.open-1)),e.kind){case"group":case"list":case"map":{if(e.afterSlash||s===47||e.items===0)return;const r=t.slice(e.open,e.close+1),i=vi(r,vh(s)?` ${n}`:n);return i===void 0?void 0:{name:n,kind:"expr",start:e.open,original:r,replacement:i,text:r,prefix:0}}case"interpolation":case"call":case"method":case"index":{if(e.items===0||e.declaration)return;const r=t.slice(e.open+1,e.close),i=vi(` ${r}`,` ${n}`)?.slice(1);if(i===void 0)return;if(e.kind==="interpolation")return{name:n,kind:"expr",start:e.open+1,original:r,replacement:i,text:r,prefix:0};const o=e.kind==="index"?"index":"args",a=`${an}${t.slice(e.open,e.close+1)}`;return{name:n,kind:o,start:e.open+1,original:r,replacement:i,text:a,prefix:an.length+1}}default:return}}function Sh(t,e=yo){if(t.indexOf(Cn,t.startsWith(an)?an.length:0)!==-1)return;const n=Math.max(e,2),s=zu(t,{comments:!0,regexLiterals:!1,multilineStrings:!1}),r=[],i=[];let o=0;for(const a of s){if(a.depth<n||a.open<o)continue;const c=wh(t,a,`${Cn}${r.length}ǂ`);c!==void 0&&(i.push(t.slice(o,c.start),c.replacement),o=c.start+c.original.length,r.push(c))}if(r.length!==0)return i.push(t.slice(o)),{text:i.join(""),segments:r}}function is(t){if(typeof t!="object"||t===null)return;const e=t;if(!(e.type!=="identifier"||typeof e.name!="string"||!e.name.startsWith(Cn)))return e.name===an?void 0:e.name}function ya(t){return t.type==="identifier"&&t.name===an}function Ah(t){return is(t)!==void 0}function kh(t,e){const n=new Set,s=new WeakSet,r=c=>e.get(c)?.segment.kind,i=(c,u)=>{const l=e.get(c);if(!(l===void 0||l.segment.kind!==u||n.has(c)))return n.add(c),s.add(l.ast),l},o=is(t);if(o!==void 0){const c=i(o,"expr");return c===void 0||n.size!==e.size?void 0:ba(t,c.ast)}const a=[t];for(;a.length>0;){const c=a.pop();if(!(s.has(c)||ArrayBuffer.isView(c))){if(!Eh(c,r,i)||c.type==="pathLiteral"&&!Ih(c,e))return;for(const u of Object.keys(c)){const l=c[u];if(typeof l!="object"||l===null)continue;const d=is(l);if(d===void 0){a.push(l);continue}if(u==="key"&&"value"in c&&!("type"in c))return;const f=i(d,"expr");if(f===void 0)return;c[u]=ba(l,f.ast)}}}return n.size===e.size?t:void 0}function ba(t,e){const n=ks(t);for(let r=0;r<n;r++)fo(e);const s=Zu(t);return n>0&&s!==void 0&&e.type==="binaryOp"&&e.op==="&&"&&Ju(e,s),e}function Eh(t,e,n){if(t.type==="functionCall"||t.type==="methodCall"){const s=t.args;if(s.length!==1)return!0;const r=is(s[0]);if(r===void 0||e(r)!=="args")return!0;const i=n(r,"args")?.ast;return i===void 0||i.type!=="functionCall"||i.name!==an?!1:(t.args=i.args,!0)}if(t.type==="bracketAccess"){const s=is(t.index);if(s===void 0||e(s)!=="index")return!0;const r=n(s,"index")?.ast;return r===void 0?!1:r.type==="bracketAccess"&&ya(r.object)?(t.index=r.index,!0):r.type==="sliceAccess"&&ya(r.object)?(delete t.index,t.type="sliceAccess",t.start=r.start,t.end=r.end,!0):!1}return!0}function Ih(t,e){let n=t.raw;if(!n.includes(Cn))return!0;for(const{segment:s}of e.values())n.includes(s.name)&&(n=n.split(s.replacement).join(s.original));return t.raw=n,!n.includes(Cn)}function _h(t){return t.length<4||/[\n\r]/.test(t.slice(-2))?vi(t,"(!1)"):`(!${t.slice(2,-2).replace(/[^\n\r]/g," ")}1)`}function xh(t,e){const n=[];let s=0;for(const r of e){let i;r.kind==="expr"&&(i=_h(r.original)),n.push(t.slice(s,r.start),i??r.replacement),s=r.start+r.original.length}return n.push(t.slice(s)),n.join("")}function Yu(t,e,n,s=0,r=0,i=yo){const o=Sh(t,i);if(o===void 0)return n(t,e,s,r);const a=n(o.text,e,s,r);if(!a.ok)return a;const c=new Map;for(const l of o.segments){const d=s+l.start-r,f=Yu(l.text,"Expr",n,d,l.prefix,i);if(!f.ok)return f;c.set(l.name,{segment:l,ast:f.ast})}const u=kh(a.ast,c);if(u===void 0){const l=n(xh(t,o.segments),e,s,r);return l.ok?n(t,e,s,r):l}return{ok:!0,ast:u}}const wi=eh(th),Xu=wi.createSemantics();let Lt=null;function K(t,e){return Lt!==null&&yh(t,Lt.at(e.source.startIdx)),t}function va(t,e){return Lt!==null&&Ju(t,Lt.at(e.source.startIdx)),t}Xu.addOperation("toAST",{RulesFile_versionFirst(t,e,n,s){return{imports:e.children.map(r=>r.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:n.children.map(r=>r.toAST()),service:s.toAST()}},RulesFile_importsFirst(t,e,n,s){return{imports:t.children.map(r=>r.toAST()),version:e.toAST(),functions:n.children.map(r=>r.toAST()),service:s.toAST()}},ImportDecl(t,e,n,s,r,i,o,a){const{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{functions:n.asIteration().children.map(l=>l.sourceString),module:o.toAST().value,loc:{line:c,col:u}}},RulesVersion(t,e,n,s){return n.toAST().value},ServiceBlock(t,e,n,s,r,i,o){const{lineNum:a,colNum:c}=t.source.getLineAndColumn();return{name:e.sourceString,functions:[...s.children.map(u=>u.toAST()),...i.children.map(u=>u.toAST())],match:r.toAST(),loc:{line:a,col:c}}},DocumentsMatch(t,e,n,s,r){const{lineNum:i,colNum:o}=t.source.getLineAndColumn();return{...s.toAST(),path:Aa(e.sourceString),loc:{line:i,col:o}}},MatchBody(t){const e=[],n=[],s=[];for(const r of t.children){const i=r.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?n.push(i):i._kind==="match"&&s.push(i)}return{functions:e,allows:n,children:s}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,s,r){const{functions:i,allows:o,children:a}=s.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:Aa(e.sourceString),functions:i,allows:o,children:a,loc:{line:c,col:u}}},AllowStatement(t,e,n,s,r,i){const{lineNum:o,colNum:a}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:r.toAST(),loc:{line:o,col:a}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(s=>s.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,s,r,i,o,a,c){const{lets:u,expr:l,returnLoc:d}=a.toAST(),{lineNum:f,colNum:p}=e.source.getLineAndColumn();return{_kind:"function",name:n.sourceString,parameters:r.toAST(),exported:t.sourceString.trim()==="export",lets:u,body:l,returnLoc:d,loc:{line:f,col:p}}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){const{lineNum:n,colNum:s}=e.child(1).source.getLineAndColumn();return{lets:t.children.map(r=>r.toAST()),expr:e.toAST(),returnLoc:{line:n,col:s}}},LetBinding(t,e,n,s,r){const{lineNum:i,colNum:o}=t.source.getLineAndColumn();return K({name:e.sourceString,value:s.toAST(),loc:{line:i,col:o}},this)},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,s,r){return K({type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:r.toAST()},this)},LogicalOr_or(t,e,n){return K({type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()},e)},LogicalAnd_and(t,e,n){return va(K({type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()},e),this)},InIsExpr_in(t,e,n){return K({type:"inExpr",element:t.toAST(),collection:n.toAST()},e)},InIsExpr_is(t,e,n){return K({type:"isExpr",value:t.toAST(),typeName:n.sourceString},e)},Equality_eq(t,e,n){return K({type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()},e)},Equality_neq(t,e,n){return K({type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()},e)},Comparison_gte(t,e,n){return K({type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()},e)},Comparison_lte(t,e,n){return K({type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()},e)},Comparison_gt(t,e,n){return K({type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()},e)},Comparison_lt(t,e,n){return K({type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()},e)},Additive_add(t,e,n){return K({type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()},e)},Additive_sub(t,e,n){return K({type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()},e)},Multiplicative_mul(t,e,n){return K({type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()},e)},Multiplicative_div(t,e,n){const s=e.source,r=s.sourceString.charAt(s.endIdx);return K({type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST(),.../\s/.test(r)?{}:{slashStartsPath:!0}},e)},Multiplicative_mod(t,e,n){return K({type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()},e)},UnaryExpr_not(t,e){return K({type:"unaryOp",op:"!",operand:e.toAST()},this)},UnaryExpr_neg(t,e){return K({type:"unaryOp",op:"-",operand:e.toAST()},this)},PostfixExpr_methodCall(t,e,n,s,r,i){return K({type:"methodCall",object:t.toAST(),method:n.sourceString,args:r.asIteration().children.map(o=>o.toAST())},this)},PostfixExpr_memberAccess(t,e,n){return K({type:"memberAccess",object:t.toAST(),property:n.sourceString},this)},PostfixExpr_bracketAccess(t,e,n,s){return K({type:"bracketAccess",object:t.toAST(),index:n.toAST()},this)},PostfixExpr_sliceAccess(t,e,n,s,r,i){return K({type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:r.toAST()},this)},Primary_paren(t,e,n){const s=e.toAST();return fo(s),(s.type==="binaryOp"&&s.op==="&&"||Ah(s))&&va(s,this),s},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,s){return K({type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(r=>r.toAST())},this)},PathLiteral(t,e,n){const s=[];for(const r of e.children)s.push(r.toAST());return s.push(n.toAST()),K({type:"pathLiteral",raw:this.sourceString,segments:s},this)},PathLitContSegment_interpolation(t,e,n){return e.toAST()},PathLitContSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitContSegment_parenLiteral(t){return t.sourceString.slice(0,-1)},PathLitContSegment_literal(t){return t.sourceString.slice(0,-1)},PathLitSegment_interpolation(t,e,n){return e.toAST()},PathLitSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,n){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,n,s){return K({type:"listLiteral",elements:e.asIteration().children.map(r=>r.toAST())},this)},MapLiteral(t,e,n,s){return K({type:"mapLiteral",entries:e.asIteration().children.map(r=>r.toAST())},this)},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return K({type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString},this)},number_int(t){return K({type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString},this)},string_single(t,e,n){return K({type:"literal",value:wa(e.sourceString),raw:this.sourceString},this)},string_double(t,e,n){return K({type:"literal",value:wa(e.sourceString),raw:this.sourceString},this)},bytes_single(t,e,n,s){return K({type:"literal",value:Sa(n.sourceString),raw:this.sourceString},this)},bytes_double(t,e,n,s){return K({type:"literal",value:Sa(n.sourceString),raw:this.sourceString},this)},bool_true(t){return K({type:"literal",value:!0,raw:"true"},this)},bool_false(t){return K({type:"literal",value:!1,raw:"false"},this)},null(t){return K({type:"literal",value:null,raw:"null"},this)},ident(t,e){return K({type:"identifier",name:this.sourceString},this)},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});const Ch={"\\":92,"'":39,'"':34,n:10,r:13,t:9,b:8,f:12};function el(t,e,n){let s=0,r=0;for(;r<t.length;){if(t[r]!=="\\"){r++;continue}r>s&&e(t.slice(s,r));const i=t[r+1];i==="x"?(n(parseInt(t.slice(r+2,r+4),16)),r+=4):i==="u"?(n(parseInt(t.slice(r+2,r+6),16)),r+=6):i>="0"&&i<="3"?(n(parseInt(t.slice(r+1,r+4),8)),r+=4):(n(Ch[i]),r+=2),s=r}t.length>s&&e(t.slice(s))}function wa(t){let e="";return el(t,n=>{e+=n},n=>{e+=String.fromCharCode(n)}),e}function Sa(t){const e=[],n=new TextEncoder;return el(t,s=>{e.push(...n.encode(s))},s=>{e.push(s)}),new Uint8Array(e)}function Aa(t){const e=[],n=t.split("/").filter(Boolean);for(const s of n)if(s.startsWith("{")&&s.endsWith("}")){const r=s.slice(1,-1);r.endsWith("=**")?e.push({type:"recursive",name:r.slice(0,-3)}):e.push({type:"wildcard",name:r})}else e.push({type:"literal",value:s});return{raw:t,segments:e}}function tl(t,e,n=0){const s=t,r=n+(s.getRightmostFailurePosition?.()??0),i=s.getExpectedText?.()??"",o=s.getInterval?.();let a=s.message??"Parse error";return o!==void 0&&(s.input!==e||n!==0)&&(a=`${new o.constructor(e,r,r).getLineAndColumnMessage()}Expected ${i}`),bo(e,r,i,a)}function bo(t,e,n,s){let r=1,i=-1;for(let u=0;u<e&&u<t.length;u++)t.charCodeAt(u)===10&&(r++,i=u);const o=e-i;let a=t.indexOf(`
|
|
498
|
+
`,e);a===-1&&(a=t.length);const c=t.slice(e,Math.min(a,e+40));return{line:r,column:o,offset:e,expected:n,actual:c,message:s}}function ka(t,e){const n=bo(t,e.offset,e.expected,"");return n.message=`Line ${n.line}, col ${n.column}: Brackets nest more than ${Vs} levels deep: the rules parser reads at most ${Vs}, a limit of this parser, not of production.`,n}function Oh(t){const e=bo(t,0,"an expression with fewer chained terms","");return e.message="Line 1, col 1: The rules source chains more terms than the rules parser reads.",e}function nl(t,e){return e===void 0?wi.match(t):wi.match(t,e)}function Th(t,e,n,s,r,i){const o=nl(t,e);if(!o.succeeded())return{ok:!1,error:tl(o,r,i+n-s)};const a=Lt;if(a!==null&&(n!==0||s!==0)){const c=a.at(n);Lt=new Qu(t,c.line-1,c.column-1-s)}try{return{ok:!0,ast:Xu(o).toAST()}}finally{Lt=a}}function Rh(t,e,n,s=t,r=0,i=yo){const o=ga(t);if(!("source"in o))return{ok:!1,error:ka(s,{offset:r+o.offset,expected:o.expected})};const a=(c,u,l,d)=>Yu(c,u,(f,p,h,m)=>{if(l||f!==c)return Th(f,p,h,m,s,d);const g=nl(f,p);return g.succeeded()?{ok:!0,ast:{}}:{ok:!1,error:tl(g,s,d)}},0,0,i);try{const c=a(o.source,e,n,r);if(!c.ok)return c;if(o.elided!==void 0){const u=o.elided.map(l=>({offset:r+l.offset,text:l.text}));for(let l=0;l<u.length;l++){const d=u[l],f=ga(d.text);if(!("source"in f))return{ok:!1,error:ka(s,{offset:d.offset+f.offset,expected:f.expected})};const p=a(f.source,"Expr",!1,d.offset);if(!p.ok)return p;if(f.elided!==void 0)for(const h of f.elided)u.push({offset:d.offset+h.offset,text:h.text})}}return{ok:!0,value:c.ast}}catch(c){if(c instanceof RangeError)return{ok:!1,error:Oh(s)};throw c}}function vo(t){const e=Es(t);return e.ok?e.ast:null}function Es(t,e={}){const n=t.trim();if(!n)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const s=t.length-t.trimStart().length;let r=0,i=-1;for(let c=0;c<s;c++)t.charCodeAt(c)===10&&(r++,i=c);Lt=new Qu(n,r,s-i-1);let o;try{o=Rh(n,void 0,!0,t.trimEnd(),s,e.segmentDepth)}finally{Lt=null}if(!o.ok)return o;const a=o.value;return r>0&&Lh(a,r),{ok:!0,ast:a}}function ot(t,e){t!==void 0&&(t.line+=e)}function js(t,e){ot(t.loc,e);for(const n of t.lets)ot(n.loc,e),ot(n.value.loc,e);ot(t.body.loc,e),ot(t.returnLoc,e)}function Lh(t,e){ot(t.loc,e);for(const s of t.imports)ot(s.loc,e);for(const s of t.functions??[])js(s,e);ot(t.service.loc,e);for(const s of t.service.functions??[])js(s,e);const n=[t.service.match];for(;n.length>0;){const s=n.pop();ot(s.loc,e);for(const r of s.functions)js(r,e);for(const r of s.allows)ot(r.loc,e),ot(r.condition.loc,e);for(const r of s.children)n.push(r)}}function Nh(t,e){t.loc!==void 0&&(t.loc.file=e);for(const n of t.lets)n.loc!==void 0&&(n.loc.file=e),n.value.loc!==void 0&&(n.value.loc.file=e);t.returnLoc!==void 0&&(t.returnLoc.file=e),t.body.loc!==void 0&&(t.body.loc.file=e)}function Mh(t,e){const n=`rules_version = '2';
|
|
499
499
|
service cloud.firestore {
|
|
500
500
|
match /databases/{db}/documents {
|
|
501
501
|
${t}
|
|
502
502
|
}
|
|
503
|
-
}`,s=vo(n);if(s===null)return null;const r=s.service.match.functions;for(const i of r)js(i,-3),e!==void 0&&
|
|
504
|
-
`),sourceMap:n}}const
|
|
505
|
-
`,s);if(i===-1)return t.length;s=i+1}return Math.min(t.length,s+n-1)}function
|
|
503
|
+
}`,s=vo(n);if(s===null)return null;const r=s.service.match.functions;for(const i of r)js(i,-3),e!==void 0&&Nh(i,e);return r}const sl={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function Dh(t){switch(t.type){case"ternary":return 1;case"binaryOp":return sl[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"pathLiteral":return 7.5;case"unaryOp":return 9;default:return 100}}function $h(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${Xe(t.object,10)}.${t.property}`;case"methodCall":return`${Xe(t.object,10)}.${t.method}(${t.args.map(e=>Ae(e)).join(", ")})`;case"bracketAccess":return`${Xe(t.object,10)}[${Ae(t.index)}]`;case"sliceAccess":return`${Xe(t.object,10)}[${Ae(t.start)}:${Ae(t.end)}]`;case"binaryOp":{const e=sl[t.op]??0,n=Xe(t.left,e),s=Xe(t.right,e+1);return t.op==="/"&&t.slashStartsPath?`${n}/${s}`:`${n} ${t.op} ${s}`}case"unaryOp":return`${t.op}${Xe(t.operand,9)}`;case"ternary":return`${Xe(t.condition,2)} ? ${Ae(t.consequent)} : ${Ae(t.alternate)}`;case"inExpr":return`${Xe(t.element,5)} in ${Xe(t.collection,5)}`;case"isExpr":return`${Xe(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>Ae(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${Ae(e.key)}: ${Ae(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${Ae(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>Ae(e)).join(", ")})`}}function Xe(t,e){const n=$h(t),r=Dh(t)<e,i=Math.max(ks(t),r?1:0);return i>0?`${"(".repeat(i)}${n}${")".repeat(i)}`:n}function Ae(t){return Xe(t,0)}function Ph(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function Hs(t){return" ".repeat(t)}function In(t,e,n,s){if(t!==void 0&&t.file!==void 0){const i=t.file,o={generatedLine:e,authoredLine:t.line,authoredCol:t.col,authoredFile:i};s!==void 0&&(o.expression=s),n.push(o)}}function Si(t,e,n,s){const r=Hs(e),i=Hs(e+2),o=t.parameters.join(", ");let a="";t.exported===!0&&(a="export ");const u=n.length+1;n.push(`${r}${a}function ${t.name}(${o}) {`),In(t.loc,u,s);for(const d of t.lets){const f=n.length+1;n.push(`${i}let ${d.name} = ${Ae(d.value)};`),In(d.loc??t.loc,f,s)}const l=n.length+1;n.push(`${i}return ${Ae(t.body)};`),In(t.returnLoc??t.body.loc??t.loc,l,s),n.push(`${r}}`)}function jh(t,e,n,s){const r=Hs(e),i=t.operations.join(", "),o=Ae(t.condition),a=n.length+1;n.push(`${r}allow ${i}: if ${o};`),In(t.loc,a,s,o)}function rl(t,e,n,s){const r=Hs(e),i=e+2,o=n.length+1;n.push(`${r}match ${Ph(t.path)} {`),In(t.loc,o,s);for(const a of t.functions)Si(a,i,n,s);for(const a of t.allows)jh(a,i,n,s);for(const a of t.children)rl(a,i,n,s);n.push(`${r}}`)}function Ea(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}function Ia(t){const e=[],n=[];for(const a of t.imports)e.push(`import { ${a.functions.join(", ")} } from '${Ea(a.module)}';`);if(e.push(`rules_version = '${Ea(t.version)}';`),t.functions!==void 0)for(const a of t.functions)Si(a,0,e,n);const r=e.length+1;if(e.push(`service ${t.service.name} {`),In(t.service.loc,r,n),t.service.functions!==void 0)for(const a of t.service.functions)Si(a,2,e,n);const o=t.service.match;return rl(o,2,e,n),e.push("}"),e.push(""),{resolved:e.join(`
|
|
504
|
+
`),sourceMap:n}}const Fh=new Set(["get","exists","getAfter","existsAfter"]);function il(t,e,n=new Set,s){const r=new Map,i=new Set;return a(t,e).count;function o(c,u){const l=r.get(c);if(l!==void 0)return{count:l,hitStack:!1};if(i.has(c)||n.has(c.name))return{count:0,hitStack:!0};const d=s?.get(c)??u;i.add(c),n.add(c.name);let f=0,p=!1;for(const m of c.lets){const g=a(m.value,d);f+=g.count,g.hitStack&&(p=!0)}const h=a(c.body,d);return f+=h.count,h.hitStack&&(p=!0),n.delete(c.name),i.delete(c),p||r.set(c,f),{count:f,hitStack:p}}function a(c,u){let l=0,d=!1;const f=p=>{const h=a(p,u);l+=h.count,h.hitStack&&(d=!0)};switch(c.type){case"functionCall":if(Fh.has(c.name))l++;else{const p=u.get(c.name);if(p!==void 0){const h=o(p,u);l+=h.count,h.hitStack&&(d=!0)}}c.args.forEach(f);break;case"binaryOp":f(c.left),f(c.right);break;case"unaryOp":f(c.operand);break;case"ternary":f(c.condition),f(c.consequent),f(c.alternate);break;case"methodCall":c.object.type==="identifier"&&c.object.name==="firestore"&&(c.method==="get"||c.method==="exists")&&l++,f(c.object),c.args.forEach(f);break;case"memberAccess":f(c.object);break;case"bracketAccess":f(c.object),f(c.index);break;case"sliceAccess":f(c.object),f(c.start),f(c.end);break;case"inExpr":f(c.element),f(c.collection);break;case"isExpr":f(c.value);break;case"listLiteral":c.elements.forEach(f);break;case"mapLiteral":c.entries.forEach(p=>{f(p.key),f(p.value)});break;case"pathLiteral":for(const p of c.segments)typeof p!="string"&&f(p);break}return{count:l,hitStack:d}}}function Gr(t){return t.map(e=>e.type==="literal"?`/${e.value}`:e.type==="wildcard"?`/{${e.name}}`:`/{${e.name}=**}`).join("")}function qh(t){const e=t.findIndex(u=>u.type==="recursive");if(e===-1)return null;const n=Gr(t),s=Gr(t.slice(0,e)),r=t.slice(e+1);if(r.length===0)return{kind:"subtree",fullPath:n,description:s?`every document under ${s}`:"every document in the database"};const i=s?` under ${s}`:"",[o,a]=r,c=r.length===2&&o?.type==="literal"&&a?.type==="wildcard"?`every document in a collection named ${o.value} at any depth${i}`:`every document whose path ends in ${Gr(r)}${i}`;return{kind:"suffix",fullPath:n,description:c}}const ol=new Set(["get","exists","getAfter","existsAfter","int","float","string","path"]),Uh=new Set(["int","float","string","path"]),wo=new Set(["request","resource","math","timestamp","duration","latlng","hashing"]),Bh=new Set([...wo,"firestore"]);function al(t){const e={functions:[],rules:[]},n=t.service?.name==="firebase.storage",s=new Set(n?Uh:ol);for(const f of t.imports??[]){const p=f.functions??f.names??[];for(const h of p)s.add(h)}const r=n?Bh:wo,i=t.functions??[],o=t.service.functions??[],a=Hr(new Map,i),c=Hr(a,o),u=new Set;for(const f of i)e.functions.push({fn:f,label:"global scope",functions:a,captures:u,globalFunctions:s,globalIdentifiers:r});const l=`service ${t.service.name}`;for(const f of o)e.functions.push({fn:f,label:l,functions:c,captures:u,globalFunctions:s,globalIdentifiers:r});const d=(f,p,h)=>{const m=Hr(p,f.functions),g=new Set(h);for(const y of f.path.segments)y.type!=="literal"&&g.add(y.name);const b=f.path.raw;for(const y of f.functions)e.functions.push({fn:y,label:b,functions:m,captures:g,globalFunctions:s,globalIdentifiers:r});for(const y of f.allows)e.rules.push({rule:y,match:f,label:b,functions:m,captures:g,globalFunctions:s,globalIdentifiers:r});for(const y of f.children)d(y,m,g)};return d(t.service.match,c,u),e}function Hr(t,e){const n=new Map(t);for(const s of e)n.set(s.name,s);return n}function cl(t){const e=zh(),n=new Set(t.fn.parameters);for(const s of t.fn.lets)_a(s.value,t,n,e),n.add(s.name);return _a(t.fn.body,t,n,e),e}function zh(){return{callees:[],undefinedCalls:[],unboundVariables:[]}}function _a(t,e,n,s){const r=e.globalIdentifiers??wo,i=e.globalFunctions??ol,o=(c,u)=>{c.includes(u)||c.push(u)},a=c=>{switch(c.type){case"identifier":!n.has(c.name)&&!e.captures.has(c.name)&&!r.has(c.name)&&o(s.unboundVariables,c.name);return;case"functionCall":{const u=e.functions.get(c.name);u?o(s.callees,u):i.has(c.name)||o(s.undefinedCalls,c.name),c.args.forEach(a);return}case"binaryOp":a(c.left),a(c.right);return;case"unaryOp":a(c.operand);return;case"ternary":a(c.condition),a(c.consequent),a(c.alternate);return;case"methodCall":a(c.object),c.args.forEach(a);return;case"bracketAccess":a(c.object),a(c.index);return;case"sliceAccess":a(c.object),a(c.start),a(c.end);return;case"memberAccess":a(c.object);return;case"inExpr":a(c.element),a(c.collection);return;case"isExpr":a(c.value);return;case"listLiteral":c.elements.forEach(a);return;case"mapLiteral":c.entries.forEach(u=>{a(u.key),a(u.value)});return;case"pathLiteral":for(const u of c.segments)typeof u!="string"&&a(u);return;case"literal":return;default:{const u=c;throw new Error(`collectReferences: unhandled type ${u.type}`)}}};a(t)}function Wh(t){const e=new Map;for(const o of t.functions)e.set(o.fn,cl(o).callees);const n=new Map,s=new Map,r=new Set,i=(o,a)=>{const c=n.get(o);if(c!==void 0)return{depth:c,hitStack:!1};if(a.has(o))return{depth:0,hitStack:!0};a.add(o);let u=0,l=!1;for(const f of e.get(o)??[]){const p=i(f,a);u=Math.max(u,p.depth),p.hitStack&&(l=!0)}a.delete(o);const d=1+u;return l||n.set(o,d),{depth:d,hitStack:l}};for(const o of t.functions){const a=i(o.fn,new Set);s.set(o.fn,a.depth),a.hitStack&&r.add(o.fn)}return{depths:s,cyclic:r}}const Vh={allow:"the allow statement",let:"the let binding",return:"the return expression",rules_version:"the version line"},Gh={service:"the service block",match:"the match block",function:"the function body"},Hh="the map literal",Kh="at the end of the statement",Zh=8;function Jh(t,e,n){let s=0;for(let r=1;r<e;r++){const i=t.indexOf(`
|
|
505
|
+
`,s);if(i===-1)return t.length;s=i+1}return Math.min(t.length,s+n-1)}function Qh(t,e){const n=[];let s=1,r=0;for(;r<e;){const i=t[r];if(i===`
|
|
506
506
|
`)s++,r++;else if(/\s/.test(i))r++;else if(t.startsWith("//",r))for(;r<t.length&&t[r]!==`
|
|
507
507
|
`;)r++;else if(t.startsWith("/*",r)){const o=t.indexOf("*/",r+2),a=o===-1?t.length:o+2;for(;r<a;r++)t[r]===`
|
|
508
508
|
`&&s++}else if(i==="'"||i==='"'){for(r++;r<t.length&&t[r]!==i&&t[r]!==`
|
|
509
|
-
`;)r+=t[r]==="\\"?2:1;r++}else if(/[A-Za-z_]/.test(i)){const o=r;for(;r<t.length&&/[A-Za-z0-9_]/.test(t[r]);)r++;n.push({text:t.slice(o,r),offset:o,line:s})}else n.push({text:i,offset:r,line:s}),r++}return n}function ul(t,e){return t[e-1]?.text!=="."}function So(t,e,n){const s=e[n-1];return s!==void 0&&s.text==="/"&&s.offset===e[n].offset-1}function
|
|
509
|
+
`;)r+=t[r]==="\\"?2:1;r++}else if(/[A-Za-z_]/.test(i)){const o=r;for(;r<t.length&&/[A-Za-z0-9_]/.test(t[r]);)r++;n.push({text:t.slice(o,r),offset:o,line:s})}else n.push({text:i,offset:r,line:s}),r++}return n}function ul(t,e){return t[e-1]?.text!=="."}function So(t,e,n){const s=e[n-1];return s!==void 0&&s.text==="/"&&s.offset===e[n].offset-1}function Yh(t){for(let e=t.length-1;e>=0;e--){const n=t[e].text;if(n===";")return;const s=Vh[n];if(s!==void 0&&ul(t,e))return s}}function ll(t,e,n){for(let s=n-1;s>=0;s--){const r=e[s].text;if(r===";"||(r==="{"||r==="}")&&!So(t,e,s)&&!dl(t,e,s))return;const i=Gh[r];if(i!==void 0&&ul(e,s))return i}}function dl(t,e,n){if(e[n].text!=="}")return!1;for(let s=n-1;s>=0;s--){const r=e[s].text;if(r==="{")return So(t,e,s);if(r==="}"||r===";")return!1}return!1}function Xh(t,e){const n=[];for(let s=0;s<e.length;s++){const r=e[s];r.text==="{"&&!So(t,e,s)?n.push({construct:ll(t,e,s)??Hh,line:r.line}):r.text==="}"&&!dl(t,e,s)&&n.pop()}return n}function fl(t,e){return t.includes(`"${e}"`)}function hl(t){const e=t.match(/"[^"]*"/g);return e===null?0:e.length}function xa(t,e){return hl(t)===1&&fl(t,e)}function ep(t,e){const n=Qh(e,Jh(e,t.line,t.column));if(fl(t.expected,";")){const s=Yh(n);return s===void 0?`expected ';' ${Kh}`:`expected ';' after ${s}`}if(xa(t.expected,"{")){const s=ll(e,n,n.length);if(s!==void 0)return`expected '{' to open ${s}`}if(xa(t.expected,"}")){const s=Xh(e,n).at(-1);if(s!==void 0)return`expected '}' to close ${s.construct} opened at line ${s.line}`}return hl(t.expected)<=Zh?`expected ${t.expected}`:"syntax error"}function tp(t){const e=pl(t);return e.ok?null:e.rejection}function pl(t){const e=Es(t);if(!e.ok){const{line:s,column:r}=e.error;return{ok:!1,rejection:{kind:"parse",line:s,column:r,message:`rules did not parse at line ${s}, column ${r}: ${ep(e.error,t)}.`}}}const n=mo(e.ast);return n.length===0?{ok:!0,ast:e.ast}:{ok:!1,rejection:{kind:"compile",violations:n,message:`rules did not compile: ${dh(n)}`}}}const Kr=new Set(["get","exists","getAfter","debug"]);function Ca(t,e){if(t.type!=="binaryOp"||t.op!==e)return 0;let n=1,s=t;for(;s.type==="binaryOp"&&s.op===e;)n++,s=s.left;return n}function np(t){let e={op:"",depth:0};function n(r){if(r.type==="binaryOp"){const i=Ca(r,"&&"),o=Ca(r,"||");i>e.depth&&(e={op:"&&",depth:i}),o>e.depth&&(e={op:"||",depth:o}),n(r.left),n(r.right)}else s(r)}function s(r){switch(r.type){case"unaryOp":n(r.operand);break;case"methodCall":n(r.object),r.args.forEach(n);break;case"memberAccess":n(r.object);break;case"bracketAccess":n(r.object),n(r.index);break;case"ternary":n(r.condition),n(r.consequent),n(r.alternate);break;case"inExpr":n(r.element),n(r.collection);break;case"isExpr":n(r.value);break;case"listLiteral":r.elements.forEach(n);break;case"mapLiteral":r.entries.forEach(i=>{n(i.key),n(i.value)});break;case"functionCall":r.args.forEach(n);break}}return n(t),e}function se(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${se(t.object)}.${t.property}`;case"methodCall":return`MC:${se(t.object)}.${t.method}(${t.args.map(se).join(",")})`;case"bracketAccess":return`B:${se(t.object)}[${se(t.index)}]`;case"binaryOp":return`BO:${se(t.left)}${t.op}${se(t.right)}`;case"unaryOp":return`UO:${t.op}${se(t.operand)}`;case"ternary":return`T:${se(t.condition)}?${se(t.consequent)}:${se(t.alternate)}`;case"inExpr":return`IN:${se(t.element)}in${se(t.collection)}`;case"isExpr":return`IS:${se(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(se).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>se(e.key)+":"+se(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(se).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${se(t.object)}[${se(t.start)}:${se(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function ml(t){return t.type==="binaryOp"&&t.op==="&&"?ml(t.left):t}function sp(t,e){const n=new Map,s=r=>{switch(r.type){case"functionCall":e.has(r.name)&&n.set(r.name,(n.get(r.name)??0)+1),r.args.forEach(s);break;case"binaryOp":s(r.left),s(r.right);break;case"unaryOp":s(r.operand);break;case"methodCall":s(r.object),r.args.forEach(s);break;case"memberAccess":s(r.object);break;case"bracketAccess":s(r.object),s(r.index);break;case"ternary":s(r.condition),s(r.consequent),s(r.alternate);break;case"inExpr":s(r.element),s(r.collection);break;case"isExpr":s(r.value);break;case"listLiteral":r.elements.forEach(s);break;case"mapLiteral":r.entries.forEach(i=>{s(i.key),s(i.value)});break}};return s(t),n}function gl(t,e,n=new Set,s,r=new Set){const i=e.get(t);if(!i||r.has(i)||n.has(t))return!1;n.add(t),r.add(i);const o=s?.get(i)??e,a=c=>{switch(c.type){case"functionCall":return c.name==="get"||c.name==="exists"||c.name==="getAfter"||c.name==="existsAfter"||o.has(c.name)&&gl(c.name,o,new Set,s,r)?!0:c.args.some(a);case"binaryOp":return a(c.left)||a(c.right);case"unaryOp":return a(c.operand);case"methodCall":return c.object.type==="identifier"&&c.object.name==="firestore"&&(c.method==="get"||c.method==="exists")?!0:a(c.object)||c.args.some(a);case"memberAccess":return a(c.object);case"bracketAccess":return a(c.object)||a(c.index);case"sliceAccess":return a(c.object)||a(c.start)||a(c.end);case"ternary":return a(c.condition)||a(c.consequent)||a(c.alternate);case"inExpr":return a(c.element)||a(c.collection);case"isExpr":return a(c.value);case"listLiteral":return c.elements.some(a);case"mapLiteral":return c.entries.some(u=>a(u.key)||a(u.value));case"pathLiteral":return c.segments.some(u=>typeof u!="string"&&a(u));default:return!1}};return a(i.body)||i.lets.some(c=>a(c.value))}function Ai(t,e,n=new Set,s,r=new Set){const i=o=>{switch(o.type){case"memberAccess":return o.property==="time"&&o.object.type==="identifier"&&o.object.name==="request"?!0:i(o.object);case"bracketAccess":return o.object.type==="identifier"&&o.object.name==="request"&&o.index.type==="literal"&&o.index.value==="time"?!0:i(o.object)||i(o.index);case"sliceAccess":return i(o.object)||i(o.start)||i(o.end);case"functionCall":{const a=e.get(o.name);if(a&&!r.has(a)&&!n.has(o.name)){n.add(o.name),r.add(a);const c=s?.get(a)??e;if(Ai(a.body,c,new Set,s,r)||a.lets.some(u=>Ai(u.value,c,new Set,s,r)))return!0}return o.args.some(i)}case"binaryOp":return i(o.left)||i(o.right);case"unaryOp":return i(o.operand);case"methodCall":return i(o.object)||o.args.some(i);case"ternary":return i(o.condition)||i(o.consequent)||i(o.alternate);case"inExpr":return i(o.element)||i(o.collection);case"isExpr":return i(o.value);case"listLiteral":return o.elements.some(i);case"mapLiteral":return o.entries.some(a=>i(a.key)||i(a.value));case"pathLiteral":return o.segments.some(a=>typeof a!="string"&&i(a));default:return!1}};return i(t)}function rp(t){return[...t.functions??[],...t.service.functions??[],...yl(t.service.match)]}function yl(t){const e=[...t.functions];for(const n of t.children)e.push(...yl(n));return e}function ip(t,e){if(!t)return e;const n=t.endsWith("/")?t.slice(0,-1):t,s=e.startsWith("/")?e:`/${e}`;return`${n}${s}`}function Ao(t,e=""){const n=t.path.raw.includes("databases")&&t.path.raw.includes("documents")||t.path.raw.includes("/b/")&&t.path.raw.includes("/o")||/^\/?b\/[^/]+\/o$/.test(t.path.raw),s=ip(e,t.path.raw),r=n&&!e?"":s,i=[];for(const o of t.allows)i.push({rule:o,path:s,matchFunctions:t.functions});for(const o of t.children){const a=Ao(o,r);for(const c of a)c.matchFunctions=[...t.functions,...c.matchFunctions];i.push(...a)}return i}function op(t){let e="",n=0;for(;n<t.length;){const s=t[n],r=t[n+1];if(s==="/"&&r==="/")for(n+=2;n<t.length&&t[n]!==`
|
|
510
510
|
`;)n++;else if(s==="/"&&r==="*"){for(n+=2;n<t.length&&!(t[n]==="*"&&t[n+1]==="/");)t[n]===`
|
|
511
511
|
`&&(e+=`
|
|
512
512
|
`),n++;n<t.length&&(n+=2)}else if(s==="'"||s==='"'){const i=s;for(e+=i,n++;n<t.length&&t[n]!==i&&t[n]!==`
|
|
513
|
-
`;)t[n]==="\\"&&n+1<t.length?(e+=" ",n+=2):(e+=" ",n++);n<t.length&&t[n]===i&&(e+=i,n++)}else e+=s,n++}return e}function qt(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=qt(t.left),n=qt(t.right);if(t.op==="&&")return e===!1||n===!1?!1:e===!0&&n===!0?!0:null;if(t.op==="||")return e===!0||n===!0?!0:e===!1&&n===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=qt(t.operand);return e===null?null:!e}if(t.type==="ternary"){const e=qt(t.condition);return e===!0?qt(t.consequent):e===!1?qt(t.alternate):null}return null}function pe(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${pe(t.object)}.${t.property}`;case"methodCall":return`${pe(t.object)}.${t.method}(${t.args.map(pe).join(",")})`;case"bracketAccess":return`${pe(t.object)}[${pe(t.index)}]`;case"sliceAccess":return`${pe(t.object)}[${pe(t.start)}:${pe(t.end)}]`;case"binaryOp":return`(${pe(t.left)}${t.op}${pe(t.right)})`;case"unaryOp":return`(${t.op}${pe(t.operand)})`;case"ternary":return`(${pe(t.condition)}?${pe(t.consequent)}:${pe(t.alternate)})`;case"inExpr":return`(${pe(t.element)} in ${pe(t.collection)})`;case"isExpr":return`(${pe(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(pe).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${pe(e.key)}:${pe(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(pe).join(",")})`}}function Ks(t){return t.type==="binaryOp"&&t.op==="&&"?[...Ks(t.left),...Ks(t.right)]:[t]}const ki={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},xt={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use direct comparison or validation instead of boolean casting",bool:"No `bool()` cast in rules — boolean casting is not supported in production Firestore rules.",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},sp=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),rp=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)",storageSuggestion:"Use `request.resource` (e.g. `request.resource.size`, `request.resource.contentType`, or `request.resource.metadata`)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"request.auth",property:"id",suggestion:"Use `request.auth.uid`"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)",storageSuggestion:"Use `resource != null` (or `firestore.exists()` for cross-service document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"},{receiver:"resource",property:"data",suggestion:"`resource.data` does not exist in Storage rules — use `resource.size`, `resource.contentType`, or `resource.metadata`",storageOnly:!0},{receiver:"request.resource",property:"data",suggestion:"`request.resource.data` does not exist in Storage rules — use `request.resource.size`, `request.resource.contentType`, or `request.resource.metadata`",storageOnly:!0},{receiver:"resource",property:"timeUpdated",suggestion:"Use `resource.updated` instead of `resource.timeUpdated`",storageOnly:!0},{receiver:"request.resource",property:"timeUpdated",suggestion:"Use `request.resource.updated` instead of `request.resource.timeUpdated`",storageOnly:!0}],ip=new Set(["email_verified"]),op=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),ap=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function cp(t){const e=[],n=np(t);for(const s of ap)s.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:s.message});return e}function bl(t,e,n,s){const r=t.path.raw,i=new Set(e);for(const a of t.functions)i.add(a.name);const o=new Set(n);for(const a of t.path.segments)a.type!=="literal"&&o.add(a.name);for(const a of t.functions){const c={matchPath:r,functionName:a.name},u=new Set([...o,...a.parameters]);for(const l of a.lets)ee(l.value,c,i,u,s),u.add(l.name);ee(a.body,c,i,u,s)}for(let a=0;a<t.allows.length;a++)ee(t.allows[a].condition,{matchPath:r,ruleIndex:a},i,o,s);for(const a of t.children)bl(a,i,o,s)}function ee(t,e,n,s,r){switch(r(t,e,n,s),t.type){case"binaryOp":ee(t.left,e,n,s,r),ee(t.right,e,n,s,r);break;case"unaryOp":ee(t.operand,e,n,s,r);break;case"methodCall":ee(t.object,e,n,s,r),t.args.forEach(i=>ee(i,e,n,s,r));break;case"memberAccess":ee(t.object,e,n,s,r);break;case"bracketAccess":ee(t.object,e,n,s,r),ee(t.index,e,n,s,r);break;case"sliceAccess":ee(t.object,e,n,s,r),ee(t.start,e,n,s,r),ee(t.end,e,n,s,r);break;case"ternary":ee(t.condition,e,n,s,r),ee(t.consequent,e,n,s,r),ee(t.alternate,e,n,s,r);break;case"inExpr":ee(t.element,e,n,s,r),ee(t.collection,e,n,s,r);break;case"isExpr":ee(t.value,e,n,s,r);break;case"listLiteral":t.elements.forEach(i=>ee(i,e,n,s,r));break;case"mapLiteral":t.entries.forEach(i=>{ee(i.key,e,n,s,r),ee(i.value,e,n,s,r)});break;case"functionCall":t.args.forEach(i=>ee(i,e,n,s,r));break;case"pathLiteral":t.segments.forEach(i=>{typeof i!="string"&&ee(i,e,n,s,r)});break}}function up(t,e,n){return n?!1:t.type==="functionCall"&&t.name==="debug"&&!e.has("debug")}function lp(t){return t.type==="methodCall"&&Object.hasOwn(ki,t.method)}function dp(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!sp.has(t.method)}function fp(t){return t.type!=="methodCall"||t.method!=="hasAll"&&t.method!=="hasAny"&&t.method!=="hasOnly"?!1:t.object.type==="mapLiteral"||t.object.type==="memberAccess"&&t.object.property==="data"}function hp(t,e){return t.type!=="methodCall"||t.object.type!=="identifier"||e.has(t.object.name)?!1:Object.hasOwn(xt,t.object.name)}function pp(t,e){return t.type!=="functionCall"||e.has(t.name)?!1:Object.hasOwn(xt,t.name)}function mp(t,e){return t.type!=="identifier"||e.has(t.name)?!1:Object.hasOwn(xt,t.name)}function gp(t,e=!1){if(t.type!=="memberAccess")return;let n;if(t.object.type==="identifier"?n=t.object.name:t.object.type==="memberAccess"&&t.object.object.type==="identifier"&&(n=`${t.object.object.name}.${t.object.property}`),!n)return;const s=t.property,r=rp.find(i=>i.receiver===n&&i.property===s&&(!i.storageOnly||e));if(r)return{path:`${n}.${s}`,suggestion:e&&r.storageSuggestion?r.storageSuggestion:r.suggestion}}function yp(t){if(t.type!=="memberAccess"||!ip.has(t.property))return;const e=t.object;if(e.type!=="memberAccess"||e.property!=="token")return;const n=e.object;if(!(n.type!=="memberAccess"||n.property!=="auth"))return n.object.type==="identifier"&&n.object.name==="request"?t.property:void 0}function bp(t){if(!(t.type!=="binaryOp"||t.op!=="=="&&t.op!=="!="))for(const[e,n]of[[t.left,t.right],[t.right,t.left]]){const s=yp(e);if(s&&n.type==="literal"&&typeof n.value=="string")return{claim:s,op:t.op,literal:n.value}}}function vp(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function wp(t,e=!1){if(t.type!=="memberAccess"||!op.has(t.property))return!1;if(e&&t.property==="size"){const s=t.object.type==="identifier"&&t.object.name==="resource",r=t.object.type==="memberAccess"&&t.object.property==="resource"&&t.object.object.type==="identifier"&&t.object.object.name==="request";if(s||r)return!1}return t.object.type==="identifier"&&(t.object.name==="request"||t.object.name==="resource")||t.object.type==="memberAccess"||t.object.type==="methodCall"||t.object.type==="bracketAccess"}function Sp(t,e={}){const n=[],s=new Set,r=t.service?.name==="firebase.storage";function i(u,l,d,f){const p=`${u}|${l}|${d.matchPath||""}|${d.functionName||""}|${d.ruleIndex??""}`;s.has(p)||(s.add(p),n.push(f))}const o=new Set;for(const u of t.imports??[]){const l=u.functions??u.names??[];for(const d of l)o.add(d)}for(const u of t.functions??[])o.add(u.name);const a=new Set(o);for(const u of t.service.functions??[])a.add(u.name);const c=(u,l,d,f)=>{if(up(u,d,e.allowDebug)&&i("HALLUCINATED_GLOBAL","debug",l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:"`debug()` is not a Firestore rules function and no function named `debug` is declared in scope. Production rejects the whole ruleset at compile time with `Function not found error: Name: [debug]`, so nothing in the file deploys.",location:l,fix:"Remove the debug() call and evaluate the inner expression directly."}),lp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",u.method,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${u.method}()\` does not exist in Firestore rules. ${ki[u.method]}`,location:l,fix:ki[u.method]}),dp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",`math.${u.method}`,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${u.method}()\` does not exist in production Firestore security rules.`,location:l,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),fp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",`map.${u.method}`,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${u.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:l,fix:`Insert \`.keys()\`: e.g. \`data.keys().${u.method}(...)\`.`}),hp(u,f)&&u.type==="methodCall"&&u.object.type==="identifier"){const m=u.object.name;i("HALLUCINATED_GLOBAL",`${m}.${u.method}`,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${m}.${u.method}()\` does not exist in Firestore rules. ${xt[m]}`,location:l,fix:xt[m]})}pp(u,d)&&u.type==="functionCall"&&i("HALLUCINATED_GLOBAL",u.name,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${u.name}()\` does not exist in Firestore rules. ${xt[u.name]}`,location:l,fix:xt[u.name]}),mp(u,f)&&u.type==="identifier"&&i("HALLUCINATED_GLOBAL",`ref:${u.name}`,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${u.name}\` is not a Firestore rules identifier. ${xt[u.name]}`,location:l,fix:xt[u.name]});const p=gp(u,r);p&&i("WRONG_CONTEXT_PATH",p.path,l,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${p.path}\` is not a valid ${r?"Storage":"Firestore"} rules path. ${p.suggestion}`,location:l,fix:p.suggestion});const h=bp(u);if(h){const{claim:m,op:g,literal:b}=h;i("BOOL_TOKEN_CLAIM",`${m}|${g}|${b}`,l,{rule:"BOOL_TOKEN_CLAIM",severity:"error",message:`\`request.auth.token.${m}\` is a bool, but it is compared against the string "${b}", a cross-type comparison that is always ${g==="=="?"false (rule always denies)":"true (rule silently allows)"}. Compare against the boolean literal instead: \`request.auth.token.${m} ${g} true\`.`,location:l,fix:`Drop the quotes: \`request.auth.token.${m} ${g} ${b==="false"?"false":"true"}\`.`})}if(vp(u)&&i("LENGTH_PROPERTY","",l,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:l,fix:"Replace `.length` with `.size()`."}),u.type==="pathLiteral")for(const m of u.segments){if(typeof m!="string")continue;const g=m.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!g)continue;const b=g[1];i("INVALID_PATH_INTERPOLATION",`${u.raw}|${b}`,l,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${b}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${b}}\` with \`$(${b})\` in path \`${u.raw}\`.`,location:l,fix:`Replace \`{${b}}\` with \`$(${b})\` inside the path argument.`})}wp(u,r)&&u.type==="memberAccess"&&i("METHOD_MISSING_PARENS",u.property,l,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${u.property}\` looks like a built-in method called without parentheses. Use \`.${u.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:l,fix:`Add parentheses: \`.${u.property}()\`.`})};for(const u of t.functions??[]){const l={functionName:u.name},d=new Set(u.parameters);for(const f of u.lets)ee(f.value,l,o,d,c),d.add(f.name);ee(u.body,l,o,d,c)}for(const u of t.service.functions??[]){const l={functionName:u.name},d=new Set(u.parameters);for(const f of u.lets)ee(f.value,l,a,d,c),d.add(f.name);ee(u.body,l,a,d,c)}return bl(t.service.match,a,new Set,c),n}const os=1e3,Oa=["get","list","create","update","delete"];function Zr(t,e){return t.operations.some(n=>n===e||n==="read"&&(e==="get"||e==="list")||n==="write"&&(e==="create"||e==="update"||e==="delete"))}const es=new Map;function Ap(t){return t.size===0?"":[...t.entries()].sort(([e],[n])=>e<n?-1:1).map(([e,n])=>`${e}=${n}`).join("|")}function kp(t,e){for(const[n,s]of e){const r=t.get(n);if(r!==void 0&&r!==s)return null}return Jn(t,e)}function Jn(t,e){if(e.size===0)return t;if(t.size===0)return e;const n=new Map(t);for(const[s,r]of e)n.set(s,r);return n}function as(t){switch(t.type){case"identifier":return t.name==="request"||t.name==="resource";case"memberAccess":return as(t.object);case"bracketAccess":return t.index.type==="literal"&&as(t.object);default:return!1}}function Ta(t){return t.type!=="binaryOp"||t.op!=="=="&&t.op!=="!="?null:t.right.type==="literal"&&as(t.left)?{path:se(t.left),literal:Ei(t.right)}:t.left.type==="literal"&&as(t.right)?{path:se(t.right),literal:Ei(t.left)}:null}function Ei(t){const{value:e}=t;return e instanceof Uint8Array?`bytes:${[...e].join(",")}`:`${typeof e}:${String(e)}`}class Ep{fns;memo=new Map;factMemo=new Map;depth=0;constructor(e){this.fns=e}factsOf(e){const n=this.factMemo.get(e);if(n)return n;let s=es;if(e.type==="binaryOp"&&e.op==="&&")s=Jn(this.factsOf(e.left),this.factsOf(e.right));else if(e.type==="binaryOp"&&e.op==="=="){const r=Ta(e);r&&(s=new Map([[r.path,r.literal]]))}else e.type==="functionCall"&&this.fns.has(e.name)&&this.depth<20&&(this.depth++,s=this.factsOf(this.fns.get(e.name).body),this.depth--);return this.factMemo.set(e,s),s}known(e,n){if(e.type==="inExpr"&&e.collection.type==="listLiteral"&&as(e.element)){const o=n.get(se(e.element)),a=e.collection.elements;return o===void 0||!a.every(c=>c.type==="literal")?void 0:a.some(c=>c.type==="literal"&&Ei(c)===o)}const s=Ta(e);if(!s||e.type!=="binaryOp")return;const r=n.get(s.path);if(r===void 0)return;const i=r===s.literal;return e.op==="=="?i:!i}cost(e,n,s){const r=`${n}#${Ap(s)}`;let i=this.memo.get(e);if(i||this.memo.set(e,i=new Map),i.has(r))return i.get(r);const o=this.compute(e,n,s);return i.set(r,o),o}any(e,n){return this.cost(e,"A",n)??0}compute(e,n,s){if(n==="A"&&(Ip(e)||e.type==="unaryOp"&&e.op==="!"))return Un(this.cost(e,"T",s),this.cost(e,"F",s));switch(e.type){case"literal":return typeof e.value=="boolean"&&n!=="A"&&e.value!==(n==="T")?null:1;case"identifier":return 1;case"memberAccess":return 1+this.any(e.object,s);case"methodCall":return 1+this.any(e.object,s)+vn(e.args.map(r=>this.any(r,s)));case"bracketAccess":return 1+this.any(e.object,s)+this.any(e.index,s);case"sliceAccess":return 1+this.any(e.object,s)+this.any(e.start,s)+this.any(e.end,s);case"inExpr":{const r=this.known(e,s);return r!==void 0&&n!=="A"&&r!==(n==="T")?null:1+this.any(e.element,s)+this.any(e.collection,s)}case"isExpr":return 2+this.any(e.value,s);case"listLiteral":return 1+vn(e.elements.map(r=>this.any(r,s)));case"mapLiteral":return 1+vn(e.entries.map(r=>this.any(r.key,s)+this.any(r.value,s)));case"pathLiteral":return 1+vn(e.segments.map(r=>typeof r=="string"?1:this.any(r,s)));case"unaryOp":if(e.op==="!"){const r=this.cost(e.operand,n==="T"?"F":n==="F"?"T":"A",s);return r===null?null:1+r}return 1+this.any(e.operand,s);case"ternary":{const r=(a,c)=>{const u=this.cost(e.condition,a,s);if(u===null)return null;const l=a==="T"?Jn(s,this.factsOf(e.condition)):s,d=this.cost(c,n,l);return d===null?null:u+d},i=r("T",e.consequent),o=r("F",e.alternate);return Un(i===null?null:2+i,o===null?null:4+o)}case"binaryOp":if(e.op==="&&")return this.and(e.left,e.right,n,s);if(e.op==="||")return this.or(e.left,e.right,n,s);{const r=this.known(e,s);return r!==void 0&&n!=="A"&&r!==(n==="T")?null:1+this.any(e.left,s)+this.any(e.right,s)}case"functionCall":{const r=vn(e.args.map(o=>this.any(o,s))),i=this.fns.get(e.name);if(!i||this.depth>=20)return 1+r;this.depth++;try{const o=vn(i.lets.map(c=>1+this.any(c.value,s))),a=this.cost(i.body,n,s);return a===null?null:1+r+o+a}finally{this.depth--}}}}failAtGate(e,n){let s=0,r=e;for(;r.type==="binaryOp"&&r.op==="&&";)s++,r=r.left;const i=this.cost(r,"F",n);return i===null?null:s+i}and(e,n,s,r){const i=this.cost(e,"T",r),o=Jn(r,this.factsOf(e));if(s==="T"){const u=this.cost(n,"T",o);return i===null||u===null?null:2+i+u}const a=this.cost(e,"F",r),c=this.cost(n,"F",o);return Un(a===null?null:1+a,i===null||c===null?null:2+i+c)}or(e,n,s,r){if(s==="F"){const c=this.factsOf(ko(n));if(c.size===0){const h=this.cost(e,"F",r),m=this.cost(n,"F",r);return h===null||m===null?null:2+h+m}const u=this.failAtGate(n,r),l=this.cost(e,"F",r),d=kp(r,c),f=d&&this.cost(e,"F",d),p=d&&this.cost(n,"F",d);return Un(l===null||u===null?null:2+l+u,f===null||p===null||!d?null:2+f+p)}this.cost(e,"F",r);const i=this.cost(e,"T",r),o=this.cost(n,"T",r),a=this.cost(e,"F",Jn(r,this.factsOf(n)));return Un(i===null?null:1+i,a===null||o===null?null:2+a+o)}}function Ip(t){return t.type==="binaryOp"&&(t.op==="&&"||t.op==="||")}function vn(t){let e=0;for(const n of t)e+=n;return e}function Un(...t){let e=null;for(const n of t)n!==null&&(e===null||n>e)&&(e=n);return e}function vl(t){const e=[],n=new Map;for(const r of t.functions??[])n.set(r.name,r);for(const r of t.service.functions??[])n.set(r.name,r);const s=(r,i,o)=>{const a=new Map(o);for(const u of r.functions)a.set(u.name,u);const c=`${i}${r.path.raw}`;e.push({block:r,path:c,fns:a});for(const u of r.children)s(u,c,a)};return s(t.service.match,"",n),e}function _p(t){const e=[],n=[];let s=0;for(const{block:r,path:i,fns:o}of vl(t)){const a=new Ep(o),c=r.allows,u=c.map(()=>s++),l=(d,f)=>a.cost(d.condition,"F",f);c.forEach((d,f)=>{const p=a.cost(d.condition,"T",es),h=a.factsOf(d.condition);let m=null;for(const g of Oa){if(p===null||!Zr(d,g))continue;let b=p;for(let y=0;y<f;y++)Zr(c[y],g)&&(b+=l(c[y],h)??l(c[y],es)??0);m=Math.max(m??0,b)}e.push({ruleIndex:u[f],matchPath:i,blockPath:r.path.raw,blockRuleIndex:f,...d.loc?.line!==void 0?{line:d.loc.line}:{},operations:[...d.operations],grantCost:m})});for(const d of Oa){const f=c.filter(h=>Zr(h,d));if(f.length===0)continue;let p=0;for(const h of xp(a,f)){let m=0;for(const g of f)m+=l(g,h)??l(g,es)??0;p=Math.max(p,m)}n.push({matchPath:i,blockPath:r.path.raw,method:d,denyCost:p})}}return{rules:e,blocks:n}}function xp(t,e){const n=new Map;for(const i of e)for(const[o,a]of t.factsOf(ko(i.condition)))n.has(o)||n.set(o,new Set),n.get(o).add(a);let s;for(const[i,o]of n)(!s||o.size>n.get(s).size)&&(s=i);return s?[...[...n.get(s)],"unmatched"].map(i=>new Map([[s,i]])):[es]}function ko(t){return t.type==="binaryOp"&&t.op==="&&"?ko(t.left):t}function Cp(t){const e=[];let n=0;for(const{block:s,path:r,fns:i}of vl(t))for(const o of s.allows){const a=new Map,c=(u,l)=>{if(u.type==="functionCall"){const d=i.get(u.name);if(d&&(a.set(d,(a.get(d)??0)+1),l<20)){for(const f of d.lets)c(f.value,l+1);c(d.body,l+1)}}for(const d of Op(u))c(d,l)};c(o.condition,0),e.push({ruleIndex:n++,matchPath:r,blockPath:s.path.raw,...o.loc?.line!==void 0?{line:o.loc.line}:{},calls:[...a].map(([u,l])=>({fn:u,count:l}))})}return e}function Op(t){switch(t.type){case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end].filter(e=>!!e);case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args;default:return[]}}const Eo={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],fairness:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],results:["cloud.firestore"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Eo).sort());const Tp={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],fairness:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],results:[],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},Rp=["exists","existsAfter","float","get","getAfter","int","path","string"],Lp=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Np={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},wl={duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Sl=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.name","request.resource.size","request.time","resource","resource.bucket","resource.cacheControl","resource.contentDisposition","resource.contentEncoding","resource.contentLanguage","resource.contentType","resource.crc32c","resource.etag","resource.generation","resource.md5Hash","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Mp=["float","int","path","string"],Dp=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],$p={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},Al={duration:["abs","time","value"],firestore:["exists","get"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Pp=new Set(Sl),jp=["request.auth.token","request.resource.metadata","resource.metadata"];function Fp(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const n=e.join(".");return Pp.has(n)||jp.some(s=>n.startsWith(`${s}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}const qp=new Set(["request","request.resource","resource"]);function Up(t,e){const n=e.join(".");return t==="cloud.firestore"?qp.has(n):cs(t,e)?!1:Sl.some(s=>s.startsWith(`${n}.`))}function cs(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Bp(t,e){if(!e||e==="unknown-ambient")return null;const n=e.join(".");return n==="request"?"request":n==="request.resource"||n==="resource"?"resource":n==="request.auth"||n==="request.auth.token"||t==="cloud.firestore"&&(n==="request.resource.data"||n==="resource.data"||n==="request.query")||n==="request.resource.metadata"||n==="resource.metadata"?"map":n==="request.auth.uid"||n==="request.method"||n==="request.resource.contentType"||n==="resource.contentType"||t==="firebase.storage"&&(n==="request.resource.name"||n==="resource.name"||n==="resource.bucket"||n.startsWith("request.resource.metadata.")||n.startsWith("resource.metadata."))?"string":n==="request.path"?"path":n==="request.time"||n==="resource.timeCreated"||n==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(n)?"number":null}function Ra(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number"}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","keys","removeAll","split","values"].includes(t.method)?"list":["toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const zp=new Set(["exists","existsAfter","get","getAfter"]),Wp=Object.fromEntries(Object.entries(wl).map(([t,e])=>[t,new Set(e)])),Vp=Object.fromEntries(Object.entries(Al).map(([t,e])=>[t,new Set(e)]));function Ii(t,e){return t.some(n=>n==="unknown-ambient"||n!==null&&Up(e.service,n))?"unknown-ambient":null}function Et(t,e){return Ii(t.map(n=>Te(n,e)),e)}function kl(t,e,n){const s=n.declarations?.get(t),r=new Map(s?.aliases),i=new Map(s?.receiverTypes);return t.parameters.forEach((o,a)=>{r.set(o,e[a]?.provenance??null),i.set(o,e[a]?.receiverType??null)}),{aliases:r,receiverTypes:i,functions:s?.functions??n.functions,service:n.service,stack:new Set([...n.stack,t.name]),declarations:n.declarations}}function On(t,e){return{expression:t,provenance:Te(t,e),receiverType:we(t,e)}}function Te(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const n=Te(t.object,e);return n==="unknown-ambient"?n:n?[...n,t.property]:null}if(t.type==="bracketAccess"){const n=Te(t.object,e);return!n||n==="unknown-ambient"?n:t.index.type==="literal"&&typeof t.index.value=="string"?[...n,t.index.value]:[...n,"*"]}if(t.type==="ternary"){const n=Te(t.consequent,e),s=Te(t.alternate,e);return!n&&!s?null:Array.isArray(n)&&Array.isArray(s)&&n.join(".")===s.join(".")?n:Ii([n,s],e)}if(t.type==="functionCall"){const n=e.functions.get(t.name),s=t.args.map(i=>On(i,e));if(!n&&zp.has(t.name))return null;if(!n||e.stack.has(n.name))return Ii(s.map(({provenance:i})=>i),e);const r=kl(n,s,e);for(const i of n.lets){const o=On(i.value,r);r.aliases.set(i.name,o.provenance),r.receiverTypes.set(i.name,o.receiverType)}return Te(n.body,r)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return Et([t.object,...t.args],e);case"sliceAccess":return Et([t.object,t.start,t.end],e);case"binaryOp":return Et([t.left,t.right],e);case"unaryOp":return Et([t.operand],e);case"inExpr":return Et([t.element,t.collection],e);case"isExpr":return Et([t.value],e);case"listLiteral":return Et(t.elements,e);case"mapLiteral":return Et(t.entries.flatMap(({key:n,value:s})=>[n,s]),e);case"pathLiteral":return Et(t.segments.filter(n=>typeof n!="string"),e);default:return null}}function we(t,e){const n=Bp(e.service,Te(t,e));if(n)return n;switch(t.type){case"identifier":{const s=e.receiverTypes.get(t.name);return s||((e.service==="cloud.firestore"?Wp:Vp)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":t.value instanceof Uint8Array?"bytes":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const s=we(t.object,e);if(s==="mixed")return"mixed";if(t.property==="data"&&s==="document")return"map";if(t.object.type==="mapLiteral"){const r=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return r?we(r.value,e):null}return null}case"bracketAccess":{const s=we(t.object,e);if(s==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?we(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,o=t.object.entries.find(({key:a})=>a.type==="literal"&&a.value===i);return o?we(o.value,e):null}if(s==="string")return"string";const r=Te(t.object,e);return e.service==="firebase.storage"&&Array.isArray(r)&&(r.join(".")==="request.resource.metadata"||r.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const s=we(t.object,e);return s==="mixed"?"mixed":s==="list"||s==="string"?s:null}case"methodCall":{const s=Ra(t);if(t.object.type==="identifier"&&s)return s;if(t.method==="get"){const r=Te(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(r)&&(r.join(".")==="request.resource.metadata"||r.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const o=t.args[0].value,a=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===o);return a?we(a.value,e):i?we(i,e):null}return i&&we(i,e)?"mixed":null}return Ra(t)}case"binaryOp":{const s=we(t.left,e),r=we(t.right,e);return t.op==="+"&&(s==="string"||r==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&s==="number"&&r==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&we(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const s=we(t.consequent,e),r=we(t.alternate,e);return!s&&!r?null:s===r?s:"mixed"}case"functionCall":{const s=e.functions.get(t.name);if(!s&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean";if(t.name==="string")return"string";if(t.name==="int"||t.name==="float")return"number";if(t.name==="path")return"path"}if(!s||e.stack.has(s.name))return null;const r=kl(s,t.args.map(i=>On(i,e)),e);for(const i of s.lets){const o=On(i.value,r);r.aliases.set(i.name,o.provenance),r.receiverTypes.set(i.name,o.receiverType)}return we(s.body,r)}default:return null}}function Gp(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Hp(t,e,n){const s=Gp(e),r=Eo[s];return r?r.includes(t)?null:`Function '${n}' from module '${e}' is not compatible with service '${t}'`:null}function Kp(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Zp=new Set(Rp),Jp=new Set(Lp),Qp=Object.fromEntries(Object.entries(wl).map(([t,e])=>[t,new Set(e)])),Yp=new Set(Mp),Xp=new Set(Dp),em=Object.fromEntries(Object.entries(Al).map(([t,e])=>[t,new Set(e)]));function Zs(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Fp(e,t)?`binding '${t.join(".")}'`:null}function tm(t,e,n,s,r){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=Te(t,r);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const o=n[0];if(o?.type==="literal"&&typeof o.value=="string")return Zs([...i,o.value],s);if(!cs(s,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!cs(s,i)?`binding '${i.join(".")}.${e}()'`:null}function nm(t,e,n,s){const r=we(t,s);if(!r||r==="unknown"||r==="mixed")return null;const o=(n==="cloud.firestore"?Np:$p)[e];return o?.includes(r)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${r}`}function sm(t,e,n,s){const r=Te(e,s);return r==="unknown-ambient"?"binding '<derived ambient value>'":r?t.type==="literal"&&typeof t.value=="string"?Zs([...r,t.value],n):cs(n,r)?null:`binding '<value> in ${r.join(".")}'`:null}function La(t,e,n){const s=r=>{switch(r.type){case"memberAccess":{const i=Zs(Te(r,n),e);return i||s(r.object)}case"functionCall":{const i=n.functions.get(r.name);if(!i&&!(e==="cloud.firestore"?Zp:Yp).has(r.name))return`function '${r.name}()'`;for(const a of r.args){const c=s(a);if(c)return c}if(i&&!n.stack.has(i.name)){const a=new Map,c=new Map;i.parameters.forEach((l,d)=>{const f=r.args[d];a.set(l,f?Te(f,n):null),c.set(l,f?we(f,n):null)});const u=El(i,e,{aliases:a,receiverTypes:c,functions:n.functions,service:e,stack:new Set([...n.stack,i.name])});if(u)return u}return null}case"methodCall":{if(r.object.type==="identifier"&&!n.aliases.has(r.object.name)){const u=(e==="cloud.firestore"?Qp:em)[r.object.name];if(u){if(!u.has(r.method))return`method '${r.object.name}.${r.method}()'`;for(const l of r.args){const d=s(l);if(d)return d}return null}return r.object.name==="firestore"?`method 'firestore.${r.method}()'`:`namespace '${r.object.name}'`}if(!(e==="cloud.firestore"?Jp:Xp).has(r.method))return`method '.${r.method}()'`;const o=nm(r.object,r.method,e,n);if(o)return o;const a=tm(r.object,r.method,r.args,e,n);return a||(s(r.object)??r.args.map(s).find(Boolean)??null)}case"binaryOp":return s(r.left)??s(r.right);case"unaryOp":return s(r.operand);case"bracketAccess":{const i=Te(r.object,n);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const o=r.index.type==="literal"&&typeof r.index.value=="string";if(i&&!o)return cs(e,i)?s(r.object)??s(r.index):`binding '${i.join(".")}[...]'`;const a=Zs(Te(r,n),e);return a||(s(r.object)??s(r.index))}case"sliceAccess":return s(r.object)??s(r.start)??s(r.end);case"ternary":return s(r.condition)??s(r.consequent)??s(r.alternate);case"inExpr":return sm(r.element,r.collection,e,n)??s(r.element)??s(r.collection);case"isExpr":return s(r.value);case"listLiteral":return r.elements.map(s).find(Boolean)??null;case"mapLiteral":for(const i of r.entries){const o=s(i.key)??s(i.value);if(o)return o}return null;case"pathLiteral":for(const i of r.segments)if(typeof i!="string"){const o=s(i);if(o)return o}return null;case"literal":return null;case"identifier":return r.name==="request"||r.name==="resource"||n.aliases.has(r.name)?null:`identifier '${r.name}'`;default:return Kp(r)}};return s(t)}function El(t,e,n){const s=new Map(n.aliases),r=new Map(n.receiverTypes),i={...n,aliases:s,receiverTypes:r};for(const o of t.lets){const a=La(o.value,e,i);if(a)return a;s.set(o.name,Te(o.value,i)),r.set(o.name,we(o.value,i))}return La(t.body,e,i)}function rm(t,e,n=new Map([[t.name,t]]),s=[]){const r={aliases:new Map,receiverTypes:new Map,functions:n,service:e,stack:new Set([t.name])};return El(t,e,{aliases:new Map(t.parameters.map((i,o)=>[i,o<s.length?s[o]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,o)=>[i,s[o]?we(s[o].expression,r)??s[o].receiverType??null:null])),functions:n,service:e,stack:new Set([t.name])})}function im(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function om(t){const e=t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[^A-Za-z0-9_]/g,"_");return e.length===0||/^[0-9]/.test(e)?`_${e}`:e}function Qe(t,e){if(t!==e){const n=ks(t);for(let s=0;s<n;s++)fo(e)}return e}function de(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,s=t.args.map(r=>de(r,e));return Qe(t,n===t.name&&s.every((r,i)=>r===t.args[i])?t:{...t,name:n,args:s})}case"binaryOp":{const n=de(t.left,e),s=de(t.right,e);return Qe(t,n===t.left&&s===t.right?t:{...t,left:n,right:s})}case"unaryOp":{const n=de(t.operand,e);return Qe(t,n===t.operand?t:{...t,operand:n})}case"methodCall":{const n=de(t.object,e),s=t.args.map(r=>de(r,e));return Qe(t,n===t.object&&s.every((r,i)=>r===t.args[i])?t:{...t,object:n,args:s})}case"memberAccess":{const n=de(t.object,e);return Qe(t,n===t.object?t:{...t,object:n})}case"bracketAccess":{const n=de(t.object,e),s=de(t.index,e);return Qe(t,n===t.object&&s===t.index?t:{...t,object:n,index:s})}case"sliceAccess":{const n=de(t.object,e),s=de(t.start,e),r=de(t.end,e);return Qe(t,n===t.object&&s===t.start&&r===t.end?t:{...t,object:n,start:s,end:r})}case"ternary":{const n=de(t.condition,e),s=de(t.consequent,e),r=de(t.alternate,e);return Qe(t,n===t.condition&&s===t.consequent&&r===t.alternate?t:{...t,condition:n,consequent:s,alternate:r})}case"inExpr":{const n=de(t.element,e),s=de(t.collection,e);return Qe(t,n===t.element&&s===t.collection?t:{...t,element:n,collection:s})}case"isExpr":{const n=de(t.value,e);return Qe(t,n===t.value?t:{...t,value:n})}case"listLiteral":{const n=t.elements.map(s=>de(s,e));return Qe(t,n.every((s,r)=>s===t.elements[r])?t:{...t,elements:n})}case"mapLiteral":{const n=t.entries.map(s=>{const r=de(s.key,e),i=de(s.value,e);return r===s.key&&i===s.value?s:{key:r,value:i}});return Qe(t,n.every((s,r)=>s===t.entries[r])?t:{...t,entries:n})}case"pathLiteral":{const n=t.segments.map(s=>typeof s=="string"?s:de(s,e));return Qe(t,n.every((s,r)=>s===t.segments[r])?t:{...t,segments:n})}case"literal":case"identifier":return t;default:return im(t)}}function am(t,e){const n=om(e),s=new Map;for(const r of t)r.exported||s.set(r.name,`${n}__${r.name}`);return s.size===0?t:t.map(r=>{const i=de(r.body,s),o=r.lets.map(c=>{const u=de(c.value,s);return u===c.value?c:{...c,value:u}}),a=r.exported?r.name:s.get(r.name)??r.name;return i===r.body&&o===r.lets&&a===r.name?r:{...r,name:a,body:i,lets:o}})}function cm(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Io(t){const e=[],n=s=>{switch(s.type){case"functionCall":e.push(s),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"sliceAccess":n(s.object),n(s.start),n(s.end);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(({key:r,value:i})=>{n(r),n(i)});break;case"pathLiteral":s.segments.forEach(r=>{typeof r!="string"&&n(r)});break;case"literal":case"identifier":break;default:cm(s)}};return n(t),e}function um(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function lm(t,e,n=new Map){const s=[],r=new Map,i=new Set,o=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",a=(h,m=new Set)=>({aliases:new Map(h.aliases),receiverTypes:new Map(h.receiverTypes),functions:h.functions,service:o,stack:m,declarations:r}),c=(h,m,g)=>{if(g.has(h.name))return;const b=r.get(h);if(!b)return;i.add(h);const y=new Map(b.aliases),w=new Map(b.receiverTypes);h.parameters.forEach((E,I)=>{y.set(E,m[I]?.provenance??null),w.set(E,m[I]?.receiverType??null)});const v=a({aliases:y,receiverTypes:w,functions:b.functions},new Set([...g,h.name]));for(const E of h.lets){u(E.value,v);const I=On(E.value,v);v.aliases.set(E.name,I.provenance),v.receiverTypes.set(E.name,I.receiverType)}u(h.body,v)},u=(h,m)=>{for(const g of Io(h)){const b=g.args.map(w=>On(w,m));g.name===e&&s.push({arguments:b.map(um)});const y=m.functions.get(g.name);y&&!n.has(g.name)&&c(y,b,m.stack)}},l=new Map((t.functions??[]).map(h=>[h.name,h])),d=new Map([...l,...n]);for(const h of t.service.functions??[])d.set(h.name,h);for(const h of n.values())r.set(h,{aliases:new Map,receiverTypes:new Map,functions:n});const f=[];for(const h of t.functions??[])r.set(h,{aliases:new Map,receiverTypes:new Map,functions:l}),f.push(h);for(const h of t.service.functions??[])r.set(h,{aliases:new Map,receiverTypes:new Map,functions:d}),f.push(h);const p=(h,m)=>{const g=new Map(m.receiverTypes);for(const v of h.path.segments)v.type==="wildcard"&&g.set(v.name,"string"),v.type==="recursive"&&g.set(v.name,"path");const b=new Map(m.functions),y={aliases:m.aliases,receiverTypes:g,functions:b};for(const v of h.functions)b.set(v.name,v),r.set(v,y),f.push(v);const w=a(y);for(const{condition:v}of h.allows)u(v,w);h.children.forEach(v=>p(v,y))};p(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:d});for(const h of f)i.has(h)||c(h,[],new Set);return s}function Bn(t){return Io(t).map(({name:e})=>e)}function dm(t,e){return[...t.values()].flatMap(s=>[...s.lets.map(({value:r})=>r),s.body]).flatMap(Io).filter(({name:s})=>s===e).map(({args:s})=>s)}const fm=/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)/,hm=/^rules_version\s*=\s*(['"])([^'"]*)\1\s*;/,pm=/^import\s*\{([^}]*)\}\s*from\s*(['"])([^'"]+)\2\s*;/,mm=/^\s*(?:import\s*\{|rules_version\b)/m;function Na(t){return t.replace(/[^\n]/g," ")}function gm(t,e){const n=[];let s=t,r=0;for(;;){const i=t.slice(r),o=fm.exec(i);if(o){r+=o[0].length;continue}const a=hm.exec(i);if(a){if(a[2]!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Module '${e}' declares rules_version '${a[2]}'; a module's version is '2+modules'`}};s=s.slice(0,r)+Na(a[0])+s.slice(r+a[0].length),r+=a[0].length;continue}const c=pm.exec(i);if(c){const u=c[1].split(",").map(l=>l.trim()).filter(l=>l!=="");n.push({module:c[3],functions:u}),s=s.slice(0,r)+Na(c[0])+s.slice(r+c[0].length),r+=c[0].length;continue}return{success:!0,body:s,imports:n}}}function Ma(t,e,n){const s=gm(t,e);if(!s.success)return s;const r=Th(s.body,e);return r===null?{success:!1,error:{code:"PARSE_FAILED",message:mm.test(s.body)?`Failed to parse module '${e}': a module puts rules_version and imports before its first function`:`Failed to parse module '${e}'`}}:{success:!0,functions:r,imports:s.imports,bundled:n}}function ym(t,e){if(t===null||!us(e)||!us(t))return e;const n=[];for(const r of[...t.split("/").slice(0,-1),...e.split("/")]){if(r==="."||r==="")continue;const i=n.length>0&&n[n.length-1]!=="..";r===".."&&i?n.pop():n.push(r)}const s=n.join("/");return s.startsWith("..")?s:`./${s}`}function us(t){return t.startsWith("./")||t.startsWith("../")}function ls(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)(?:\.rules)?$/.exec(t)?.[1]??null}function Da(t,e,n,s=new Set){return n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e)?s.has(e)?ls(e)??e:e:(us(e)&&n?.basePath,ls(e)??e)}function bm(t,e,n,s=new Set){if(n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e))return Ma(n.modules[e],e,s.has(e));if(us(e)&&n?.basePath){const i=`${n.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!ls(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}const r=ls(e);return r?n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,r)?Ma(n.modules[r],e,s.has(r)):{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:us(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function vm(t,e,n,s=new Set){const r=Es(e);if(!r.ok){const{line:A,column:M,message:ue}=r.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${A}, col ${M}: ${ue}`}}}const i=r.ast,o=i.version==="2+modules",a=i.service.name==="firebase.storage";let c=a?"storage.rules":"firestore.rules";if(o&&(c=a?"storage.modules.rules":"firestore.modules.rules"),n!==void 0&&n.sourceFile!==void 0&&n.sourceFile!==""&&(c=n.sourceFile),wm(i,c),o===!1)return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name==="cloud.firestore"===!1&&i.service.name==="firebase.storage"===!1)return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};const d=new Set([...(i.functions??[]).map(A=>A.name),...(i.service.functions??[]).map(A=>A.name)]),f=A=>{A.functions.forEach(M=>d.add(M.name)),A.children.forEach(f)};f(i.service.match);const p=[...d].find(A=>Kr.has(A));if(p)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${p}' conflicts with a Rules builtin`}};if(i.imports.length===0){i.version="2";const A=Ia(i),M=JSON.stringify(A.sourceMap);return{success:!0,data:{resolved:`${A.resolved}// @pyric-source-map: ${M}
|
|
514
|
-
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:A.sourceMap}}}const m=i.imports.find(A=>A.functions.length===0);if(m)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${m.module}' must request at least one function`}};const g=new Map,b=new Map,y=new Map,w=new Map,v=[],E=[],I=new Map,j=new Map,W=new Map,V=new Map,T=new Map,N=i.imports.map(A=>({module:A.module,functions:A.functions,importer:null}));for(let A=N.shift();A!==void 0;A=N.shift()){const M=Da(t,A.module,n,s);if(!j.has(M)){const q=
|
|
515
|
-
`,modules:v,bundledModules:E,evidenceIds:[...jt].sort(),sourceMap:Os.sourceMap}}}function
|
|
516
|
-
`,r);let o="";i!==-1?o=t.slice(r,i).trim():o=t.slice(r).trim();try{const c=JSON.parse(o);if(Array.isArray(c))for(const l of c)!e.has(l.generatedLine)&&e.set(l.generatedLine,l)}catch{}return e}function
|
|
513
|
+
`;)t[n]==="\\"&&n+1<t.length?(e+=" ",n+=2):(e+=" ",n++);n<t.length&&t[n]===i&&(e+=i,n++)}else e+=s,n++}return e}function qt(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=qt(t.left),n=qt(t.right);if(t.op==="&&")return e===!1||n===!1?!1:e===!0&&n===!0?!0:null;if(t.op==="||")return e===!0||n===!0?!0:e===!1&&n===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=qt(t.operand);return e===null?null:!e}if(t.type==="ternary"){const e=qt(t.condition);return e===!0?qt(t.consequent):e===!1?qt(t.alternate):null}return null}function pe(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${pe(t.object)}.${t.property}`;case"methodCall":return`${pe(t.object)}.${t.method}(${t.args.map(pe).join(",")})`;case"bracketAccess":return`${pe(t.object)}[${pe(t.index)}]`;case"sliceAccess":return`${pe(t.object)}[${pe(t.start)}:${pe(t.end)}]`;case"binaryOp":return`(${pe(t.left)}${t.op}${pe(t.right)})`;case"unaryOp":return`(${t.op}${pe(t.operand)})`;case"ternary":return`(${pe(t.condition)}?${pe(t.consequent)}:${pe(t.alternate)})`;case"inExpr":return`(${pe(t.element)} in ${pe(t.collection)})`;case"isExpr":return`(${pe(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(pe).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${pe(e.key)}:${pe(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(pe).join(",")})`}}function Ks(t){return t.type==="binaryOp"&&t.op==="&&"?[...Ks(t.left),...Ks(t.right)]:[t]}const ki={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},xt={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use direct comparison or validation instead of boolean casting",bool:"No `bool()` cast in rules — boolean casting is not supported in production Firestore rules.",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},ap=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),cp=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)",storageSuggestion:"Use `request.resource` (e.g. `request.resource.size`, `request.resource.contentType`, or `request.resource.metadata`)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"request.auth",property:"id",suggestion:"Use `request.auth.uid`"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)",storageSuggestion:"Use `resource != null` (or `firestore.exists()` for cross-service document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"},{receiver:"resource",property:"data",suggestion:"`resource.data` does not exist in Storage rules — use `resource.size`, `resource.contentType`, or `resource.metadata`",storageOnly:!0},{receiver:"request.resource",property:"data",suggestion:"`request.resource.data` does not exist in Storage rules — use `request.resource.size`, `request.resource.contentType`, or `request.resource.metadata`",storageOnly:!0},{receiver:"resource",property:"timeUpdated",suggestion:"Use `resource.updated` instead of `resource.timeUpdated`",storageOnly:!0},{receiver:"request.resource",property:"timeUpdated",suggestion:"Use `request.resource.updated` instead of `request.resource.timeUpdated`",storageOnly:!0}],up=new Set(["email_verified"]),lp=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),dp=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function fp(t){const e=[],n=op(t);for(const s of dp)s.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:s.message});return e}function bl(t,e,n,s){const r=t.path.raw,i=new Set(e);for(const a of t.functions)i.add(a.name);const o=new Set(n);for(const a of t.path.segments)a.type!=="literal"&&o.add(a.name);for(const a of t.functions){const c={matchPath:r,functionName:a.name},u=new Set([...o,...a.parameters]);for(const l of a.lets)ee(l.value,c,i,u,s),u.add(l.name);ee(a.body,c,i,u,s)}for(let a=0;a<t.allows.length;a++)ee(t.allows[a].condition,{matchPath:r,ruleIndex:a},i,o,s);for(const a of t.children)bl(a,i,o,s)}function ee(t,e,n,s,r){switch(r(t,e,n,s),t.type){case"binaryOp":ee(t.left,e,n,s,r),ee(t.right,e,n,s,r);break;case"unaryOp":ee(t.operand,e,n,s,r);break;case"methodCall":ee(t.object,e,n,s,r),t.args.forEach(i=>ee(i,e,n,s,r));break;case"memberAccess":ee(t.object,e,n,s,r);break;case"bracketAccess":ee(t.object,e,n,s,r),ee(t.index,e,n,s,r);break;case"sliceAccess":ee(t.object,e,n,s,r),ee(t.start,e,n,s,r),ee(t.end,e,n,s,r);break;case"ternary":ee(t.condition,e,n,s,r),ee(t.consequent,e,n,s,r),ee(t.alternate,e,n,s,r);break;case"inExpr":ee(t.element,e,n,s,r),ee(t.collection,e,n,s,r);break;case"isExpr":ee(t.value,e,n,s,r);break;case"listLiteral":t.elements.forEach(i=>ee(i,e,n,s,r));break;case"mapLiteral":t.entries.forEach(i=>{ee(i.key,e,n,s,r),ee(i.value,e,n,s,r)});break;case"functionCall":t.args.forEach(i=>ee(i,e,n,s,r));break;case"pathLiteral":t.segments.forEach(i=>{typeof i!="string"&&ee(i,e,n,s,r)});break}}function hp(t,e,n){return n?!1:t.type==="functionCall"&&t.name==="debug"&&!e.has("debug")}function pp(t){return t.type==="methodCall"&&Object.hasOwn(ki,t.method)}function mp(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!ap.has(t.method)}function gp(t){return t.type!=="methodCall"||t.method!=="hasAll"&&t.method!=="hasAny"&&t.method!=="hasOnly"?!1:t.object.type==="mapLiteral"||t.object.type==="memberAccess"&&t.object.property==="data"}function yp(t,e){return t.type!=="methodCall"||t.object.type!=="identifier"||e.has(t.object.name)?!1:Object.hasOwn(xt,t.object.name)}function bp(t,e){return t.type!=="functionCall"||e.has(t.name)?!1:Object.hasOwn(xt,t.name)}function vp(t,e){return t.type!=="identifier"||e.has(t.name)?!1:Object.hasOwn(xt,t.name)}function wp(t,e=!1){if(t.type!=="memberAccess")return;let n;if(t.object.type==="identifier"?n=t.object.name:t.object.type==="memberAccess"&&t.object.object.type==="identifier"&&(n=`${t.object.object.name}.${t.object.property}`),!n)return;const s=t.property,r=cp.find(i=>i.receiver===n&&i.property===s&&(!i.storageOnly||e));if(r)return{path:`${n}.${s}`,suggestion:e&&r.storageSuggestion?r.storageSuggestion:r.suggestion}}function Sp(t){if(t.type!=="memberAccess"||!up.has(t.property))return;const e=t.object;if(e.type!=="memberAccess"||e.property!=="token")return;const n=e.object;if(!(n.type!=="memberAccess"||n.property!=="auth"))return n.object.type==="identifier"&&n.object.name==="request"?t.property:void 0}function Ap(t){if(!(t.type!=="binaryOp"||t.op!=="=="&&t.op!=="!="))for(const[e,n]of[[t.left,t.right],[t.right,t.left]]){const s=Sp(e);if(s&&n.type==="literal"&&typeof n.value=="string")return{claim:s,op:t.op,literal:n.value}}}function kp(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function Ep(t,e=!1){if(t.type!=="memberAccess"||!lp.has(t.property))return!1;if(e&&t.property==="size"){const s=t.object.type==="identifier"&&t.object.name==="resource",r=t.object.type==="memberAccess"&&t.object.property==="resource"&&t.object.object.type==="identifier"&&t.object.object.name==="request";if(s||r)return!1}return t.object.type==="identifier"&&(t.object.name==="request"||t.object.name==="resource")||t.object.type==="memberAccess"||t.object.type==="methodCall"||t.object.type==="bracketAccess"}function Ip(t,e={}){const n=[],s=new Set,r=t.service?.name==="firebase.storage";function i(u,l,d,f){const p=`${u}|${l}|${d.matchPath||""}|${d.functionName||""}|${d.ruleIndex??""}`;s.has(p)||(s.add(p),n.push(f))}const o=new Set;for(const u of t.imports??[]){const l=u.functions??u.names??[];for(const d of l)o.add(d)}for(const u of t.functions??[])o.add(u.name);const a=new Set(o);for(const u of t.service.functions??[])a.add(u.name);const c=(u,l,d,f)=>{if(hp(u,d,e.allowDebug)&&i("HALLUCINATED_GLOBAL","debug",l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:"`debug()` is not a Firestore rules function and no function named `debug` is declared in scope. Production rejects the whole ruleset at compile time with `Function not found error: Name: [debug]`, so nothing in the file deploys.",location:l,fix:"Remove the debug() call and evaluate the inner expression directly."}),pp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",u.method,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${u.method}()\` does not exist in Firestore rules. ${ki[u.method]}`,location:l,fix:ki[u.method]}),mp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",`math.${u.method}`,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${u.method}()\` does not exist in production Firestore security rules.`,location:l,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),gp(u)&&u.type==="methodCall"&&i("HALLUCINATED_METHOD",`map.${u.method}`,l,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${u.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:l,fix:`Insert \`.keys()\`: e.g. \`data.keys().${u.method}(...)\`.`}),yp(u,f)&&u.type==="methodCall"&&u.object.type==="identifier"){const m=u.object.name;i("HALLUCINATED_GLOBAL",`${m}.${u.method}`,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${m}.${u.method}()\` does not exist in Firestore rules. ${xt[m]}`,location:l,fix:xt[m]})}bp(u,d)&&u.type==="functionCall"&&i("HALLUCINATED_GLOBAL",u.name,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${u.name}()\` does not exist in Firestore rules. ${xt[u.name]}`,location:l,fix:xt[u.name]}),vp(u,f)&&u.type==="identifier"&&i("HALLUCINATED_GLOBAL",`ref:${u.name}`,l,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${u.name}\` is not a Firestore rules identifier. ${xt[u.name]}`,location:l,fix:xt[u.name]});const p=wp(u,r);p&&i("WRONG_CONTEXT_PATH",p.path,l,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${p.path}\` is not a valid ${r?"Storage":"Firestore"} rules path. ${p.suggestion}`,location:l,fix:p.suggestion});const h=Ap(u);if(h){const{claim:m,op:g,literal:b}=h;i("BOOL_TOKEN_CLAIM",`${m}|${g}|${b}`,l,{rule:"BOOL_TOKEN_CLAIM",severity:"error",message:`\`request.auth.token.${m}\` is a bool, but it is compared against the string "${b}", a cross-type comparison that is always ${g==="=="?"false (rule always denies)":"true (rule silently allows)"}. Compare against the boolean literal instead: \`request.auth.token.${m} ${g} true\`.`,location:l,fix:`Drop the quotes: \`request.auth.token.${m} ${g} ${b==="false"?"false":"true"}\`.`})}if(kp(u)&&i("LENGTH_PROPERTY","",l,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:l,fix:"Replace `.length` with `.size()`."}),u.type==="pathLiteral")for(const m of u.segments){if(typeof m!="string")continue;const g=m.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!g)continue;const b=g[1];i("INVALID_PATH_INTERPOLATION",`${u.raw}|${b}`,l,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${b}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${b}}\` with \`$(${b})\` in path \`${u.raw}\`.`,location:l,fix:`Replace \`{${b}}\` with \`$(${b})\` inside the path argument.`})}Ep(u,r)&&u.type==="memberAccess"&&i("METHOD_MISSING_PARENS",u.property,l,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${u.property}\` looks like a built-in method called without parentheses. Use \`.${u.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:l,fix:`Add parentheses: \`.${u.property}()\`.`})};for(const u of t.functions??[]){const l={functionName:u.name},d=new Set(u.parameters);for(const f of u.lets)ee(f.value,l,o,d,c),d.add(f.name);ee(u.body,l,o,d,c)}for(const u of t.service.functions??[]){const l={functionName:u.name},d=new Set(u.parameters);for(const f of u.lets)ee(f.value,l,a,d,c),d.add(f.name);ee(u.body,l,a,d,c)}return bl(t.service.match,a,new Set,c),n}const os=1e3,Oa=["get","list","create","update","delete"];function Zr(t,e){return t.operations.some(n=>n===e||n==="read"&&(e==="get"||e==="list")||n==="write"&&(e==="create"||e==="update"||e==="delete"))}const es=new Map;function _p(t){return t.size===0?"":[...t.entries()].sort(([e],[n])=>e<n?-1:1).map(([e,n])=>`${e}=${n}`).join("|")}function xp(t,e){for(const[n,s]of e){const r=t.get(n);if(r!==void 0&&r!==s)return null}return Jn(t,e)}function Jn(t,e){if(e.size===0)return t;if(t.size===0)return e;const n=new Map(t);for(const[s,r]of e)n.set(s,r);return n}function as(t){switch(t.type){case"identifier":return t.name==="request"||t.name==="resource";case"memberAccess":return as(t.object);case"bracketAccess":return t.index.type==="literal"&&as(t.object);default:return!1}}function Ta(t){return t.type!=="binaryOp"||t.op!=="=="&&t.op!=="!="?null:t.right.type==="literal"&&as(t.left)?{path:se(t.left),literal:Ei(t.right)}:t.left.type==="literal"&&as(t.right)?{path:se(t.right),literal:Ei(t.left)}:null}function Ei(t){const{value:e}=t;return e instanceof Uint8Array?`bytes:${[...e].join(",")}`:`${typeof e}:${String(e)}`}class Cp{fns;memo=new Map;factMemo=new Map;depth=0;constructor(e){this.fns=e}factsOf(e){const n=this.factMemo.get(e);if(n)return n;let s=es;if(e.type==="binaryOp"&&e.op==="&&")s=Jn(this.factsOf(e.left),this.factsOf(e.right));else if(e.type==="binaryOp"&&e.op==="=="){const r=Ta(e);r&&(s=new Map([[r.path,r.literal]]))}else e.type==="functionCall"&&this.fns.has(e.name)&&this.depth<20&&(this.depth++,s=this.factsOf(this.fns.get(e.name).body),this.depth--);return this.factMemo.set(e,s),s}known(e,n){if(e.type==="inExpr"&&e.collection.type==="listLiteral"&&as(e.element)){const o=n.get(se(e.element)),a=e.collection.elements;return o===void 0||!a.every(c=>c.type==="literal")?void 0:a.some(c=>c.type==="literal"&&Ei(c)===o)}const s=Ta(e);if(!s||e.type!=="binaryOp")return;const r=n.get(s.path);if(r===void 0)return;const i=r===s.literal;return e.op==="=="?i:!i}cost(e,n,s){const r=`${n}#${_p(s)}`;let i=this.memo.get(e);if(i||this.memo.set(e,i=new Map),i.has(r))return i.get(r);const o=this.compute(e,n,s);return i.set(r,o),o}any(e,n){return this.cost(e,"A",n)??0}compute(e,n,s){if(n==="A"&&(Op(e)||e.type==="unaryOp"&&e.op==="!"))return Un(this.cost(e,"T",s),this.cost(e,"F",s));switch(e.type){case"literal":return typeof e.value=="boolean"&&n!=="A"&&e.value!==(n==="T")?null:1;case"identifier":return 1;case"memberAccess":return 1+this.any(e.object,s);case"methodCall":return 1+this.any(e.object,s)+vn(e.args.map(r=>this.any(r,s)));case"bracketAccess":return 1+this.any(e.object,s)+this.any(e.index,s);case"sliceAccess":return 1+this.any(e.object,s)+this.any(e.start,s)+this.any(e.end,s);case"inExpr":{const r=this.known(e,s);return r!==void 0&&n!=="A"&&r!==(n==="T")?null:1+this.any(e.element,s)+this.any(e.collection,s)}case"isExpr":return 2+this.any(e.value,s);case"listLiteral":return 1+vn(e.elements.map(r=>this.any(r,s)));case"mapLiteral":return 1+vn(e.entries.map(r=>this.any(r.key,s)+this.any(r.value,s)));case"pathLiteral":return 1+vn(e.segments.map(r=>typeof r=="string"?1:this.any(r,s)));case"unaryOp":if(e.op==="!"){const r=this.cost(e.operand,n==="T"?"F":n==="F"?"T":"A",s);return r===null?null:1+r}return 1+this.any(e.operand,s);case"ternary":{const r=(a,c)=>{const u=this.cost(e.condition,a,s);if(u===null)return null;const l=a==="T"?Jn(s,this.factsOf(e.condition)):s,d=this.cost(c,n,l);return d===null?null:u+d},i=r("T",e.consequent),o=r("F",e.alternate);return Un(i===null?null:2+i,o===null?null:4+o)}case"binaryOp":if(e.op==="&&")return this.and(e.left,e.right,n,s);if(e.op==="||")return this.or(e.left,e.right,n,s);{const r=this.known(e,s);return r!==void 0&&n!=="A"&&r!==(n==="T")?null:1+this.any(e.left,s)+this.any(e.right,s)}case"functionCall":{const r=vn(e.args.map(o=>this.any(o,s))),i=this.fns.get(e.name);if(!i||this.depth>=20)return 1+r;this.depth++;try{const o=vn(i.lets.map(c=>1+this.any(c.value,s))),a=this.cost(i.body,n,s);return a===null?null:1+r+o+a}finally{this.depth--}}}}failAtGate(e,n){let s=0,r=e;for(;r.type==="binaryOp"&&r.op==="&&";)s++,r=r.left;const i=this.cost(r,"F",n);return i===null?null:s+i}and(e,n,s,r){const i=this.cost(e,"T",r),o=Jn(r,this.factsOf(e));if(s==="T"){const u=this.cost(n,"T",o);return i===null||u===null?null:2+i+u}const a=this.cost(e,"F",r),c=this.cost(n,"F",o);return Un(a===null?null:1+a,i===null||c===null?null:2+i+c)}or(e,n,s,r){if(s==="F"){const c=this.factsOf(ko(n));if(c.size===0){const h=this.cost(e,"F",r),m=this.cost(n,"F",r);return h===null||m===null?null:2+h+m}const u=this.failAtGate(n,r),l=this.cost(e,"F",r),d=xp(r,c),f=d&&this.cost(e,"F",d),p=d&&this.cost(n,"F",d);return Un(l===null||u===null?null:2+l+u,f===null||p===null||!d?null:2+f+p)}this.cost(e,"F",r);const i=this.cost(e,"T",r),o=this.cost(n,"T",r),a=this.cost(e,"F",Jn(r,this.factsOf(n)));return Un(i===null?null:1+i,a===null||o===null?null:2+a+o)}}function Op(t){return t.type==="binaryOp"&&(t.op==="&&"||t.op==="||")}function vn(t){let e=0;for(const n of t)e+=n;return e}function Un(...t){let e=null;for(const n of t)n!==null&&(e===null||n>e)&&(e=n);return e}function vl(t){const e=[],n=new Map;for(const r of t.functions??[])n.set(r.name,r);for(const r of t.service.functions??[])n.set(r.name,r);const s=(r,i,o)=>{const a=new Map(o);for(const u of r.functions)a.set(u.name,u);const c=`${i}${r.path.raw}`;e.push({block:r,path:c,fns:a});for(const u of r.children)s(u,c,a)};return s(t.service.match,"",n),e}function Tp(t){const e=[],n=[];let s=0;for(const{block:r,path:i,fns:o}of vl(t)){const a=new Cp(o),c=r.allows,u=c.map(()=>s++),l=(d,f)=>a.cost(d.condition,"F",f);c.forEach((d,f)=>{const p=a.cost(d.condition,"T",es),h=a.factsOf(d.condition);let m=null;for(const g of Oa){if(p===null||!Zr(d,g))continue;let b=p;for(let y=0;y<f;y++)Zr(c[y],g)&&(b+=l(c[y],h)??l(c[y],es)??0);m=Math.max(m??0,b)}e.push({ruleIndex:u[f],matchPath:i,blockPath:r.path.raw,blockRuleIndex:f,...d.loc?.line!==void 0?{line:d.loc.line}:{},operations:[...d.operations],grantCost:m})});for(const d of Oa){const f=c.filter(h=>Zr(h,d));if(f.length===0)continue;let p=0;for(const h of Rp(a,f)){let m=0;for(const g of f)m+=l(g,h)??l(g,es)??0;p=Math.max(p,m)}n.push({matchPath:i,blockPath:r.path.raw,method:d,denyCost:p})}}return{rules:e,blocks:n}}function Rp(t,e){const n=new Map;for(const i of e)for(const[o,a]of t.factsOf(ko(i.condition)))n.has(o)||n.set(o,new Set),n.get(o).add(a);let s;for(const[i,o]of n)(!s||o.size>n.get(s).size)&&(s=i);return s?[...[...n.get(s)],"unmatched"].map(i=>new Map([[s,i]])):[es]}function ko(t){return t.type==="binaryOp"&&t.op==="&&"?ko(t.left):t}function Lp(t){const e=[];let n=0;for(const{block:s,path:r,fns:i}of vl(t))for(const o of s.allows){const a=new Map,c=(u,l)=>{if(u.type==="functionCall"){const d=i.get(u.name);if(d&&(a.set(d,(a.get(d)??0)+1),l<20)){for(const f of d.lets)c(f.value,l+1);c(d.body,l+1)}}for(const d of Np(u))c(d,l)};c(o.condition,0),e.push({ruleIndex:n++,matchPath:r,blockPath:s.path.raw,...o.loc?.line!==void 0?{line:o.loc.line}:{},calls:[...a].map(([u,l])=>({fn:u,count:l}))})}return e}function Np(t){switch(t.type){case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end].filter(e=>!!e);case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args;default:return[]}}const Eo={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],fairness:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],results:["cloud.firestore"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Eo).sort());const Mp={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],fairness:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],results:[],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},Dp=["exists","existsAfter","float","get","getAfter","int","path","string"],$p=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Pp={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},wl={duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Sl=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.name","request.resource.size","request.time","resource","resource.bucket","resource.cacheControl","resource.contentDisposition","resource.contentEncoding","resource.contentLanguage","resource.contentType","resource.crc32c","resource.etag","resource.generation","resource.md5Hash","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],jp=["float","int","path","string"],Fp=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],qp={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},Al={duration:["abs","time","value"],firestore:["exists","get"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Up=new Set(Sl),Bp=["request.auth.token","request.resource.metadata","resource.metadata"];function zp(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const n=e.join(".");return Up.has(n)||Bp.some(s=>n.startsWith(`${s}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}const Wp=new Set(["request","request.resource","resource"]);function Vp(t,e){const n=e.join(".");return t==="cloud.firestore"?Wp.has(n):cs(t,e)?!1:Sl.some(s=>s.startsWith(`${n}.`))}function cs(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Gp(t,e){if(!e||e==="unknown-ambient")return null;const n=e.join(".");return n==="request"?"request":n==="request.resource"||n==="resource"?"resource":n==="request.auth"||n==="request.auth.token"||t==="cloud.firestore"&&(n==="request.resource.data"||n==="resource.data"||n==="request.query")||n==="request.resource.metadata"||n==="resource.metadata"?"map":n==="request.auth.uid"||n==="request.method"||n==="request.resource.contentType"||n==="resource.contentType"||t==="firebase.storage"&&(n==="request.resource.name"||n==="resource.name"||n==="resource.bucket"||n.startsWith("request.resource.metadata.")||n.startsWith("resource.metadata."))?"string":n==="request.path"?"path":n==="request.time"||n==="resource.timeCreated"||n==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(n)?"number":null}function Ra(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number"}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","keys","removeAll","split","values"].includes(t.method)?"list":["toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const Hp=new Set(["exists","existsAfter","get","getAfter"]),Kp=Object.fromEntries(Object.entries(wl).map(([t,e])=>[t,new Set(e)])),Zp=Object.fromEntries(Object.entries(Al).map(([t,e])=>[t,new Set(e)]));function Ii(t,e){return t.some(n=>n==="unknown-ambient"||n!==null&&Vp(e.service,n))?"unknown-ambient":null}function Et(t,e){return Ii(t.map(n=>Te(n,e)),e)}function kl(t,e,n){const s=n.declarations?.get(t),r=new Map(s?.aliases),i=new Map(s?.receiverTypes);return t.parameters.forEach((o,a)=>{r.set(o,e[a]?.provenance??null),i.set(o,e[a]?.receiverType??null)}),{aliases:r,receiverTypes:i,functions:s?.functions??n.functions,service:n.service,stack:new Set([...n.stack,t.name]),declarations:n.declarations}}function On(t,e){return{expression:t,provenance:Te(t,e),receiverType:we(t,e)}}function Te(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const n=Te(t.object,e);return n==="unknown-ambient"?n:n?[...n,t.property]:null}if(t.type==="bracketAccess"){const n=Te(t.object,e);return!n||n==="unknown-ambient"?n:t.index.type==="literal"&&typeof t.index.value=="string"?[...n,t.index.value]:[...n,"*"]}if(t.type==="ternary"){const n=Te(t.consequent,e),s=Te(t.alternate,e);return!n&&!s?null:Array.isArray(n)&&Array.isArray(s)&&n.join(".")===s.join(".")?n:Ii([n,s],e)}if(t.type==="functionCall"){const n=e.functions.get(t.name),s=t.args.map(i=>On(i,e));if(!n&&Hp.has(t.name))return null;if(!n||e.stack.has(n.name))return Ii(s.map(({provenance:i})=>i),e);const r=kl(n,s,e);for(const i of n.lets){const o=On(i.value,r);r.aliases.set(i.name,o.provenance),r.receiverTypes.set(i.name,o.receiverType)}return Te(n.body,r)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return Et([t.object,...t.args],e);case"sliceAccess":return Et([t.object,t.start,t.end],e);case"binaryOp":return Et([t.left,t.right],e);case"unaryOp":return Et([t.operand],e);case"inExpr":return Et([t.element,t.collection],e);case"isExpr":return Et([t.value],e);case"listLiteral":return Et(t.elements,e);case"mapLiteral":return Et(t.entries.flatMap(({key:n,value:s})=>[n,s]),e);case"pathLiteral":return Et(t.segments.filter(n=>typeof n!="string"),e);default:return null}}function we(t,e){const n=Gp(e.service,Te(t,e));if(n)return n;switch(t.type){case"identifier":{const s=e.receiverTypes.get(t.name);return s||((e.service==="cloud.firestore"?Kp:Zp)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":t.value instanceof Uint8Array?"bytes":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const s=we(t.object,e);if(s==="mixed")return"mixed";if(t.property==="data"&&s==="document")return"map";if(t.object.type==="mapLiteral"){const r=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return r?we(r.value,e):null}return null}case"bracketAccess":{const s=we(t.object,e);if(s==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?we(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,o=t.object.entries.find(({key:a})=>a.type==="literal"&&a.value===i);return o?we(o.value,e):null}if(s==="string")return"string";const r=Te(t.object,e);return e.service==="firebase.storage"&&Array.isArray(r)&&(r.join(".")==="request.resource.metadata"||r.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const s=we(t.object,e);return s==="mixed"?"mixed":s==="list"||s==="string"?s:null}case"methodCall":{const s=Ra(t);if(t.object.type==="identifier"&&s)return s;if(t.method==="get"){const r=Te(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(r)&&(r.join(".")==="request.resource.metadata"||r.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const o=t.args[0].value,a=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===o);return a?we(a.value,e):i?we(i,e):null}return i&&we(i,e)?"mixed":null}return Ra(t)}case"binaryOp":{const s=we(t.left,e),r=we(t.right,e);return t.op==="+"&&(s==="string"||r==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&s==="number"&&r==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&we(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const s=we(t.consequent,e),r=we(t.alternate,e);return!s&&!r?null:s===r?s:"mixed"}case"functionCall":{const s=e.functions.get(t.name);if(!s&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean";if(t.name==="string")return"string";if(t.name==="int"||t.name==="float")return"number";if(t.name==="path")return"path"}if(!s||e.stack.has(s.name))return null;const r=kl(s,t.args.map(i=>On(i,e)),e);for(const i of s.lets){const o=On(i.value,r);r.aliases.set(i.name,o.provenance),r.receiverTypes.set(i.name,o.receiverType)}return we(s.body,r)}default:return null}}function Jp(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Qp(t,e,n){const s=Jp(e),r=Eo[s];return r?r.includes(t)?null:`Function '${n}' from module '${e}' is not compatible with service '${t}'`:null}function Yp(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Xp=new Set(Dp),em=new Set($p),tm=Object.fromEntries(Object.entries(wl).map(([t,e])=>[t,new Set(e)])),nm=new Set(jp),sm=new Set(Fp),rm=Object.fromEntries(Object.entries(Al).map(([t,e])=>[t,new Set(e)]));function Zs(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!zp(e,t)?`binding '${t.join(".")}'`:null}function im(t,e,n,s,r){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=Te(t,r);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const o=n[0];if(o?.type==="literal"&&typeof o.value=="string")return Zs([...i,o.value],s);if(!cs(s,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!cs(s,i)?`binding '${i.join(".")}.${e}()'`:null}function om(t,e,n,s){const r=we(t,s);if(!r||r==="unknown"||r==="mixed")return null;const o=(n==="cloud.firestore"?Pp:qp)[e];return o?.includes(r)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${r}`}function am(t,e,n,s){const r=Te(e,s);return r==="unknown-ambient"?"binding '<derived ambient value>'":r?t.type==="literal"&&typeof t.value=="string"?Zs([...r,t.value],n):cs(n,r)?null:`binding '<value> in ${r.join(".")}'`:null}function La(t,e,n){const s=r=>{switch(r.type){case"memberAccess":{const i=Zs(Te(r,n),e);return i||s(r.object)}case"functionCall":{const i=n.functions.get(r.name);if(!i&&!(e==="cloud.firestore"?Xp:nm).has(r.name))return`function '${r.name}()'`;for(const a of r.args){const c=s(a);if(c)return c}if(i&&!n.stack.has(i.name)){const a=new Map,c=new Map;i.parameters.forEach((l,d)=>{const f=r.args[d];a.set(l,f?Te(f,n):null),c.set(l,f?we(f,n):null)});const u=El(i,e,{aliases:a,receiverTypes:c,functions:n.functions,service:e,stack:new Set([...n.stack,i.name])});if(u)return u}return null}case"methodCall":{if(r.object.type==="identifier"&&!n.aliases.has(r.object.name)){const u=(e==="cloud.firestore"?tm:rm)[r.object.name];if(u){if(!u.has(r.method))return`method '${r.object.name}.${r.method}()'`;for(const l of r.args){const d=s(l);if(d)return d}return null}return r.object.name==="firestore"?`method 'firestore.${r.method}()'`:`namespace '${r.object.name}'`}if(!(e==="cloud.firestore"?em:sm).has(r.method))return`method '.${r.method}()'`;const o=om(r.object,r.method,e,n);if(o)return o;const a=im(r.object,r.method,r.args,e,n);return a||(s(r.object)??r.args.map(s).find(Boolean)??null)}case"binaryOp":return s(r.left)??s(r.right);case"unaryOp":return s(r.operand);case"bracketAccess":{const i=Te(r.object,n);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const o=r.index.type==="literal"&&typeof r.index.value=="string";if(i&&!o)return cs(e,i)?s(r.object)??s(r.index):`binding '${i.join(".")}[...]'`;const a=Zs(Te(r,n),e);return a||(s(r.object)??s(r.index))}case"sliceAccess":return s(r.object)??s(r.start)??s(r.end);case"ternary":return s(r.condition)??s(r.consequent)??s(r.alternate);case"inExpr":return am(r.element,r.collection,e,n)??s(r.element)??s(r.collection);case"isExpr":return s(r.value);case"listLiteral":return r.elements.map(s).find(Boolean)??null;case"mapLiteral":for(const i of r.entries){const o=s(i.key)??s(i.value);if(o)return o}return null;case"pathLiteral":for(const i of r.segments)if(typeof i!="string"){const o=s(i);if(o)return o}return null;case"literal":return null;case"identifier":return r.name==="request"||r.name==="resource"||n.aliases.has(r.name)?null:`identifier '${r.name}'`;default:return Yp(r)}};return s(t)}function El(t,e,n){const s=new Map(n.aliases),r=new Map(n.receiverTypes),i={...n,aliases:s,receiverTypes:r};for(const o of t.lets){const a=La(o.value,e,i);if(a)return a;s.set(o.name,Te(o.value,i)),r.set(o.name,we(o.value,i))}return La(t.body,e,i)}function cm(t,e,n=new Map([[t.name,t]]),s=[]){const r={aliases:new Map,receiverTypes:new Map,functions:n,service:e,stack:new Set([t.name])};return El(t,e,{aliases:new Map(t.parameters.map((i,o)=>[i,o<s.length?s[o]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,o)=>[i,s[o]?we(s[o].expression,r)??s[o].receiverType??null:null])),functions:n,service:e,stack:new Set([t.name])})}function um(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function lm(t){const e=t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[^A-Za-z0-9_]/g,"_");return e.length===0||/^[0-9]/.test(e)?`_${e}`:e}function Qe(t,e){if(t!==e){const n=ks(t);for(let s=0;s<n;s++)fo(e)}return e}function de(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,s=t.args.map(r=>de(r,e));return Qe(t,n===t.name&&s.every((r,i)=>r===t.args[i])?t:{...t,name:n,args:s})}case"binaryOp":{const n=de(t.left,e),s=de(t.right,e);return Qe(t,n===t.left&&s===t.right?t:{...t,left:n,right:s})}case"unaryOp":{const n=de(t.operand,e);return Qe(t,n===t.operand?t:{...t,operand:n})}case"methodCall":{const n=de(t.object,e),s=t.args.map(r=>de(r,e));return Qe(t,n===t.object&&s.every((r,i)=>r===t.args[i])?t:{...t,object:n,args:s})}case"memberAccess":{const n=de(t.object,e);return Qe(t,n===t.object?t:{...t,object:n})}case"bracketAccess":{const n=de(t.object,e),s=de(t.index,e);return Qe(t,n===t.object&&s===t.index?t:{...t,object:n,index:s})}case"sliceAccess":{const n=de(t.object,e),s=de(t.start,e),r=de(t.end,e);return Qe(t,n===t.object&&s===t.start&&r===t.end?t:{...t,object:n,start:s,end:r})}case"ternary":{const n=de(t.condition,e),s=de(t.consequent,e),r=de(t.alternate,e);return Qe(t,n===t.condition&&s===t.consequent&&r===t.alternate?t:{...t,condition:n,consequent:s,alternate:r})}case"inExpr":{const n=de(t.element,e),s=de(t.collection,e);return Qe(t,n===t.element&&s===t.collection?t:{...t,element:n,collection:s})}case"isExpr":{const n=de(t.value,e);return Qe(t,n===t.value?t:{...t,value:n})}case"listLiteral":{const n=t.elements.map(s=>de(s,e));return Qe(t,n.every((s,r)=>s===t.elements[r])?t:{...t,elements:n})}case"mapLiteral":{const n=t.entries.map(s=>{const r=de(s.key,e),i=de(s.value,e);return r===s.key&&i===s.value?s:{key:r,value:i}});return Qe(t,n.every((s,r)=>s===t.entries[r])?t:{...t,entries:n})}case"pathLiteral":{const n=t.segments.map(s=>typeof s=="string"?s:de(s,e));return Qe(t,n.every((s,r)=>s===t.segments[r])?t:{...t,segments:n})}case"literal":case"identifier":return t;default:return um(t)}}function dm(t,e){const n=lm(e),s=new Map;for(const r of t)r.exported||s.set(r.name,`${n}__${r.name}`);return s.size===0?t:t.map(r=>{const i=de(r.body,s),o=r.lets.map(c=>{const u=de(c.value,s);return u===c.value?c:{...c,value:u}}),a=r.exported?r.name:s.get(r.name)??r.name;return i===r.body&&o===r.lets&&a===r.name?r:{...r,name:a,body:i,lets:o}})}function fm(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Io(t){const e=[],n=s=>{switch(s.type){case"functionCall":e.push(s),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"sliceAccess":n(s.object),n(s.start),n(s.end);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(({key:r,value:i})=>{n(r),n(i)});break;case"pathLiteral":s.segments.forEach(r=>{typeof r!="string"&&n(r)});break;case"literal":case"identifier":break;default:fm(s)}};return n(t),e}function hm(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function pm(t,e,n=new Map){const s=[],r=new Map,i=new Set,o=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",a=(h,m=new Set)=>({aliases:new Map(h.aliases),receiverTypes:new Map(h.receiverTypes),functions:h.functions,service:o,stack:m,declarations:r}),c=(h,m,g)=>{if(g.has(h.name))return;const b=r.get(h);if(!b)return;i.add(h);const y=new Map(b.aliases),w=new Map(b.receiverTypes);h.parameters.forEach((E,I)=>{y.set(E,m[I]?.provenance??null),w.set(E,m[I]?.receiverType??null)});const v=a({aliases:y,receiverTypes:w,functions:b.functions},new Set([...g,h.name]));for(const E of h.lets){u(E.value,v);const I=On(E.value,v);v.aliases.set(E.name,I.provenance),v.receiverTypes.set(E.name,I.receiverType)}u(h.body,v)},u=(h,m)=>{for(const g of Io(h)){const b=g.args.map(w=>On(w,m));g.name===e&&s.push({arguments:b.map(hm)});const y=m.functions.get(g.name);y&&!n.has(g.name)&&c(y,b,m.stack)}},l=new Map((t.functions??[]).map(h=>[h.name,h])),d=new Map([...l,...n]);for(const h of t.service.functions??[])d.set(h.name,h);for(const h of n.values())r.set(h,{aliases:new Map,receiverTypes:new Map,functions:n});const f=[];for(const h of t.functions??[])r.set(h,{aliases:new Map,receiverTypes:new Map,functions:l}),f.push(h);for(const h of t.service.functions??[])r.set(h,{aliases:new Map,receiverTypes:new Map,functions:d}),f.push(h);const p=(h,m)=>{const g=new Map(m.receiverTypes);for(const v of h.path.segments)v.type==="wildcard"&&g.set(v.name,"string"),v.type==="recursive"&&g.set(v.name,"path");const b=new Map(m.functions),y={aliases:m.aliases,receiverTypes:g,functions:b};for(const v of h.functions)b.set(v.name,v),r.set(v,y),f.push(v);const w=a(y);for(const{condition:v}of h.allows)u(v,w);h.children.forEach(v=>p(v,y))};p(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:d});for(const h of f)i.has(h)||c(h,[],new Set);return s}function Bn(t){return Io(t).map(({name:e})=>e)}function mm(t,e){return[...t.values()].flatMap(s=>[...s.lets.map(({value:r})=>r),s.body]).flatMap(Io).filter(({name:s})=>s===e).map(({args:s})=>s)}const gm=/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)/,ym=/^rules_version\s*=\s*(['"])([^'"]*)\1\s*;/,bm=/^import\s*\{([^}]*)\}\s*from\s*(['"])([^'"]+)\2\s*;/,vm=/^\s*(?:import\s*\{|rules_version\b)/m;function Na(t){return t.replace(/[^\n]/g," ")}function wm(t,e){const n=[];let s=t,r=0;for(;;){const i=t.slice(r),o=gm.exec(i);if(o){r+=o[0].length;continue}const a=ym.exec(i);if(a){if(a[2]!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Module '${e}' declares rules_version '${a[2]}'; a module's version is '2+modules'`}};s=s.slice(0,r)+Na(a[0])+s.slice(r+a[0].length),r+=a[0].length;continue}const c=bm.exec(i);if(c){const u=c[1].split(",").map(l=>l.trim()).filter(l=>l!=="");n.push({module:c[3],functions:u}),s=s.slice(0,r)+Na(c[0])+s.slice(r+c[0].length),r+=c[0].length;continue}return{success:!0,body:s,imports:n}}}function Ma(t,e,n){const s=wm(t,e);if(!s.success)return s;const r=Mh(s.body,e);return r===null?{success:!1,error:{code:"PARSE_FAILED",message:vm.test(s.body)?`Failed to parse module '${e}': a module puts rules_version and imports before its first function`:`Failed to parse module '${e}'`}}:{success:!0,functions:r,imports:s.imports,bundled:n}}function Sm(t,e){if(t===null||!us(e)||!us(t))return e;const n=[];for(const r of[...t.split("/").slice(0,-1),...e.split("/")]){if(r==="."||r==="")continue;const i=n.length>0&&n[n.length-1]!=="..";r===".."&&i?n.pop():n.push(r)}const s=n.join("/");return s.startsWith("..")?s:`./${s}`}function us(t){return t.startsWith("./")||t.startsWith("../")}function ls(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)(?:\.rules)?$/.exec(t)?.[1]??null}function Da(t,e,n,s=new Set){return n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e)?s.has(e)?ls(e)??e:e:(us(e)&&n?.basePath,ls(e)??e)}function Am(t,e,n,s=new Set){if(n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e))return Ma(n.modules[e],e,s.has(e));if(us(e)&&n?.basePath){const i=`${n.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!ls(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}const r=ls(e);return r?n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,r)?Ma(n.modules[r],e,s.has(r)):{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:us(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function km(t,e,n,s=new Set){const r=Es(e);if(!r.ok){const{line:A,column:M,message:ue}=r.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${A}, col ${M}: ${ue}`}}}const i=r.ast,o=i.version==="2+modules",a=i.service.name==="firebase.storage";let c=a?"storage.rules":"firestore.rules";if(o&&(c=a?"storage.modules.rules":"firestore.modules.rules"),n!==void 0&&n.sourceFile!==void 0&&n.sourceFile!==""&&(c=n.sourceFile),Em(i,c),o===!1)return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name==="cloud.firestore"===!1&&i.service.name==="firebase.storage"===!1)return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};const d=new Set([...(i.functions??[]).map(A=>A.name),...(i.service.functions??[]).map(A=>A.name)]),f=A=>{A.functions.forEach(M=>d.add(M.name)),A.children.forEach(f)};f(i.service.match);const p=[...d].find(A=>Kr.has(A));if(p)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${p}' conflicts with a Rules builtin`}};if(i.imports.length===0){i.version="2";const A=Ia(i),M=JSON.stringify(A.sourceMap);return{success:!0,data:{resolved:`${A.resolved}// @pyric-source-map: ${M}
|
|
514
|
+
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:A.sourceMap}}}const m=i.imports.find(A=>A.functions.length===0);if(m)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${m.module}' must request at least one function`}};const g=new Map,b=new Map,y=new Map,w=new Map,v=[],E=[],I=new Map,j=new Map,W=new Map,V=new Map,T=new Map,N=i.imports.map(A=>({module:A.module,functions:A.functions,importer:null}));for(let A=N.shift();A!==void 0;A=N.shift()){const M=Da(t,A.module,n,s);if(!j.has(M)){const q=Am(t,A.module,n,s);if(!q.success)return{success:!1,error:q.error};v.push(A.module),y.set(M,A.module),W.set(M,q.bundled),q.bundled&&E.push(A.module);for(const he of q.imports){if(he.functions.length===0)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${he.module}' in module '${A.module}' must request at least one function`}};N.push({...he,module:Sm(A.module,he.module),importer:M})}const le=new Set,kt=q.functions.find(he=>le.has(he.name)?!0:(le.add(he.name),!1));if(kt)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${A.module}' defines duplicate function '${kt.name}'`}};const jn=q.functions.find(he=>Kr.has(he.name));if(jn)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${jn.name}' from module '${A.module}' conflicts with a Rules builtin`}};const yn=new Set;for(const he of q.functions)he.exported||yn.add(he.name);I.set(M,yn);const _e=dm(q.functions,A.module),qr=new Map;for(const he of _e){if(qr.has(he.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${A.module}' defines conflicting function name '${he.name}'`}};qr.set(he.name,he),b.has(he.name)||b.set(he.name,A.module)}const Yd=new Set(_e.filter(he=>he.exported).map(he=>he.name));g.set(M,qr),j.set(M,Yd)}const ue=j.get(M),Ve=y.get(M)??A.module;for(const q of A.functions){if(!ue.has(q))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:I.get(M)?.has(q)?`Function '${q}' in module '${A.module}' is not exported`:`Function '${q}' not found in module '${A.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const le=W.get(M)?Qp(i.service.name,A.module,q):null;if(le)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:le}}}if(A.importer===null){const le=T.get(q);if(le!==void 0&&le!==M)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${q}' exported by both '${y.get(le)}' and '${Ve}'`}};T.set(q,M)}else{const le=V.get(A.importer)??new Map,kt=le.get(q);if(kt!==void 0&&kt!==M)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${q}' exported by both '${y.get(kt)}' and '${Ve}'`}};le.set(q,M),V.set(A.importer,le)}}}const B=new Set(i.imports.flatMap(A=>A.functions)),G=[],C=[],S={cycle:null,error:null};function x(A,M){if(S.cycle||S.error)return;const ue=C.findIndex(_e=>_e.modKey===A&&_e.fnName===M);if(ue>=0){S.cycle=[...C.slice(ue).map(_e=>_e.fnName),M];return}const Ve=w.get(M);if(Ve!==void 0){if(Ve===A)return;S.error={code:"DUPLICATE_FUNCTION",message:`Function '${M}' from module '${y.get(A)}' conflicts with module '${y.get(Ve)}'`};return}const q=g.get(A)?.get(M);if(!q)return;C.push({modKey:A,fnName:M});const le=[...q.lets.flatMap(({value:_e})=>Bn(_e)),...Bn(q.body)],kt=g.get(A),jn=V.get(A);for(const _e of le)if(!Kr.has(_e)){if(kt?.has(_e))x(A,_e);else if(jn?.has(_e))x(jn.get(_e),_e);else if(b.has(_e)){S.error={code:"UNKNOWN_FUNCTION",message:`Function '${q.name}' in module '${y.get(A)}' cannot call '${_e}' from another module`},C.pop();return}if(S.cycle||S.error){C.pop();return}}if(C.pop(),S.cycle||S.error)return;const yn=w.get(M);if(yn!==void 0&&yn!==A){S.error={code:"DUPLICATE_FUNCTION",message:`Function '${M}' from module '${y.get(A)}' conflicts with module '${y.get(yn)}'`};return}w.set(M,A),G.push({...q,exported:!1})}for(const A of i.imports){const M=Da(t,A.module,n,s);for(const ue of A.functions)x(M,ue)}if(S.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${S.cycle.join(" -> ")}`}};if(S.error)return{success:!1,error:S.error};const F=new Set(G.map(A=>A.name)),D=new Map((i.functions??[]).map(A=>[A.name,A])),H=new Set((i.service.functions??[]).map(A=>A.name)),ne=(A,M)=>A.flatMap(Bn).find(ue=>b.has(ue)&&!B.has(ue)&&!M.has(ue))??null,ae=A=>A.flatMap(M=>[...M.lets.map(({value:ue})=>ue),M.body]),Oe=new Set(D.keys());let ce=ne(ae(i.functions??[]),Oe);const Y=new Set([...Oe,...H]);ce??=ne(ae(i.service.functions??[]),Y);const X=(A,M)=>{const ue=new Set([...M,...A.functions.map(q=>q.name)]),Ve=[...ae(A.functions),...A.allows.map(({condition:q})=>q)];return ne(Ve,ue)??A.children.map(q=>X(q,ue)).find(Boolean)??null};if(ce??=X(i.service.match,Y),ce)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${ce}' from module '${b.get(ce)}' without importing it`}};const be=(A,M)=>{if(M.has(A.name))return!1;const ue=new Set([...M,A.name]);return[...A.lets.flatMap(({value:q})=>Bn(q)),...Bn(A.body)].some(q=>{const le=D.get(q);return le?be(le,ue):F.has(q)||H.has(q)})},ie=[...D.values()].find(A=>be(A,new Set));if(ie)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${ie.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const A=new Map(G.map(M=>[M.name,M]));for(const M of G){const ue=[...pm(i,M.name,A),...mm(A,M.name).map(q=>({arguments:q.map(le=>({expression:le,provenance:null,receiverType:"unknown"}))}))],Ve=ue.length>0?ue:[{arguments:[]}];for(const{arguments:q}of Ve){const le=cm(M,i.service.name,A,q);if(le)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${M.name}' requires unsupported ${le} for service '${i.service.name}'`}}}}}for(const A of G)if(d.has(A.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${A.name}' conflicts with a function defined in the source`}};i.service.functions=[...G,...i.service.functions??[]],i.version="2",i.imports=[];const jt=new Set,Cs=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const A of E){const M=ls(A)??A,ue=Mp[M]??[];for(const Ve of ue)Ve.startsWith(Cs)&&jt.add(Ve)}const Os=Ia(i),gn=JSON.stringify(Os.sourceMap);return{success:!0,data:{resolved:`${Os.resolved}// @pyric-source-map: ${gn}
|
|
515
|
+
`,modules:v,bundledModules:E,evidenceIds:[...jt].sort(),sourceMap:Os.sourceMap}}}function Em(t,e){const n=a=>{a.loc!==void 0&&(a.loc.file=e);for(const c of a.lets)c.loc!==void 0&&(c.loc.file=e);a.returnLoc!==void 0&&(a.returnLoc.file=e),a.body?.loc!==void 0&&(a.body.loc.file=e)};if(t.service.loc!==void 0&&(t.service.loc.file=e),t.functions!==void 0)for(const a of t.functions)n(a);if(t.service.functions!==void 0)for(const a of t.service.functions)n(a);const i=[t.service.match];let o=i.length;for(;o>0;){const a=i.pop();a.loc!==void 0&&(a.loc.file=e);for(const u of a.allows)u.loc!==void 0&&(u.loc.file=e);for(const u of a.functions)n(u);for(const u of a.children)i.push(u);o=i.length}}const $a="// @pyric-source-map: ";function _o(t){const e=new Map,n=t.indexOf($a);if(!(n!==-1))return e;const r=n+$a.length,i=t.indexOf(`
|
|
516
|
+
`,r);let o="";i!==-1?o=t.slice(r,i).trim():o=t.slice(r).trim();try{const c=JSON.parse(o);if(Array.isArray(c))for(const l of c)!e.has(l.generatedLine)&&e.set(l.generatedLine,l)}catch{}return e}function Im(t,e,n,s,r){if(e!==void 0)return Il(_o(t),e,n,s,r)}function Il(t,e,n,s,r){if(e===void 0)return;let o=e,a=1;n!==void 0&&(a=n);let u="firestore.rules";s!==void 0&&s!==""&&(u=s);let d;r!==void 0&&(d=r);const p=t.get(o);p!==void 0&&(o=p.authoredLine,a=p.authoredCol,u=p.authoredFile,p.expression!==void 0&&(d=p.expression));const m=`${u}:${o}:${a}`,g={line:o,col:a,file:u,citation:m};return d!==void 0&&(g.expression=d),g}const _m={atomic:`// @pyric-services cloud.firestore
|
|
517
517
|
// Costs are production expressions per call, not counting arguments. Calls
|
|
518
518
|
// are not memoized: every call pays its full cost again, and a let inside a
|
|
519
519
|
// function is paid on every call.
|
|
@@ -1689,27 +1689,27 @@ export function validString(field, min, max) {
|
|
|
1689
1689
|
export function isOneOf(field, values) {
|
|
1690
1690
|
return request.resource.data[field] in values;
|
|
1691
1691
|
}
|
|
1692
|
-
`};function km(){const t={};for(const[e,n]of Object.entries(Am))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}const _l=km(),Em=new Set(Object.keys(_l));function Im(t,e,n){const s=Object.entries(n?.modules??{}),r=Object.fromEntries(s),i=new Set(s.map(([a])=>a)),o=new Set([...Em].filter(a=>!i.has(a)));return vm(t,e,{...n,modules:{..._l,...r}},o)}function _m(t,e){return Im(null,t,e)}const xm={key:"builtins",kind:"language-namespace",description:"Top-level functions always in scope inside rules: get, exists, getAfter. Called bare, no namespace prefix. (debug() is docs-only: production rejects it at compile.)",purpose:"The built-in functions Firestore Rules ships with at the top level. They are NOT inside a namespace: call `get(path)`, not `firestore.get(path)`. Used to read other documents (cross-document gates), check existence, and peek at post-write state.",whenToUse:"Reach for `builtins` any time a rule needs information that isn't already on `request` or `resource`. Most common: `get(path)` to read another document's fields inside a predicate.",entries:[{signature:"get(path: path): Resource",description:"Read another document. Returns a Resource whose `.data` is the doc map. Counts against the rule's `get()` budget (cap 10 per evaluation).",examples:["allow update: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';"],notes:"Path must start with `/databases/$(database)/documents/`. Hardcoding a different database id silently fails."},{signature:"exists(path: path): bool",description:"True if a document at `path` exists. Counts against the get() budget like `get`.",examples:["allow create: if exists(/databases/$(database)/documents/teams/$(request.resource.data.teamId));"]},{signature:"getAfter(path: path): Resource",description:"Like `get`, but reads the doc AS IT WILL BE after the current transaction commits. Use for cross-document consistency gates that depend on the post-write state of another doc in the same batch.",notes:"Only meaningful inside transactions / batched writes. Outside a batch, equivalent to `get`."},{signature:"debug(value: any): bool",acceptance:"rejected",description:"DO NOT USE. Although Firebase reference docs list `debug()`, production Firestore REJECTS rulesets that call it at compile time (`Function not found error: Name: [debug]`). The linter and local simulator reject it for the same reason.",notes:"Remove any debug() wrapper before deploying and evaluate the inner expression directly. There is no deployable logging primitive in rules."}],relatedKeys:["request","resource","path"]},Cm={key:"math",kind:"language-namespace",description:"Numeric helpers: abs, ceil, floor, round, sqrt, pow, isNaN. Use when rules need to coerce or bound numbers.",purpose:"The `math` namespace exposes a small set of numeric utilities for use inside rule predicates. Functions are called as `math.<fn>(...)`. Always in scope; no import needed.",whenToUse:"Reach for `math` whenever a rule needs to round, bound, or guard against NaN in a user-supplied field.",entries:[{signature:"math.abs(n: number): number",description:"Absolute value of `n`."},{signature:"math.ceil(n: number): int",description:"Smallest integer >= `n`."},{signature:"math.floor(n: number): int",description:"Largest integer <= `n`."},{signature:"math.round(n: number): int",description:"Nearest integer to `n`."},{signature:"math.sqrt(n: number): number",description:"Square root of `n`. Negative input returns NaN."},{signature:"math.pow(base: number, exp: number): number",description:"`base` raised to `exp`."},{signature:"math.isNaN(n: number): bool",description:"True if `n` is NaN.",notes:"There is NO isInfinite function in the math namespace. Production Firestore rejects it at compile time (`Function not found error: Name: [math.isInfinite]`), despite it appearing in some Firebase reference material."}],examples:["allow update: if math.ceil(request.resource.data.score) <= 100;","allow create: if !math.isNaN(request.resource.data.lat);"],relatedKeys:["hashing"]},Om={key:"timestamp",kind:"language-namespace",description:"Timestamp constructors — date(year, month, day), value(epochMillis). Use to build timestamps in rule comparisons.",purpose:"The `timestamp` namespace contains constructors that produce Timestamp values for use in comparisons. The Timestamp TYPE has its own methods (year, month, etc.) — those live under the `string`/`list`/`map`-style key `timestamp-methods` in this stdlib, accessed via dot notation on a timestamp value.",whenToUse:"Reach for the `timestamp` namespace when a rule needs to construct a specific Timestamp value to compare against `request.time` or a document field.",entries:[{signature:"timestamp.date(year: int, month: int, day: int): Timestamp",description:"Construct a Timestamp at UTC midnight of the given date.",examples:["allow read: if request.time > timestamp.date(2024, 1, 1);"]},{signature:"timestamp.value(epochMillis: int): Timestamp",description:"Construct a Timestamp from epoch milliseconds."}],relatedKeys:["duration","request","lifecycle"]},Tm={key:"duration",kind:"language-namespace",description:'Duration constructors — value(magnitude, unit), time(h, m, s, ns), abs(d). Use for "within N seconds" windows.',purpose:"The `duration` namespace builds Duration values that can be added to or subtracted from Timestamps. Useful for time-window predicates in security rules.",whenToUse:'Reach for `duration` whenever a rule expresses a time window — "within 5 minutes of write", "older than 30 days", etc.',entries:[{signature:"duration.value(magnitude: int, unit: 'w' | 'd' | 'h' | 'm' | 's' | 'ms' | 'ns'): Duration",description:"Construct a Duration of `magnitude` of the given unit.",examples:["allow update: if request.time < resource.data.createdAt + duration.value(5, 'm');"]},{signature:"duration.time(h: int, m: int, s: int, ns: int): Duration",description:"Construct a Duration as a sum of hours, minutes, seconds, nanoseconds."},{signature:"duration.abs(d: Duration): Duration",description:"Absolute value of a Duration (drops sign)."}],relatedKeys:["timestamp"]},Rm={key:"latlng",kind:"language-namespace",description:"GeoPoint constructor — value(lat, lng). Builds LatLng values for proximity rules.",purpose:"The `latlng` namespace constructs LatLng values. The LatLng type itself has methods (`latitude()`, `longitude()`, `distance(other)`) accessed via dot notation on a latlng value.",whenToUse:'Reach for `latlng` when a rule gates on physical proximity — e.g. "this write must come within N meters of the document\'s anchor point".',entries:[{signature:"latlng.value(lat: number, lng: number): LatLng",description:"Construct a LatLng. Latitude in [-90, 90], longitude in [-180, 180].",examples:["allow update: if latlng.value(request.resource.data.lat, request.resource.data.lng).distance(resource.data.anchor) < 1000;"]}]},Lm={key:"hashing",kind:"language-namespace",description:"Hash digests — md5, sha256, crc32, crc32c. Each takes Bytes or String and returns Bytes.",purpose:"The `hashing` namespace exposes one-shot digest functions. Output is Bytes; compare equality with `==` against a stored Bytes value.",whenToUse:"Reach for `hashing` for tamper-evidence checks — comparing a submitted hash against a stored digest, or verifying a public-facing checksum.",entries:[{signature:"hashing.md5(input: Bytes | String): Bytes",description:"MD5 digest. 128-bit; do not use for security-sensitive integrity proofs."},{signature:"hashing.sha256(input: Bytes | String): Bytes",description:"SHA-256 digest. 256-bit; the right choice for integrity proofs."},{signature:"hashing.crc32(input: Bytes | String): Bytes",description:"CRC32 checksum (Bytes). Use for non-cryptographic integrity."},{signature:"hashing.crc32c(input: Bytes | String): Bytes",description:"CRC32C checksum (Bytes). Same role as crc32 with a different polynomial."}],examples:["allow update: if hashing.sha256(request.resource.data.payload) == resource.data.checksum;"],relatedKeys:["bytes"]},Nm={key:"string",kind:"type-methods",description:"Methods on string values — matches, lower, upper, trim, size, split, replace, toUtf8. Called as `value.method(...)`.",purpose:"Methods available on values of type `string` inside rule expressions. Dispatched on the value: `myField.matches(...)`, not `string.matches(myField, ...)`. The engine routes the call based on the value's runtime type.",whenToUse:"Reach for these whenever a rule examines a string field — pattern checks, case-insensitive comparisons, trimming user input, encoding to bytes.",entries:[{signature:"string.matches(pattern: string): bool",description:"True if the string matches the given RE2 regex (full match).",examples:["allow create: if request.resource.data.email.matches('.*@example[.]com');"],notes:"Pattern is RE2 syntax, NOT JavaScript regex. No anchors needed — the match is full-string by default."},{signature:"string.lower(): string",description:"Return the string lowercased."},{signature:"string.upper(): string",description:"Return the string uppercased."},{signature:"string.trim(): string",description:"Strip leading + trailing whitespace."},{signature:"string.size(): int",description:"Length in characters (NOT bytes — use `toUtf8().size()` for byte length)."},{signature:"string.split(separator: string): list<string>",description:"Split the string into a list on `separator`."},{signature:"string.replace(old: string, new: string): string",description:"Replace all occurrences of `old` with `new`."},{signature:"string.toUtf8(): bytes",description:"Encode the string as UTF-8 bytes.",notes:"Use before hashing if the input is a string."}],examples:["allow create: if request.resource.data.slug.size() > 0 && request.resource.data.slug.size() <= 64;","allow update: if request.resource.data.kind.lower() == 'public';"],relatedKeys:["bytes","hashing","validation"]},Mm={key:"list",kind:"type-methods",description:"Methods on list values — hasAll, hasAny, hasOnly, size, toSet, concat, removeAll, join. Called as `value.method(...)`.",purpose:"Methods on list values — used to check membership, compare contents, transform to sets, and concatenate. Lists in rules are ordered + finite; methods often have parallel semantics on the `set` view produced by `toSet()`.",whenToUse:'Reach for these whenever a rule examines an array field — tag membership ("user can update if their uid is in editors"), array-shape validation, or projecting to a set for difference checks.',entries:[{signature:"list.hasAll(other: list): bool",description:"True if every element of `other` is present in this list.",examples:["allow update: if request.resource.data.tags.hasAll(['public', 'reviewed']);"]},{signature:"list.hasAny(other: list): bool",description:"True if at least one element of `other` is present in this list."},{signature:"list.hasOnly(other: list): bool",description:"True if every element of THIS list is in `other` (i.e. this is a subset).",notes:'Often the right call for "no fields outside this allowlist" patterns when used with `request.resource.data.keys()`.'},{signature:"list.size(): int",description:"Number of elements."},{signature:"list.toSet(): set",description:"Convert to a Set view (de-duplicated, unordered). Useful for `difference`/`union`/`intersection` operations."},{signature:"list.concat(other: list): list",description:"Return a new list with `other` appended."},{signature:"list.removeAll(other: list): list",description:"Return a new list with every element of `other` removed."},{signature:"list.join(separator: string): string",description:"Join elements into a single string with `separator` between them."}],relatedKeys:["map","string"]},Dm={key:"map",kind:"type-methods",description:"Methods on map values — keys, values, size, get, diff. Called as `value.method(...)`.",purpose:"Methods on map values. The most common in rule code: `keys()` returns a list of map keys (combined with `list.hasAll`/`list.hasOnly` for shape checks), and `diff(other)` returns a MapDiff used to assert which fields changed across an update.",whenToUse:"Reach for these for shape validation (which keys exist), for default-aware reads (`get(key, default)`), and for diff-based immutability gates on updates.",entries:[{signature:"map.keys(): list<string>",description:"List of top-level keys in the map.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"map.values(): list",description:"List of top-level values in the map."},{signature:"map.size(): int",description:"Number of top-level keys."},{signature:"map.get(key: string, fallback: any): any",description:"Return `map[key]` if present, otherwise `fallback`. Same shape as `get(map, key, fallback)`."},{signature:"map.diff(other: map): MapDiff",description:"Return a MapDiff with `.addedKeys()`, `.removedKeys()`, `.changedKeys()`, `.affectedKeys()`, `.unchangedKeys()` methods, each returning a Set of keys.",examples:["allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['updatedAt']);"],notes:"The MapDiff result is the right surface for immutability gates — easier to read than chaining individual field-unchanged checks."}],relatedKeys:["list","lifecycle","validation"]},$m={key:"bytes",kind:"type-methods",description:"Methods on bytes values — size, toBase64, toHexString. Called as `value.method(...)`.",purpose:"Methods on Bytes values — the output of hashing operations and the storage shape for arbitrary binary payloads. Bytes also support comparison operators (<, <=, >, >=) for lexicographic ordering.",whenToUse:"Reach for these when a rule examines a Bytes field — typically a stored digest from `hashing.sha256(...)` — or when comparing two hashes for tamper-evidence.",entries:[{signature:"bytes.size(): int",description:"Number of bytes."},{signature:"bytes.toBase64(): string",description:"Padded base64url encoding of the bytes: `-` and `_` in place of `+` and `/`, with `=` padding."},{signature:"bytes.toHexString(): string",description:"Uppercase hexadecimal encoding of the bytes."}],relatedKeys:["hashing","string"]},Pm={key:"path",kind:"type-methods",description:"Methods on path values — bind. Used to fill in template variables in document paths.",purpose:"Path values are the type used for cross-document references inside rules (e.g. the path passed to `get()` or `exists()`). The `bind` method substitutes template variables into a path literal.",whenToUse:"Reach for `path.bind` when a `get()` or `exists()` call needs a dynamic path with one or more template variables filled in from rule context.",entries:[{signature:"path.bind(bindings: map<string, string>): path",description:"Return a new path with template variables (`{name}`) replaced by values from `bindings`.",examples:["allow update: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/profile/main);"],notes:"In practice most rule code constructs paths inline with `$()` interpolation instead of `path.bind`. `bind` is here for completeness."}],relatedKeys:["request","resource"]},jm={key:"request",kind:"globals",description:"Root namespace for the in-flight request — auth, resource.data, time, path, method, query. Always available, no import.",purpose:"The `request` identifier carries everything the engine knows about the current request — who is making it (`auth`), what they are sending (`resource.data`), when (`time`), and where (`path`, `method`). These are *paths*, not callables — read fields off them in rule predicates.",whenToUse:"Every non-trivial rule reads from `request` to authorize the operation. The two most common touchpoints: `request.auth` (who) and `request.resource.data` (what).",entries:[{signature:"request.auth: map | null",description:"The authenticated user. `null` for unauthenticated requests.",examples:["allow read: if request.auth != null;"]},{signature:"request.auth.uid: string",description:"The signed-in user's UID. Only safe to read after a null-check on `request.auth`.",examples:["allow update: if request.auth.uid == resource.data.ownerId;"]},{signature:"request.auth.token: map",description:"Map of custom claims set on the user's ID token (e.g. `request.auth.token.admin`).",examples:["allow delete: if request.auth.token.admin == true;"],notes:"Custom claims live under `request.auth.token.*`, NOT `request.auth.*`. Agents often emit `request.auth.admin` — that always reads `null`."},{signature:"request.resource.data: map",description:"The document data being written (create/update/set). Read it to validate what the client is sending.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"request.time: timestamp",description:"Server time of the request. Compare against document timestamps for windowed gates."},{signature:"request.path: path",description:"Path of the document being operated on (e.g. `/databases/(default)/documents/users/alice`)."},{signature:"request.method: 'get' | 'list' | 'create' | 'update' | 'delete'",description:"Which operation triggered the rule. Usually inferred from the `allow` clause, but available for fine-grained checks."},{signature:"request.query: map",description:"Query metadata for `list` requests — `limit`, `offset`, `orderBy`. Available on `allow list` rules only."}],relatedKeys:["resource","auth"]},Fm={key:"resource",kind:"globals",description:"Root namespace for the existing document — use resource.data to compare against what is already there.",purpose:"The `resource` identifier is the document state BEFORE the request — what is currently stored. When the target does not exist, evaluating `resource` raises a null-value error; it is not a comparable null. On an update/delete of an existing document, it contains the pre-write data. Use it to compare incoming changes against existing values.",whenToUse:'Whenever a rule needs the pre-write state — e.g. "the existing owner is the one updating", "the field already had this value before the write".',entries:[{signature:"resource.data: map",description:"The currently stored document data. When the target does not exist, evaluating `resource` raises a null-value error.",examples:["allow update: if resource.data.ownerId == request.auth.uid;"]}],relatedKeys:["request"]},qm={key:"auth",kind:"user-module",description:"User-authored module: authentication primitives (isAuthenticated, isOwner). Self-contained. Import via `import { isAuthenticated, isOwner } from 'auth';` (the resolver also accepts the path form `from './stdlib/auth.rules'` if you prefer).",purpose:'Two-function module covering the most common access-control predicates in any user-facing app: "is the request authenticated" and "is the request the owner of this document".',whenToUse:"Import as the first stdlib module on any project that has user-owned documents. Pairs with `validation` and `lifecycle` for full create/update/delete coverage.",entries:[{signature:"isAuthenticated(): bool",cost:{min:5,max:5},reads:0,description:"`request.auth != null`."},{signature:"isOwner(userId: string): bool",cost:{min:7,max:13},reads:0,description:"`request.auth.uid == userId`. Pass a field path like `resource.data.ownerId`.",examples:["allow update: if isAuthenticated() && isOwner(resource.data.ownerId);"]}],examples:[`rules_version = '2+modules';
|
|
1692
|
+
`};function xm(){const t={};for(const[e,n]of Object.entries(_m))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}const _l=xm(),Cm=new Set(Object.keys(_l));function Om(t,e,n){const s=Object.entries(n?.modules??{}),r=Object.fromEntries(s),i=new Set(s.map(([a])=>a)),o=new Set([...Cm].filter(a=>!i.has(a)));return km(t,e,{...n,modules:{..._l,...r}},o)}function Tm(t,e){return Om(null,t,e)}const Rm={key:"builtins",kind:"language-namespace",description:"Top-level functions always in scope inside rules: get, exists, getAfter. Called bare, no namespace prefix. (debug() is docs-only: production rejects it at compile.)",purpose:"The built-in functions Firestore Rules ships with at the top level. They are NOT inside a namespace: call `get(path)`, not `firestore.get(path)`. Used to read other documents (cross-document gates), check existence, and peek at post-write state.",whenToUse:"Reach for `builtins` any time a rule needs information that isn't already on `request` or `resource`. Most common: `get(path)` to read another document's fields inside a predicate.",entries:[{signature:"get(path: path): Resource",description:"Read another document. Returns a Resource whose `.data` is the doc map. Counts against the rule's `get()` budget (cap 10 per evaluation).",examples:["allow update: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';"],notes:"Path must start with `/databases/$(database)/documents/`. Hardcoding a different database id silently fails."},{signature:"exists(path: path): bool",description:"True if a document at `path` exists. Counts against the get() budget like `get`.",examples:["allow create: if exists(/databases/$(database)/documents/teams/$(request.resource.data.teamId));"]},{signature:"getAfter(path: path): Resource",description:"Like `get`, but reads the doc AS IT WILL BE after the current transaction commits. Use for cross-document consistency gates that depend on the post-write state of another doc in the same batch.",notes:"Only meaningful inside transactions / batched writes. Outside a batch, equivalent to `get`."},{signature:"debug(value: any): bool",acceptance:"rejected",description:"DO NOT USE. Although Firebase reference docs list `debug()`, production Firestore REJECTS rulesets that call it at compile time (`Function not found error: Name: [debug]`). The linter and local simulator reject it for the same reason.",notes:"Remove any debug() wrapper before deploying and evaluate the inner expression directly. There is no deployable logging primitive in rules."}],relatedKeys:["request","resource","path"]},Lm={key:"math",kind:"language-namespace",description:"Numeric helpers: abs, ceil, floor, round, sqrt, pow, isNaN. Use when rules need to coerce or bound numbers.",purpose:"The `math` namespace exposes a small set of numeric utilities for use inside rule predicates. Functions are called as `math.<fn>(...)`. Always in scope; no import needed.",whenToUse:"Reach for `math` whenever a rule needs to round, bound, or guard against NaN in a user-supplied field.",entries:[{signature:"math.abs(n: number): number",description:"Absolute value of `n`."},{signature:"math.ceil(n: number): int",description:"Smallest integer >= `n`."},{signature:"math.floor(n: number): int",description:"Largest integer <= `n`."},{signature:"math.round(n: number): int",description:"Nearest integer to `n`."},{signature:"math.sqrt(n: number): number",description:"Square root of `n`. Negative input returns NaN."},{signature:"math.pow(base: number, exp: number): number",description:"`base` raised to `exp`."},{signature:"math.isNaN(n: number): bool",description:"True if `n` is NaN.",notes:"There is NO isInfinite function in the math namespace. Production Firestore rejects it at compile time (`Function not found error: Name: [math.isInfinite]`), despite it appearing in some Firebase reference material."}],examples:["allow update: if math.ceil(request.resource.data.score) <= 100;","allow create: if !math.isNaN(request.resource.data.lat);"],relatedKeys:["hashing"]},Nm={key:"timestamp",kind:"language-namespace",description:"Timestamp constructors — date(year, month, day), value(epochMillis). Use to build timestamps in rule comparisons.",purpose:"The `timestamp` namespace contains constructors that produce Timestamp values for use in comparisons. The Timestamp TYPE has its own methods (year, month, etc.) — those live under the `string`/`list`/`map`-style key `timestamp-methods` in this stdlib, accessed via dot notation on a timestamp value.",whenToUse:"Reach for the `timestamp` namespace when a rule needs to construct a specific Timestamp value to compare against `request.time` or a document field.",entries:[{signature:"timestamp.date(year: int, month: int, day: int): Timestamp",description:"Construct a Timestamp at UTC midnight of the given date.",examples:["allow read: if request.time > timestamp.date(2024, 1, 1);"]},{signature:"timestamp.value(epochMillis: int): Timestamp",description:"Construct a Timestamp from epoch milliseconds."}],relatedKeys:["duration","request","lifecycle"]},Mm={key:"duration",kind:"language-namespace",description:'Duration constructors — value(magnitude, unit), time(h, m, s, ns), abs(d). Use for "within N seconds" windows.',purpose:"The `duration` namespace builds Duration values that can be added to or subtracted from Timestamps. Useful for time-window predicates in security rules.",whenToUse:'Reach for `duration` whenever a rule expresses a time window — "within 5 minutes of write", "older than 30 days", etc.',entries:[{signature:"duration.value(magnitude: int, unit: 'w' | 'd' | 'h' | 'm' | 's' | 'ms' | 'ns'): Duration",description:"Construct a Duration of `magnitude` of the given unit.",examples:["allow update: if request.time < resource.data.createdAt + duration.value(5, 'm');"]},{signature:"duration.time(h: int, m: int, s: int, ns: int): Duration",description:"Construct a Duration as a sum of hours, minutes, seconds, nanoseconds."},{signature:"duration.abs(d: Duration): Duration",description:"Absolute value of a Duration (drops sign)."}],relatedKeys:["timestamp"]},Dm={key:"latlng",kind:"language-namespace",description:"GeoPoint constructor — value(lat, lng). Builds LatLng values for proximity rules.",purpose:"The `latlng` namespace constructs LatLng values. The LatLng type itself has methods (`latitude()`, `longitude()`, `distance(other)`) accessed via dot notation on a latlng value.",whenToUse:'Reach for `latlng` when a rule gates on physical proximity — e.g. "this write must come within N meters of the document\'s anchor point".',entries:[{signature:"latlng.value(lat: number, lng: number): LatLng",description:"Construct a LatLng. Latitude in [-90, 90], longitude in [-180, 180].",examples:["allow update: if latlng.value(request.resource.data.lat, request.resource.data.lng).distance(resource.data.anchor) < 1000;"]}]},$m={key:"hashing",kind:"language-namespace",description:"Hash digests — md5, sha256, crc32, crc32c. Each takes Bytes or String and returns Bytes.",purpose:"The `hashing` namespace exposes one-shot digest functions. Output is Bytes; compare equality with `==` against a stored Bytes value.",whenToUse:"Reach for `hashing` for tamper-evidence checks — comparing a submitted hash against a stored digest, or verifying a public-facing checksum.",entries:[{signature:"hashing.md5(input: Bytes | String): Bytes",description:"MD5 digest. 128-bit; do not use for security-sensitive integrity proofs."},{signature:"hashing.sha256(input: Bytes | String): Bytes",description:"SHA-256 digest. 256-bit; the right choice for integrity proofs."},{signature:"hashing.crc32(input: Bytes | String): Bytes",description:"CRC32 checksum (Bytes). Use for non-cryptographic integrity."},{signature:"hashing.crc32c(input: Bytes | String): Bytes",description:"CRC32C checksum (Bytes). Same role as crc32 with a different polynomial."}],examples:["allow update: if hashing.sha256(request.resource.data.payload) == resource.data.checksum;"],relatedKeys:["bytes"]},Pm={key:"string",kind:"type-methods",description:"Methods on string values — matches, lower, upper, trim, size, split, replace, toUtf8. Called as `value.method(...)`.",purpose:"Methods available on values of type `string` inside rule expressions. Dispatched on the value: `myField.matches(...)`, not `string.matches(myField, ...)`. The engine routes the call based on the value's runtime type.",whenToUse:"Reach for these whenever a rule examines a string field — pattern checks, case-insensitive comparisons, trimming user input, encoding to bytes.",entries:[{signature:"string.matches(pattern: string): bool",description:"True if the string matches the given RE2 regex (full match).",examples:["allow create: if request.resource.data.email.matches('.*@example[.]com');"],notes:"Pattern is RE2 syntax, NOT JavaScript regex. No anchors needed — the match is full-string by default."},{signature:"string.lower(): string",description:"Return the string lowercased."},{signature:"string.upper(): string",description:"Return the string uppercased."},{signature:"string.trim(): string",description:"Strip leading + trailing whitespace."},{signature:"string.size(): int",description:"Length in characters (NOT bytes — use `toUtf8().size()` for byte length)."},{signature:"string.split(separator: string): list<string>",description:"Split the string into a list on `separator`."},{signature:"string.replace(old: string, new: string): string",description:"Replace all occurrences of `old` with `new`."},{signature:"string.toUtf8(): bytes",description:"Encode the string as UTF-8 bytes.",notes:"Use before hashing if the input is a string."}],examples:["allow create: if request.resource.data.slug.size() > 0 && request.resource.data.slug.size() <= 64;","allow update: if request.resource.data.kind.lower() == 'public';"],relatedKeys:["bytes","hashing","validation"]},jm={key:"list",kind:"type-methods",description:"Methods on list values — hasAll, hasAny, hasOnly, size, toSet, concat, removeAll, join. Called as `value.method(...)`.",purpose:"Methods on list values — used to check membership, compare contents, transform to sets, and concatenate. Lists in rules are ordered + finite; methods often have parallel semantics on the `set` view produced by `toSet()`.",whenToUse:'Reach for these whenever a rule examines an array field — tag membership ("user can update if their uid is in editors"), array-shape validation, or projecting to a set for difference checks.',entries:[{signature:"list.hasAll(other: list): bool",description:"True if every element of `other` is present in this list.",examples:["allow update: if request.resource.data.tags.hasAll(['public', 'reviewed']);"]},{signature:"list.hasAny(other: list): bool",description:"True if at least one element of `other` is present in this list."},{signature:"list.hasOnly(other: list): bool",description:"True if every element of THIS list is in `other` (i.e. this is a subset).",notes:'Often the right call for "no fields outside this allowlist" patterns when used with `request.resource.data.keys()`.'},{signature:"list.size(): int",description:"Number of elements."},{signature:"list.toSet(): set",description:"Convert to a Set view (de-duplicated, unordered). Useful for `difference`/`union`/`intersection` operations."},{signature:"list.concat(other: list): list",description:"Return a new list with `other` appended."},{signature:"list.removeAll(other: list): list",description:"Return a new list with every element of `other` removed."},{signature:"list.join(separator: string): string",description:"Join elements into a single string with `separator` between them."}],relatedKeys:["map","string"]},Fm={key:"map",kind:"type-methods",description:"Methods on map values — keys, values, size, get, diff. Called as `value.method(...)`.",purpose:"Methods on map values. The most common in rule code: `keys()` returns a list of map keys (combined with `list.hasAll`/`list.hasOnly` for shape checks), and `diff(other)` returns a MapDiff used to assert which fields changed across an update.",whenToUse:"Reach for these for shape validation (which keys exist), for default-aware reads (`get(key, default)`), and for diff-based immutability gates on updates.",entries:[{signature:"map.keys(): list<string>",description:"List of top-level keys in the map.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"map.values(): list",description:"List of top-level values in the map."},{signature:"map.size(): int",description:"Number of top-level keys."},{signature:"map.get(key: string, fallback: any): any",description:"Return `map[key]` if present, otherwise `fallback`. Same shape as `get(map, key, fallback)`."},{signature:"map.diff(other: map): MapDiff",description:"Return a MapDiff with `.addedKeys()`, `.removedKeys()`, `.changedKeys()`, `.affectedKeys()`, `.unchangedKeys()` methods, each returning a Set of keys.",examples:["allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['updatedAt']);"],notes:"The MapDiff result is the right surface for immutability gates — easier to read than chaining individual field-unchanged checks."}],relatedKeys:["list","lifecycle","validation"]},qm={key:"bytes",kind:"type-methods",description:"Methods on bytes values — size, toBase64, toHexString. Called as `value.method(...)`.",purpose:"Methods on Bytes values — the output of hashing operations and the storage shape for arbitrary binary payloads. Bytes also support comparison operators (<, <=, >, >=) for lexicographic ordering.",whenToUse:"Reach for these when a rule examines a Bytes field — typically a stored digest from `hashing.sha256(...)` — or when comparing two hashes for tamper-evidence.",entries:[{signature:"bytes.size(): int",description:"Number of bytes."},{signature:"bytes.toBase64(): string",description:"Padded base64url encoding of the bytes: `-` and `_` in place of `+` and `/`, with `=` padding."},{signature:"bytes.toHexString(): string",description:"Uppercase hexadecimal encoding of the bytes."}],relatedKeys:["hashing","string"]},Um={key:"path",kind:"type-methods",description:"Methods on path values — bind. Used to fill in template variables in document paths.",purpose:"Path values are the type used for cross-document references inside rules (e.g. the path passed to `get()` or `exists()`). The `bind` method substitutes template variables into a path literal.",whenToUse:"Reach for `path.bind` when a `get()` or `exists()` call needs a dynamic path with one or more template variables filled in from rule context.",entries:[{signature:"path.bind(bindings: map<string, string>): path",description:"Return a new path with template variables (`{name}`) replaced by values from `bindings`.",examples:["allow update: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/profile/main);"],notes:"In practice most rule code constructs paths inline with `$()` interpolation instead of `path.bind`. `bind` is here for completeness."}],relatedKeys:["request","resource"]},Bm={key:"request",kind:"globals",description:"Root namespace for the in-flight request — auth, resource.data, time, path, method, query. Always available, no import.",purpose:"The `request` identifier carries everything the engine knows about the current request — who is making it (`auth`), what they are sending (`resource.data`), when (`time`), and where (`path`, `method`). These are *paths*, not callables — read fields off them in rule predicates.",whenToUse:"Every non-trivial rule reads from `request` to authorize the operation. The two most common touchpoints: `request.auth` (who) and `request.resource.data` (what).",entries:[{signature:"request.auth: map | null",description:"The authenticated user. `null` for unauthenticated requests.",examples:["allow read: if request.auth != null;"]},{signature:"request.auth.uid: string",description:"The signed-in user's UID. Only safe to read after a null-check on `request.auth`.",examples:["allow update: if request.auth.uid == resource.data.ownerId;"]},{signature:"request.auth.token: map",description:"Map of custom claims set on the user's ID token (e.g. `request.auth.token.admin`).",examples:["allow delete: if request.auth.token.admin == true;"],notes:"Custom claims live under `request.auth.token.*`, NOT `request.auth.*`. Agents often emit `request.auth.admin` — that always reads `null`."},{signature:"request.resource.data: map",description:"The document data being written (create/update/set). Read it to validate what the client is sending.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"request.time: timestamp",description:"Server time of the request. Compare against document timestamps for windowed gates."},{signature:"request.path: path",description:"Path of the document being operated on (e.g. `/databases/(default)/documents/users/alice`)."},{signature:"request.method: 'get' | 'list' | 'create' | 'update' | 'delete'",description:"Which operation triggered the rule. Usually inferred from the `allow` clause, but available for fine-grained checks."},{signature:"request.query: map",description:"Query metadata for `list` requests — `limit`, `offset`, `orderBy`. Available on `allow list` rules only."}],relatedKeys:["resource","auth"]},zm={key:"resource",kind:"globals",description:"Root namespace for the existing document — use resource.data to compare against what is already there.",purpose:"The `resource` identifier is the document state BEFORE the request — what is currently stored. When the target does not exist, evaluating `resource` raises a null-value error; it is not a comparable null. On an update/delete of an existing document, it contains the pre-write data. Use it to compare incoming changes against existing values.",whenToUse:'Whenever a rule needs the pre-write state — e.g. "the existing owner is the one updating", "the field already had this value before the write".',entries:[{signature:"resource.data: map",description:"The currently stored document data. When the target does not exist, evaluating `resource` raises a null-value error.",examples:["allow update: if resource.data.ownerId == request.auth.uid;"]}],relatedKeys:["request"]},Wm={key:"auth",kind:"user-module",description:"User-authored module: authentication primitives (isAuthenticated, isOwner). Self-contained. Import via `import { isAuthenticated, isOwner } from 'auth';` (the resolver also accepts the path form `from './stdlib/auth.rules'` if you prefer).",purpose:'Two-function module covering the most common access-control predicates in any user-facing app: "is the request authenticated" and "is the request the owner of this document".',whenToUse:"Import as the first stdlib module on any project that has user-owned documents. Pairs with `validation` and `lifecycle` for full create/update/delete coverage.",entries:[{signature:"isAuthenticated(): bool",cost:{min:5,max:5},reads:0,description:"`request.auth != null`."},{signature:"isOwner(userId: string): bool",cost:{min:7,max:13},reads:0,description:"`request.auth.uid == userId`. Pass a field path like `resource.data.ownerId`.",examples:["allow update: if isAuthenticated() && isOwner(resource.data.ownerId);"]}],examples:[`rules_version = '2+modules';
|
|
1693
1693
|
import { isAuthenticated } from 'auth';
|
|
1694
1694
|
|
|
1695
1695
|
service cloud.firestore {
|
|
1696
1696
|
match /databases/{db}/documents {
|
|
1697
1697
|
match /posts/{id} { allow read: if isAuthenticated(); }
|
|
1698
1698
|
}
|
|
1699
|
-
}`],relatedKeys:["validation","lifecycle","membership"]},Um={key:"validation",kind:"user-module",description:"User-authored module: shape validation (hasRequired, hasOnly). Self-contained. Import via `import { hasRequired, hasOnly } from 'validation';` after `rules_version = '2+modules';`.",purpose:'Field-shape predicates: "the incoming doc has all these fields" and "the incoming doc has only these fields". Layered on top of `request.resource.data.keys()` so the agent does not have to remember the list-method idioms.',whenToUse:"Reach for `validation` on every `create` allow rule to gate field shape — and on `update` rules when the schema is strict.",entries:[{signature:"hasRequired(fields: list<string>): bool",cost:{min:7,max:7},reads:0,description:"`request.resource.data.keys().hasAll(fields)`."},{signature:"hasOnly(fields: list<string>): bool",cost:{min:7,max:7},reads:0,description:"`request.resource.data.keys().hasOnly(fields)`.",examples:["allow create: if hasRequired(['title','body']) && hasOnly(['title','body','tags']);"]},{signature:"validString(field: string, min: int, max: int): bool",cost:{min:10,max:28},reads:0,description:"The incoming field is a string with size in [min, max] (inclusive). A missing field is an error under dynamic access, so the call denies; guard an optional field with `!('title' in request.resource.data) || validString('title', 1, 80)`.",examples:["allow create: if validString('title', 1, 100);"]},{signature:"isOneOf(field: string, values: list): bool",cost:{min:8,max:8},reads:0,description:"Enum check: the incoming field value is in the allowed list (`request.resource.data[field] in values`). The rules idiom for what JS would write as `.includes()` — which does not exist here.",examples:["allow create: if isOneOf('status', ['draft', 'published']);"]}],relatedKeys:["map","lifecycle","content"]},Bm={key:"lobby",kind:"user-module",description:"User-authored module: lobby lifecycle (validCreate, validJoin, canCancel, validRematch) for two-player game sessions. Self-contained; validRematch reads the finished match with one get().",purpose:"Convention-based lifecycle for game lobbies — assumes the document has `host`, `guest`, and `status` fields. Encapsulates the rules for opening a lobby, joining as the second player, cancelling, and opening a rematch of a finished match ('won', 'draw' or 'resigned').",whenToUse:"Reach for `lobby` on games with a join-then-start flow. The convention names are load-bearing — if your schema differs, fork these functions rather than try to remap.",entries:[{signature:"validCreate(): bool",cost:{min:8,max:31},reads:0,description:'Host is the auth user, guest is empty, status is "waiting".'},{signature:"validJoin(): bool",cost:{min:10,max:57},reads:0,description:'Guest slot is empty, joiner is not the host, status transitions to "playing".'},{signature:"canCancel(): bool",cost:{min:7,max:21},reads:0,description:'Status is "waiting" and the requester is the host.'},{signature:"validRematch(previousPath: path): bool",cost:{min:14,max:55},reads:1,description:"The match at `previousPath` is finished ('won', 'draw' or 'resigned') and seated the caller as host or guest; the new match has the caller as host, guest '' and status 'waiting'.",examples:["allow create: if validRematch(/databases/$(database)/documents/matches/$(request.resource.data.rematchOf));"],notes:"Either seat can ask, so the seats swap when the guest asks. The other player takes the open seat through validJoin, which does not check that they held a seat in the finished match. A missing previous match is an error and denies the request. The `let` that holds the `get()` is evaluated before the auth check, so a signed-out request also pays for the `get()`."}],relatedKeys:["turns","state","transitions","results"]},zm={key:"turns",kind:"user-module",description:"User-authored module: turn enforcement for two-player games (isMyTurn, turnFlipped) and games with a seat list (isSeatTurn, turnAdvanced). Self-contained.",purpose:"Convention-based turn handling. Two-seat docs have `host`, `guest`, and `currentTurn` fields. Seat-list docs have `players`, a list of UIDs in turn order, and `turn`, the int index of the seat on turn. Asserts the request is from the current player and that the turn moves to the next seat across writes.",whenToUse:"Reach for `turns` on any turn-based game where exactly one player can act per state: isMyTurn and turnFlipped for two named seats, isSeatTurn and turnAdvanced for a seat list of any size.",entries:[{signature:"isMyTurn(): bool",cost:{min:16,max:23},reads:0,description:"Current player matches the auth uid (matches against `host` or `guest`)."},{signature:"turnFlipped(): bool",cost:{min:15,max:22},reads:0,description:"After the write, `currentTurn` has switched from host to guest (or vice-versa)."},{signature:"isSeatTurn(seats: list, turnIndex: int): bool",cost:{min:6,max:14},reads:0,description:"The caller is signed in and their uid is `seats[turnIndex]`. An index past the last seat, or below 0, is an error and denies the request.",examples:["allow update: if isSeatTurn(resource.data.players, resource.data.turn);"]},{signature:"turnAdvanced(seatCount: int): bool",cost:{min:14,max:23},reads:0,description:"The new `turn` is the old `turn` plus one modulo `seatCount` (production's `%` on ints), so the last seat wraps to seat 0, and `players` is unchanged.",examples:["allow update: if turnAdvanced(resource.data.players.size());"]}],relatedKeys:["lobby","state","transitions"]},Wm={key:"state",kind:"user-module",description:"User-authored module: game state tracking (isPlaying, moveIncremented, participantsUnchanged). Self-contained.",purpose:"Mid-game state predicates: the game is in play, the move counter incremented by exactly one, the participant list did not change.",whenToUse:"Reach for `state` on per-move updates to assert the move actually advanced the game and did not change the players.",entries:[{signature:"isPlaying(): bool",cost:{min:6,max:6},reads:0,description:'`resource.data.status == "playing"`.'},{signature:"moveIncremented(): bool",cost:{min:11,max:11},reads:0,description:"`request.resource.data.moveCount == resource.data.moveCount + 1`."},{signature:"participantsUnchanged(): bool",cost:{min:10,max:19},reads:0,description:"Host and guest fields are identical pre- and post-write."}],relatedKeys:["turns","lifecycle","transitions"]},Vm={key:"results",kind:"user-module",description:"User-authored module: how a two-player game ends (resignedBy, finishedWithWinner, resultUnchanged). Imports onlyFieldsChanged and immutableFields from lifecycle, statusIs and newStatusIs from transitions.",purpose:"Result writes on docs with `host`, `guest`, `status` and `winner` fields. `status` is 'playing' while in play and names how the game ended once finished: 'won' with the winning seat in `winner`, 'draw' with `winner` '', or 'resigned' with the other seat in `winner`. There is no separate reason field.",whenToUse:"Reach for `results` on the update rule of a turn-based game: resignedBy for the resign button, finishedWithWinner for a write that only records the result, and resultUnchanged on every other update so a move cannot rewrite the result.",entries:[{signature:"resignedBy(seat: string): bool",cost:{min:10,max:72},reads:0,description:"The caller holds `seat` ('host' or 'guest'), status goes from 'playing' to 'resigned', `winner` is the other seat, and only status and winner change.",examples:["allow update: if resignedBy(request.auth.uid == resource.data.host ? 'host' : 'guest');"]},{signature:"finishedWithWinner(winner: string, reason: string): bool",cost:{min:14,max:61},reads:0,description:"Status goes from 'playing' to `reason`, 'won' or 'draw'; `winner` is 'host' or 'guest' for 'won' and '' for 'draw'; only status and winner change.",examples:["allow update: if finishedWithWinner('host', 'won') || finishedWithWinner('', 'draw');"],notes:"The caller is not checked: compose it with the rule that decides who may record a result. Resignations go through resignedBy."},{signature:"resultUnchanged(): bool",cost:{min:14,max:14},reads:0,description:"Status and winner are unchanged by the write."}],relatedKeys:["state","turns","lobby","lifecycle","transitions"]},Gm={key:"fairness",kind:"user-module",description:"User-authored module: commit-reveal fairness (commitmentMatches, digestByte). Self-contained.",purpose:"Hidden choices and shared randomness: a player stores `commit`, the uppercase hex SHA-256 of a secret salt, before the other players add their input, then reveals `salt`. commitmentMatches checks the reveal against the commitment, and digestByte derives values such as die faces from a digest.",whenToUse:"Reach for `fairness` on the reveal write of a commit-reveal game: dice, card draws, or a hidden move that must not change after the other players act.",entries:[{signature:"commitmentMatches(commitment: string, salt: string): bool",cost:{min:6,max:16},reads:0,description:"`salt` is a non-empty string and `hashing.sha256(salt).toHexString()` equals `commitment`.",examples:["allow update: if commitmentMatches(resource.data.commit, request.resource.data.salt);"],notes:"The commitment is the uppercase hex string, not Bytes: a commitment stored as Bytes or as lowercase hex does not match."},{signature:"digestByte(digest: Bytes, index: int): int",cost:{min:63,max:63},reads:0,description:"Byte `index` of `digest` as an int from 0 to 255. An index outside the digest, or a digest that is not Bytes, is an error, so the rule denies.",examples:["allow update: if request.resource.data.die == digestByte(hashing.sha256(request.resource.data.salt + resource.data.nonce), 0) % 6 + 1;"],notes:"Production Bytes have no index operator, so the byte is read from `toHexString()` through a 16-entry lookup map on every call. `% 6 + 1` gives faces 1 to 4 a 43 in 256 chance and faces 5 and 6 a 42 in 256 chance."}],relatedKeys:["hashing","bytes","turns","results"]},Hm={key:"membership",kind:"user-module",description:"User-authored module: claims + role-based access (hasClaim, hasClaimRole, isMemberOf, hasRole). Self-contained.",purpose:'Two halves: claim-based checks against the auth token, and role checks against a `members` map on a document. The module is the right cover for "team-style" apps where each doc has a participant map.',whenToUse:"Reach for `membership` whenever a rule gates on a custom claim (`request.auth.token.admin`) or on a role inside a participant map.",entries:[{signature:"hasClaim(claim: string): bool",cost:{min:6,max:14},reads:0,description:"Auth token has a non-null value for the named claim."},{signature:"hasClaimRole(claim: string, role: string): bool",cost:{min:6,max:14},reads:0,description:"Auth token claim equals the named role value."},{signature:"isMemberOf(membersMap: map): bool",cost:{min:6,max:12},reads:0,description:"Auth uid is a key in the members map."},{signature:"hasRole(membersMap: map, role: string): bool",cost:{min:6,max:14},reads:0,description:"Auth uid is in the members map with the named role."}],relatedKeys:["auth","request"]},Km={key:"lifecycle",kind:"user-module",description:"User-authored module: field immutability, changed-field checks, and server-timestamp checks (fieldUnchanged, immutableFields, onlyFieldsChanged, exactlyChanged, nFieldsChanged, isServerTimestamp). Self-contained.",purpose:"Locks specific fields against modification on updates and asserts that a timestamp field matches `request.time` (i.e. the client used the server-timestamp sentinel).",whenToUse:"Reach for `lifecycle` on every update rule to lock identity fields (`createdAt`, `ownerId`) and to enforce server-set timestamps.",entries:[{signature:"fieldUnchanged(field: string): bool",cost:{min:11,max:11},reads:0,description:"The named field is byte-identical before and after the write."},{signature:"immutableFields(fields: list<string>): bool",cost:{min:10,max:10},reads:0,description:"All listed fields are unchanged. Implemented via MapDiff so it is cheaper than chaining `fieldUnchanged` calls."},{signature:"isServerTimestamp(field: string): bool",cost:{min:9,max:9},reads:0,description:"The named field equals `request.time` (i.e. the client wrote `FieldValue.serverTimestamp()`)."},{signature:"onlyFieldsChanged(fields: list<string>): bool",cost:{min:10,max:10},reads:0,description:"The dual of immutableFields: every CHANGED field is in the allowed list, so unlisted fields are implicitly immutable (adds and removes count as changes). The most common update guard: users may edit title and body and nothing else. Top-level keys only; nested-map diffs are unreliable in production.",examples:["allow update: if onlyFieldsChanged(['title', 'body']);"]},{signature:"nFieldsChanged(n: int): bool",cost:{min:11,max:11},reads:0,description:"Exactly n top-level fields changed in this write. `nFieldsChanged(1)` is the board-integrity / edit-one-field-per-write guard."},{signature:"exactlyChanged(keys: list<string> | set<string>): bool",cost:{min:13,max:17},reads:0,description:"The top-level fields the write adds, removes, or changes are exactly `keys`: every listed field changed and no other field did. `onlyFieldsChanged` is the subset form, where a listed field may stay unchanged.",examples:["allow update: if exactlyChanged(['board', 'lastMove', 'currentTurn', 'moveCount']);"],notes:"Use it for a transition that always writes the same fields, such as a tic-tac-toe move. Reads `resource.data`, so on create the call is an error and the rule denies."}],relatedKeys:["map","validation","request","counters"]},Zm={key:"transitions",kind:"user-module",description:"User-authored module: state-machine transitions (validTransition, statusIs, newStatusIs). Self-contained.",purpose:"Asserts that a field moves from one specific value to another specific value on a write. Use to encode state-machine edges directly in rules.",whenToUse:"Reach for `transitions` whenever a rule encodes a state machine — order: pending → paid → shipped, etc.",entries:[{signature:"validTransition(field: string, from: string, to: string): bool",cost:{min:8,max:16},reads:0,description:"Field was `from` before and is `to` after."},{signature:"statusIs(field: string, value: string): bool",cost:{min:7,max:7},reads:0,description:"Pre-write field equals `value`."},{signature:"newStatusIs(field: string, value: string): bool",cost:{min:8,max:8},reads:0,description:"Post-write field equals `value`."}],relatedKeys:["state","lifecycle"]},Jm={key:"geometry",kind:"user-module",description:"User-authored module: movement validation via config-doc lookup (validSimpleMove, validJumpMove) and named squares such as 'e4' on an 8 by 8 board (file, rank, step, inBounds). The config-doc functions take the config from a `get()` call.",purpose:"Board-game movement rules expressed as lookups in a config document, `cfg.moves[piece][from][to]` for simple moves and `cfg.jumps[piece][from][to]` for jumps (with captured-cell info), or as arithmetic on square names: file letter 'a' to 'h', then rank digit '1' to '8'. The module is \"explicit parameter\" style: no implicit reads. The caller passes the config and the squares explicitly.",whenToUse:"Reach for `geometry` on grid-based games (chess, checkers, go variants). Pair the config-doc functions with a `get()` on your config document. Use the named-square functions when the board is a map keyed by square names; check a client-written square with `inBounds` before you read it.",entries:[{signature:"validSimpleMove(cfg: map): bool",cost:{min:26,max:26},reads:0,description:"`cfg.moves[piece][from][to] == true`."},{signature:"validJumpMove(cfg: map): bool",cost:{min:31,max:31},reads:0,description:"`cfg.jumps[piece][from][to] == capturedCell`."},{signature:"file(square: string): int",cost:{min:23,max:23},reads:0,description:"The square's file as a number: 'a' is 1 and 'h' is 8.",examples:["allow update: if file(request.resource.data.to) - file(resource.data.from) == 1;"],notes:"A first character outside 'a' to 'h', an empty string, or a non-string square is an error, which denies. Costs the same as the map lookup written inline."},{signature:"rank(square: string): int",cost:{min:6,max:6},reads:0,description:"The square's rank as a number: the second character read as a digit.",examples:["allow update: if rank(request.resource.data.to) == 8;"],notes:"Reads only the second character, so `rank('e9')` is 9 and `rank('e44')` is 4: check the square with `inBounds` first. A non-digit second character, a square shorter than two characters, or a non-string square is an error, which denies."},{signature:"step(square: string, df: int, dr: int): string",cost:{min:49,max:49},reads:0,description:"The square `df` files and `dr` ranks away from `square`, as a name.",examples:["allow update: if request.resource.data.to == step(resource.data.from, 1, 1);"],notes:"`step(from, df, dr) == to` costs 51, where the same test written as file and rank differences costs 53 to 71. A step off the board in any direction is an error, which denies. To test for any one diagonal neighbor, compare file and rank differences instead of calling `step` four times."},{signature:"inBounds(square: any): bool",cost:{min:5,max:9},reads:0,description:"The value is a string of one file letter 'a' to 'h' and one rank digit '1' to '8'.",examples:["allow update: if inBounds(request.resource.data.to);"],notes:"Anything else, a non-string included, is false rather than an error."}],relatedKeys:["transitions","state"]},Qm={key:"counters",kind:"user-module",description:"User-authored module: denormalized numeric integrity and best scores (incrementedBy, changedBy, boundedNumber, improvedBy). Self-contained.",purpose:"Keeps client-maintained counts honest: likes, votes, moves, quantities may only change by a known step, stay within known bounds, or move strictly one way. Generalizes the state module's moveIncremented() (hardcoded to moveCount) to any field.",whenToUse:"Reach for `counters` whenever a numeric field is client-written but semantically constrained: vote/like toggles (`changedBy(f, -1, 1)`), move counters (`incrementedBy(f, 1)`), ratings (`boundedNumber(f, 1, 5)`), best scores that only get better (`improvedBy(f, 'up', [...])`).",entries:[{signature:"incrementedBy(field: string, n: int): bool",cost:{min:13,max:13},reads:0,description:"The field changed by EXACTLY n vs the existing document (n may be negative). Update rules only.",examples:["allow update: if incrementedBy('moveCount', 1);"]},{signature:"changedBy(field: string, min: int, max: int): bool",cost:{min:14,max:27},reads:0,description:"The field's delta is within [min, max] inclusive; a zero delta passes when the range spans 0.",examples:["allow update: if changedBy('likeCount', -1, 1);"]},{signature:"boundedNumber(field: string, min: number, max: number): bool",cost:{min:19,max:35},reads:0,description:"The incoming value is an int or float within [min, max]. A missing field is an error under dynamic access, so the call denies.",examples:["allow write: if boundedNumber('rating', 1, 5);"]},{signature:"improvedBy(field: string, direction: 'up' | 'down', mayChange: list<string>): bool",cost:{min:18,max:50},reads:0,description:"The numeric field moved strictly in `direction` (`up`: new > old, `down`: new < old) and every other changed top-level field is in `mayChange`. Both values must be an int or a float; they compare by value.",examples:["allow update: if improvedBy('score', 'up', ['solve']);",`allow update: if improvedBy('moves', 'down', ['pushes', 'solve'])
|
|
1700
|
-
|| improvedBy('pushes', 'down', ['solve']);`],notes:"A listed field may stay unchanged. An unchanged or worse value, a non-numeric or missing value on either side, an unlisted field added, removed, or changed, and a direction other than `up` or `down` deny. For a score ranked on two fields, call it once per field: the second call leaves the first field out of `mayChange`, so it allows fewer pushes only on as many moves. Write the score's type, bounds, and owner checks beside it. Reads `resource.data`, so on create the call is an error and the rule denies."}],relatedKeys:["lifecycle","state"]},Ym={key:"timing",kind:"user-module",description:"User-authored module: cooldown / rate-limit enforcement (cooldownElapsed). Self-contained. Live-verified against the production engine.",purpose:"Rules CAN rate-limit: compare `request.time` against a stored server timestamp with duration arithmetic. Enforces a minimum interval between writes to a document.",whenToUse:"Reach for `timing` to throttle per-document writes — game move intervals, post cooldowns, retry backoff. ALWAYS pair with lifecycle's `isServerTimestamp(field)` on the same write so the stored timestamp cannot be forged by the client. Per-document intervals only; sliding-window quotas need a counter document plus this guard.",entries:[{signature:"cooldownElapsed(field: string, seconds: int): bool",cost:{min:12,max:12},reads:0,description:"`request.time > resource.data[field] + duration.value(seconds, 's')` — the stored timestamp is STRICTLY older than the window. Update rules only (needs `resource`); a missing or non-timestamp field errors, which denies (fail-closed).",examples:["allow update: if cooldownElapsed('lastMoveAt', 2) && isServerTimestamp('lastMoveAt');"]}],relatedKeys:["lifecycle","timestamp","duration"]},Xm={key:"content",kind:"user-module",description:"User-authored module: author-owned documents (validAuthorCreate, isAuthor, canReadContent, notDeleted) and hidden per-player documents (ownerOnlyUntil). Self-contained; ownerOnlyUntil reads the parent match with one get(). Field names are parameters, not conventions.",purpose:"The most common Firebase app shape — posts, notes, docs, comments, tasks. Covers the create/read/update/delete lifecycle of documents that belong to their author, with draft/published visibility and soft delete.",whenToUse:"Reach for `content` on any collection whose documents have an author/owner field. Compose with lifecycle.onlyFieldsChanged to keep authorship immutable on edits.",entries:[{signature:"validAuthorCreate(authorField: string): bool",cost:{min:6,max:16},reads:0,description:"Create guard: signed in AND the incoming doc's author field is the caller's uid.",examples:["allow create: if validAuthorCreate('author');"]},{signature:"isAuthor(authorField: string): bool",cost:{min:6,max:15},reads:0,description:"The caller is the EXISTING document's author. Update/delete rules.",examples:["allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body']);"]},{signature:"canReadContent(statusField: string, authorField: string): bool",cost:{min:8,max:23},reads:0,description:"Published content is public; anything else is visible to its author only. `get` rules — a bare collection `list` will be denied unless the query proves `status == 'published'` via filters (rules are not filters).",examples:["allow read: if canReadContent('status', 'author') && notDeleted();"]},{signature:"notDeleted(): bool",cost:{min:8,max:8},reads:0,description:"Soft-delete guard: `resource.data.get('deleted', false) != true`. `get()` returns the default for a missing key, so a document WITHOUT the field passes. Dotted or bracket access of a missing key is an error in production and would deny it."},{signature:"ownerOnlyUntil(parentPath: path, ownerUid: string, statuses: list): bool",cost:{min:6,max:20},reads:1,description:"Read rule for a hidden per-player document under a match: the owner reads it at any time, and any other signed-in caller reads it once the match at `parentPath` has a `status` in `statuses`.",examples:["allow read: if ownerOnlyUntil(/databases/$(database)/documents/battleship/$(matchId), uid, ['won', 'resigned']);"],notes:"The document lives at {collection}/{matchId}/{sub}/{uid}. Pass the `uid` wildcard as the owner when the document id is the owner's UID, or `resource.data.<field>` when the owner is a field. Pass one status as a one-item list, such as ['finished']. The owner check runs before the `get()`, so the owner's read spends no read; everyone else pays one `get()` of the parent. A missing parent match is an error and denies every caller but the owner."}],relatedKeys:["auth","lifecycle","validation"]},eg={key:"spaces",kind:"user-module",description:"User-authored module: cross-document membership gating (isSpaceMember, hasSpaceRole, validMemberCreate). Explicit param — pass the parent doc data from a get(). Live-verified against the production engine.",purpose:"Shared spaces — teams, rooms, groups, projects, parties: a PARENT document's members field gates its children. The second-most-common app shape after author-owned content.",whenToUse:"Reach for `spaces` whenever a subcollection is gated by a parent doc. Define ONE helper in the child match block — `function space() { return get(/databases/$(database)/documents/spaces/$(spaceId)).data; }` — and pass it to every function: get() is cached per request, so all rules on the request share a single read of the 10-get budget. Do NOT inline a get() per allow clause.",entries:[{signature:"isSpaceMember(spaceData: map): bool",cost:{min:6,max:13},reads:0,description:"The caller's uid is in `spaceData.members`. `in` covers BOTH shapes: list membership (`members: ['a','b']`) and map keys (`members: {a: 'admin'}`). Missing field / non-member / missing parent doc all fail closed.",examples:["allow read: if isSpaceMember(space());"]},{signature:"hasSpaceRole(spaceData: map, role: string): bool",cost:{min:6,max:15},reads:0,description:"The caller's role in a MAP-shaped members field equals `role` (`spaceData.members[request.auth.uid] == role`). List-shaped members carry no roles — denies.",examples:["allow delete: if hasSpaceRole(space(), 'admin');"]},{signature:"validMemberCreate(spaceData: map, authorField: string): bool",cost:{min:9,max:26},reads:0,description:`Member-gated authored create: caller is a member AND the incoming child doc's author field is the caller. The "post a message / add a task" guard.`,examples:["allow create: if validMemberCreate(space(), 'author');"]}],relatedKeys:["membership","content","builtins"]},tg={key:"joining",kind:"user-module",description:"User-authored module: safe self-service membership changes (onlyAddedSelf, onlyRemovedSelf). Self-contained. Live-verified against the production engine.",purpose:"How membership CHANGES without an admin backend: users join and leave a MAP-shaped members field (uid -> role) with zero privilege escalation — no self-granted roles, no touching other members, no-op writes denied.",whenToUse:"Reach for `joining` on the PARENT doc's update rule wherever spaces gates the children. ALWAYS compose with lifecycle's onlyFieldsChanged(['members']) so a join/leave write cannot modify anything else on the doc. Invite-doc consumption (single-use invites) is a Pattern, not a function — it needs a batch write + getAfter().",entries:[{signature:"onlyAddedSelf(membersField: string, role: string): bool",cost:{min:20,max:53},reads:0,description:"The write adds EXACTLY the caller to the members map at EXACTLY `role` — changing nobody, removing nobody; a no-op write denies (uses set equality `diff.addedKeys() == [uid].toSet()`, not hasOnly, which passes on an empty diff). Update rules only.",examples:["allow update: if onlyFieldsChanged(['members']) && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));"]},{signature:"onlyRemovedSelf(membersField: string): bool",cost:{min:19,max:40},reads:0,description:"The write removes EXACTLY the caller — adding nobody, changing nobody. Self-service leave. Update rules only."}],relatedKeys:["spaces","lifecycle","membership"]},ng={key:"atomic",kind:"user-module",description:"User-authored module: cross-document BATCH-write integrity via get()/getAfter() (companionChangedBy, consumedFlag). Explicit param. Live-verified against a real production database.",purpose:"Rules that require a COMPANION write in the same atomic batch: denormalized counters (create task + increment team.taskCount), single-use invite consumption (join + mark invite used), paired documents. getAfter(path) returns the post-batch state of another doc in the batch; for docs not in the batch it equals get(path).",whenToUse:"Reach for `atomic` when two documents must change together. Define before()/after() helpers — `get(path).data` and `getAfter(path).data` for the SAME companion path — and pass both. Every write in a batch is rules-evaluated: the companion write needs its own allow rule. The client must use a batch/transaction (writeBatch / runTransaction); solo writes deny by construction.",entries:[{signature:"companionChangedBy(before: map, after: map, field: string, n: int): bool",cost:{min:10,max:10},reads:0,description:"The companion doc's field changed by EXACTLY n in this batch (`after[field] == before[field] + n`). A solo write denies: without a companion write, getAfter == get, so the delta is 0.",examples:["allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);"]},{signature:"consumedFlag(before: map, after: map, flagField: string): bool",cost:{min:7,max:13},reads:0,description:"A single-use flag was consumed IN THIS BATCH: pre-batch false AND post-batch true. Replays deny (already true before the batch); solo writes deny (false != true when getAfter == get). Pair with an allow rule on the flag doc itself (e.g. invitee-only, resource.used == false).",examples:["allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');"]}],relatedKeys:["counters","joining","spaces","builtins"]},sg={key:"storage/uploads",kind:"user-module",description:"Storage module: inclusive upload-size limits and declared MIME metadata allowlists.",purpose:"Apply bounded upload policies to the incoming Storage object. MIME helpers inspect declared metadata; they do not inspect or authenticate the uploaded bytes.",whenToUse:"Use for Storage create or update rules that limit object size or accepted content-type metadata.",entries:[{signature:"sizeAtMost(maxBytes: int): bool",cost:{min:6,max:6},reads:0,description:"The incoming object size is at most the inclusive byte limit."},{signature:"sizeBetween(minBytes: int, maxBytes: int): bool",cost:{min:7,max:13},reads:0,description:"The incoming object size is inside the inclusive byte range."},{signature:"contentTypeMatches(pattern: string): bool",cost:{min:6,max:6},reads:0,description:"The incoming content-type metadata matches the entire RE2 pattern.",notes:"This checks declared metadata, not the uploaded bytes."},{signature:"contentTypeIsOneOf(types: list): bool",cost:{min:6,max:6},reads:0,description:"The incoming content-type metadata equals one allowlisted value.",notes:"This checks declared metadata, not the uploaded bytes."}],relatedKeys:["auth","membership","storage/metadata","storage/objects"]},rg={key:"storage/metadata",kind:"user-module",description:"Storage module: required custom metadata, bounded string values, and metadata ownership.",purpose:"Validate the flat string map in Storage custom metadata and connect incoming or existing ownership metadata to the authenticated UID.",whenToUse:"Use when object paths alone do not carry every upload invariant and custom metadata must be present, bounded, or owner-bound.",entries:[{signature:"hasRequiredMetadata(keys: list): bool",cost:{min:7,max:7},reads:0,description:"The incoming custom metadata contains every required key."},{signature:"metadataString(key: string, min: int, max: int): bool",cost:{min:28,max:28},reads:0,description:"The incoming metadata value is a string within the inclusive size range."},{signature:"incomingMetadataOwner(key: string): bool",cost:{min:6,max:16},reads:0,description:"The incoming metadata value equals the authenticated UID."},{signature:"existingMetadataOwner(key: string): bool",cost:{min:6,max:15},reads:0,description:"The existing metadata value equals the authenticated UID."}],relatedKeys:["auth","membership","storage/uploads","storage/objects"]},ig={key:"storage/objects",kind:"user-module",description:"Storage module: distinguish create, update, and delete operations safely, read segments of the object name, and tie an object to the Firestore document that names it.",purpose:"Branch Storage authorization by request method without relying on missing resource bindings or null checks, and check an object by its name: one segment at a time, or against a field of a Firestore document.",whenToUse:"Use when create, update, and delete require different ownership or validation checks, when the object name carries an owner or key, or when an upload is allowed only once a Firestore document names it.",entries:[{signature:"isCreate(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'create'."},{signature:"isUpdate(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'update'."},{signature:"isDelete(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'delete'."},{signature:"nameSegment(index: int): string",cost:{min:17,max:18},reads:0,description:"Segment `index` of the object name split on '/', counting from 0. The name is `request.resource.name` on create and update and `resource.name` on get and delete.",examples:["allow create: if nameSegment(1) == request.auth.uid;"],notes:"An index past the last segment is an error that denies the request, and a name with no '/' has one segment. A create may have no stored object, and a get or delete carries no incoming object, so the name comes from the binding each operation has."},{signature:"matchesDocument(path: path, field: string): bool",cost:{min:6,max:26},reads:1,description:"The caller is signed in, and the Firestore document at `path` exists and its `field` equals the object name.",examples:["allow create: if matchesDocument(/databases/(default)/documents/scores/$(request.auth.uid), 'object');"],notes:"Each call reads one document. A Storage rule reads at most two distinct Firestore documents, so a rule may call matchesDocument at most twice with different paths; a third distinct document denies the request. A missing document or field is an error that denies the request. The lookup reads the (default) database."}],relatedKeys:["auth","membership","storage/uploads","storage/metadata"]},og={key:"storage/time",kind:"user-module",description:"Storage module: strict freshness windows over server-owned object timestamps.",purpose:"Check whether an existing Storage object was created or updated within a bounded number of seconds.",whenToUse:"Use for access policies whose validity expires relative to an existing object timestamp.",entries:[{signature:"createdWithin(seconds: int): bool",cost:{min:10,max:10},reads:0,description:"Request time is strictly before creation time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."},{signature:"updatedWithin(seconds: int): bool",cost:{min:10,max:10},reads:0,description:"Request time is strictly before update time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."}],relatedKeys:["storage/objects","auth","membership"]};function ag(t){if(t.kind!=="user-module")return["firestore"];const e=Eo[t.key];return e?e.map(n=>n==="firebase.storage"?"storage":"firestore"):["firestore"]}const cg=[xm,Cm,Om,Tm,Rm,Lm,Nm,Mm,Dm,$m,Pm,jm,Fm,qm,Um,Bm,zm,Wm,Vm,Gm,Hm,Km,Zm,Jm,Qm,Ym,Xm,eg,tg,ng,sg,rg,ig,og].map(t=>({...t,services:ag(t)}));function xl(t){return JSON.stringify([t.parameters,t.lets.map(e=>[e.name,se(e.value)]),se(t.body)])}let Jr=null;function ug(){if(Jr)return Jr;const t=new Map;for(const e of cg){if(e.kind!=="user-module")continue;const n=e.entries.map(a=>a.signature.slice(0,a.signature.indexOf("("))),s=e.services.includes("firestore")?"service cloud.firestore { match /databases/{database}/documents { } }":"service firebase.storage { match /b/{bucket}/o { } }",r=_m(`rules_version = '2+modules';
|
|
1699
|
+
}`],relatedKeys:["validation","lifecycle","membership"]},Vm={key:"validation",kind:"user-module",description:"User-authored module: shape validation (hasRequired, hasOnly). Self-contained. Import via `import { hasRequired, hasOnly } from 'validation';` after `rules_version = '2+modules';`.",purpose:'Field-shape predicates: "the incoming doc has all these fields" and "the incoming doc has only these fields". Layered on top of `request.resource.data.keys()` so the agent does not have to remember the list-method idioms.',whenToUse:"Reach for `validation` on every `create` allow rule to gate field shape — and on `update` rules when the schema is strict.",entries:[{signature:"hasRequired(fields: list<string>): bool",cost:{min:7,max:7},reads:0,description:"`request.resource.data.keys().hasAll(fields)`."},{signature:"hasOnly(fields: list<string>): bool",cost:{min:7,max:7},reads:0,description:"`request.resource.data.keys().hasOnly(fields)`.",examples:["allow create: if hasRequired(['title','body']) && hasOnly(['title','body','tags']);"]},{signature:"validString(field: string, min: int, max: int): bool",cost:{min:10,max:28},reads:0,description:"The incoming field is a string with size in [min, max] (inclusive). A missing field is an error under dynamic access, so the call denies; guard an optional field with `!('title' in request.resource.data) || validString('title', 1, 80)`.",examples:["allow create: if validString('title', 1, 100);"]},{signature:"isOneOf(field: string, values: list): bool",cost:{min:8,max:8},reads:0,description:"Enum check: the incoming field value is in the allowed list (`request.resource.data[field] in values`). The rules idiom for what JS would write as `.includes()` — which does not exist here.",examples:["allow create: if isOneOf('status', ['draft', 'published']);"]}],relatedKeys:["map","lifecycle","content"]},Gm={key:"lobby",kind:"user-module",description:"User-authored module: lobby lifecycle (validCreate, validJoin, canCancel, validRematch) for two-player game sessions. Self-contained; validRematch reads the finished match with one get().",purpose:"Convention-based lifecycle for game lobbies — assumes the document has `host`, `guest`, and `status` fields. Encapsulates the rules for opening a lobby, joining as the second player, cancelling, and opening a rematch of a finished match ('won', 'draw' or 'resigned').",whenToUse:"Reach for `lobby` on games with a join-then-start flow. The convention names are load-bearing — if your schema differs, fork these functions rather than try to remap.",entries:[{signature:"validCreate(): bool",cost:{min:8,max:31},reads:0,description:'Host is the auth user, guest is empty, status is "waiting".'},{signature:"validJoin(): bool",cost:{min:10,max:57},reads:0,description:'Guest slot is empty, joiner is not the host, status transitions to "playing".'},{signature:"canCancel(): bool",cost:{min:7,max:21},reads:0,description:'Status is "waiting" and the requester is the host.'},{signature:"validRematch(previousPath: path): bool",cost:{min:14,max:55},reads:1,description:"The match at `previousPath` is finished ('won', 'draw' or 'resigned') and seated the caller as host or guest; the new match has the caller as host, guest '' and status 'waiting'.",examples:["allow create: if validRematch(/databases/$(database)/documents/matches/$(request.resource.data.rematchOf));"],notes:"Either seat can ask, so the seats swap when the guest asks. The other player takes the open seat through validJoin, which does not check that they held a seat in the finished match. A missing previous match is an error and denies the request. The `let` that holds the `get()` is evaluated before the auth check, so a signed-out request also pays for the `get()`."}],relatedKeys:["turns","state","transitions","results"]},Hm={key:"turns",kind:"user-module",description:"User-authored module: turn enforcement for two-player games (isMyTurn, turnFlipped) and games with a seat list (isSeatTurn, turnAdvanced). Self-contained.",purpose:"Convention-based turn handling. Two-seat docs have `host`, `guest`, and `currentTurn` fields. Seat-list docs have `players`, a list of UIDs in turn order, and `turn`, the int index of the seat on turn. Asserts the request is from the current player and that the turn moves to the next seat across writes.",whenToUse:"Reach for `turns` on any turn-based game where exactly one player can act per state: isMyTurn and turnFlipped for two named seats, isSeatTurn and turnAdvanced for a seat list of any size.",entries:[{signature:"isMyTurn(): bool",cost:{min:16,max:23},reads:0,description:"Current player matches the auth uid (matches against `host` or `guest`)."},{signature:"turnFlipped(): bool",cost:{min:15,max:22},reads:0,description:"After the write, `currentTurn` has switched from host to guest (or vice-versa)."},{signature:"isSeatTurn(seats: list, turnIndex: int): bool",cost:{min:6,max:14},reads:0,description:"The caller is signed in and their uid is `seats[turnIndex]`. An index past the last seat, or below 0, is an error and denies the request.",examples:["allow update: if isSeatTurn(resource.data.players, resource.data.turn);"]},{signature:"turnAdvanced(seatCount: int): bool",cost:{min:14,max:23},reads:0,description:"The new `turn` is the old `turn` plus one modulo `seatCount` (production's `%` on ints), so the last seat wraps to seat 0, and `players` is unchanged.",examples:["allow update: if turnAdvanced(resource.data.players.size());"]}],relatedKeys:["lobby","state","transitions"]},Km={key:"state",kind:"user-module",description:"User-authored module: game state tracking (isPlaying, moveIncremented, participantsUnchanged). Self-contained.",purpose:"Mid-game state predicates: the game is in play, the move counter incremented by exactly one, the participant list did not change.",whenToUse:"Reach for `state` on per-move updates to assert the move actually advanced the game and did not change the players.",entries:[{signature:"isPlaying(): bool",cost:{min:6,max:6},reads:0,description:'`resource.data.status == "playing"`.'},{signature:"moveIncremented(): bool",cost:{min:11,max:11},reads:0,description:"`request.resource.data.moveCount == resource.data.moveCount + 1`."},{signature:"participantsUnchanged(): bool",cost:{min:10,max:19},reads:0,description:"Host and guest fields are identical pre- and post-write."}],relatedKeys:["turns","lifecycle","transitions"]},Zm={key:"results",kind:"user-module",description:"User-authored module: how a two-player game ends (resignedBy, finishedWithWinner, resultUnchanged). Imports onlyFieldsChanged and immutableFields from lifecycle, statusIs and newStatusIs from transitions.",purpose:"Result writes on docs with `host`, `guest`, `status` and `winner` fields. `status` is 'playing' while in play and names how the game ended once finished: 'won' with the winning seat in `winner`, 'draw' with `winner` '', or 'resigned' with the other seat in `winner`. There is no separate reason field.",whenToUse:"Reach for `results` on the update rule of a turn-based game: resignedBy for the resign button, finishedWithWinner for a write that only records the result, and resultUnchanged on every other update so a move cannot rewrite the result.",entries:[{signature:"resignedBy(seat: string): bool",cost:{min:10,max:72},reads:0,description:"The caller holds `seat` ('host' or 'guest'), status goes from 'playing' to 'resigned', `winner` is the other seat, and only status and winner change.",examples:["allow update: if resignedBy(request.auth.uid == resource.data.host ? 'host' : 'guest');"]},{signature:"finishedWithWinner(winner: string, reason: string): bool",cost:{min:14,max:61},reads:0,description:"Status goes from 'playing' to `reason`, 'won' or 'draw'; `winner` is 'host' or 'guest' for 'won' and '' for 'draw'; only status and winner change.",examples:["allow update: if finishedWithWinner('host', 'won') || finishedWithWinner('', 'draw');"],notes:"The caller is not checked: compose it with the rule that decides who may record a result. Resignations go through resignedBy."},{signature:"resultUnchanged(): bool",cost:{min:14,max:14},reads:0,description:"Status and winner are unchanged by the write."}],relatedKeys:["state","turns","lobby","lifecycle","transitions"]},Jm={key:"fairness",kind:"user-module",description:"User-authored module: commit-reveal fairness (commitmentMatches, digestByte). Self-contained.",purpose:"Hidden choices and shared randomness: a player stores `commit`, the uppercase hex SHA-256 of a secret salt, before the other players add their input, then reveals `salt`. commitmentMatches checks the reveal against the commitment, and digestByte derives values such as die faces from a digest.",whenToUse:"Reach for `fairness` on the reveal write of a commit-reveal game: dice, card draws, or a hidden move that must not change after the other players act.",entries:[{signature:"commitmentMatches(commitment: string, salt: string): bool",cost:{min:6,max:16},reads:0,description:"`salt` is a non-empty string and `hashing.sha256(salt).toHexString()` equals `commitment`.",examples:["allow update: if commitmentMatches(resource.data.commit, request.resource.data.salt);"],notes:"The commitment is the uppercase hex string, not Bytes: a commitment stored as Bytes or as lowercase hex does not match."},{signature:"digestByte(digest: Bytes, index: int): int",cost:{min:63,max:63},reads:0,description:"Byte `index` of `digest` as an int from 0 to 255. An index outside the digest, or a digest that is not Bytes, is an error, so the rule denies.",examples:["allow update: if request.resource.data.die == digestByte(hashing.sha256(request.resource.data.salt + resource.data.nonce), 0) % 6 + 1;"],notes:"Production Bytes have no index operator, so the byte is read from `toHexString()` through a 16-entry lookup map on every call. `% 6 + 1` gives faces 1 to 4 a 43 in 256 chance and faces 5 and 6 a 42 in 256 chance."}],relatedKeys:["hashing","bytes","turns","results"]},Qm={key:"membership",kind:"user-module",description:"User-authored module: claims + role-based access (hasClaim, hasClaimRole, isMemberOf, hasRole). Self-contained.",purpose:'Two halves: claim-based checks against the auth token, and role checks against a `members` map on a document. The module is the right cover for "team-style" apps where each doc has a participant map.',whenToUse:"Reach for `membership` whenever a rule gates on a custom claim (`request.auth.token.admin`) or on a role inside a participant map.",entries:[{signature:"hasClaim(claim: string): bool",cost:{min:6,max:14},reads:0,description:"Auth token has a non-null value for the named claim."},{signature:"hasClaimRole(claim: string, role: string): bool",cost:{min:6,max:14},reads:0,description:"Auth token claim equals the named role value."},{signature:"isMemberOf(membersMap: map): bool",cost:{min:6,max:12},reads:0,description:"Auth uid is a key in the members map."},{signature:"hasRole(membersMap: map, role: string): bool",cost:{min:6,max:14},reads:0,description:"Auth uid is in the members map with the named role."}],relatedKeys:["auth","request"]},Ym={key:"lifecycle",kind:"user-module",description:"User-authored module: field immutability, changed-field checks, and server-timestamp checks (fieldUnchanged, immutableFields, onlyFieldsChanged, exactlyChanged, nFieldsChanged, isServerTimestamp). Self-contained.",purpose:"Locks specific fields against modification on updates and asserts that a timestamp field matches `request.time` (i.e. the client used the server-timestamp sentinel).",whenToUse:"Reach for `lifecycle` on every update rule to lock identity fields (`createdAt`, `ownerId`) and to enforce server-set timestamps.",entries:[{signature:"fieldUnchanged(field: string): bool",cost:{min:11,max:11},reads:0,description:"The named field is byte-identical before and after the write."},{signature:"immutableFields(fields: list<string>): bool",cost:{min:10,max:10},reads:0,description:"All listed fields are unchanged. Implemented via MapDiff so it is cheaper than chaining `fieldUnchanged` calls."},{signature:"isServerTimestamp(field: string): bool",cost:{min:9,max:9},reads:0,description:"The named field equals `request.time` (i.e. the client wrote `FieldValue.serverTimestamp()`)."},{signature:"onlyFieldsChanged(fields: list<string>): bool",cost:{min:10,max:10},reads:0,description:"The dual of immutableFields: every CHANGED field is in the allowed list, so unlisted fields are implicitly immutable (adds and removes count as changes). The most common update guard: users may edit title and body and nothing else. Top-level keys only; nested-map diffs are unreliable in production.",examples:["allow update: if onlyFieldsChanged(['title', 'body']);"]},{signature:"nFieldsChanged(n: int): bool",cost:{min:11,max:11},reads:0,description:"Exactly n top-level fields changed in this write. `nFieldsChanged(1)` is the board-integrity / edit-one-field-per-write guard."},{signature:"exactlyChanged(keys: list<string> | set<string>): bool",cost:{min:13,max:17},reads:0,description:"The top-level fields the write adds, removes, or changes are exactly `keys`: every listed field changed and no other field did. `onlyFieldsChanged` is the subset form, where a listed field may stay unchanged.",examples:["allow update: if exactlyChanged(['board', 'lastMove', 'currentTurn', 'moveCount']);"],notes:"Use it for a transition that always writes the same fields, such as a tic-tac-toe move. Reads `resource.data`, so on create the call is an error and the rule denies."}],relatedKeys:["map","validation","request","counters"]},Xm={key:"transitions",kind:"user-module",description:"User-authored module: state-machine transitions (validTransition, statusIs, newStatusIs). Self-contained.",purpose:"Asserts that a field moves from one specific value to another specific value on a write. Use to encode state-machine edges directly in rules.",whenToUse:"Reach for `transitions` whenever a rule encodes a state machine — order: pending → paid → shipped, etc.",entries:[{signature:"validTransition(field: string, from: string, to: string): bool",cost:{min:8,max:16},reads:0,description:"Field was `from` before and is `to` after."},{signature:"statusIs(field: string, value: string): bool",cost:{min:7,max:7},reads:0,description:"Pre-write field equals `value`."},{signature:"newStatusIs(field: string, value: string): bool",cost:{min:8,max:8},reads:0,description:"Post-write field equals `value`."}],relatedKeys:["state","lifecycle"]},eg={key:"geometry",kind:"user-module",description:"User-authored module: movement validation via config-doc lookup (validSimpleMove, validJumpMove) and named squares such as 'e4' on an 8 by 8 board (file, rank, step, inBounds). The config-doc functions take the config from a `get()` call.",purpose:"Board-game movement rules expressed as lookups in a config document, `cfg.moves[piece][from][to]` for simple moves and `cfg.jumps[piece][from][to]` for jumps (with captured-cell info), or as arithmetic on square names: file letter 'a' to 'h', then rank digit '1' to '8'. The module is \"explicit parameter\" style: no implicit reads. The caller passes the config and the squares explicitly.",whenToUse:"Reach for `geometry` on grid-based games (chess, checkers, go variants). Pair the config-doc functions with a `get()` on your config document. Use the named-square functions when the board is a map keyed by square names; check a client-written square with `inBounds` before you read it.",entries:[{signature:"validSimpleMove(cfg: map): bool",cost:{min:26,max:26},reads:0,description:"`cfg.moves[piece][from][to] == true`."},{signature:"validJumpMove(cfg: map): bool",cost:{min:31,max:31},reads:0,description:"`cfg.jumps[piece][from][to] == capturedCell`."},{signature:"file(square: string): int",cost:{min:23,max:23},reads:0,description:"The square's file as a number: 'a' is 1 and 'h' is 8.",examples:["allow update: if file(request.resource.data.to) - file(resource.data.from) == 1;"],notes:"A first character outside 'a' to 'h', an empty string, or a non-string square is an error, which denies. Costs the same as the map lookup written inline."},{signature:"rank(square: string): int",cost:{min:6,max:6},reads:0,description:"The square's rank as a number: the second character read as a digit.",examples:["allow update: if rank(request.resource.data.to) == 8;"],notes:"Reads only the second character, so `rank('e9')` is 9 and `rank('e44')` is 4: check the square with `inBounds` first. A non-digit second character, a square shorter than two characters, or a non-string square is an error, which denies."},{signature:"step(square: string, df: int, dr: int): string",cost:{min:49,max:49},reads:0,description:"The square `df` files and `dr` ranks away from `square`, as a name.",examples:["allow update: if request.resource.data.to == step(resource.data.from, 1, 1);"],notes:"`step(from, df, dr) == to` costs 51, where the same test written as file and rank differences costs 53 to 71. A step off the board in any direction is an error, which denies. To test for any one diagonal neighbor, compare file and rank differences instead of calling `step` four times."},{signature:"inBounds(square: any): bool",cost:{min:5,max:9},reads:0,description:"The value is a string of one file letter 'a' to 'h' and one rank digit '1' to '8'.",examples:["allow update: if inBounds(request.resource.data.to);"],notes:"Anything else, a non-string included, is false rather than an error."}],relatedKeys:["transitions","state"]},tg={key:"counters",kind:"user-module",description:"User-authored module: denormalized numeric integrity and best scores (incrementedBy, changedBy, boundedNumber, improvedBy). Self-contained.",purpose:"Keeps client-maintained counts honest: likes, votes, moves, quantities may only change by a known step, stay within known bounds, or move strictly one way. Generalizes the state module's moveIncremented() (hardcoded to moveCount) to any field.",whenToUse:"Reach for `counters` whenever a numeric field is client-written but semantically constrained: vote/like toggles (`changedBy(f, -1, 1)`), move counters (`incrementedBy(f, 1)`), ratings (`boundedNumber(f, 1, 5)`), best scores that only get better (`improvedBy(f, 'up', [...])`).",entries:[{signature:"incrementedBy(field: string, n: int): bool",cost:{min:13,max:13},reads:0,description:"The field changed by EXACTLY n vs the existing document (n may be negative). Update rules only.",examples:["allow update: if incrementedBy('moveCount', 1);"]},{signature:"changedBy(field: string, min: int, max: int): bool",cost:{min:14,max:27},reads:0,description:"The field's delta is within [min, max] inclusive; a zero delta passes when the range spans 0.",examples:["allow update: if changedBy('likeCount', -1, 1);"]},{signature:"boundedNumber(field: string, min: number, max: number): bool",cost:{min:19,max:35},reads:0,description:"The incoming value is an int or float within [min, max]. A missing field is an error under dynamic access, so the call denies.",examples:["allow write: if boundedNumber('rating', 1, 5);"]},{signature:"improvedBy(field: string, direction: 'up' | 'down', mayChange: list<string>): bool",cost:{min:18,max:50},reads:0,description:"The numeric field moved strictly in `direction` (`up`: new > old, `down`: new < old) and every other changed top-level field is in `mayChange`. Both values must be an int or a float; they compare by value.",examples:["allow update: if improvedBy('score', 'up', ['solve']);",`allow update: if improvedBy('moves', 'down', ['pushes', 'solve'])
|
|
1700
|
+
|| improvedBy('pushes', 'down', ['solve']);`],notes:"A listed field may stay unchanged. An unchanged or worse value, a non-numeric or missing value on either side, an unlisted field added, removed, or changed, and a direction other than `up` or `down` deny. For a score ranked on two fields, call it once per field: the second call leaves the first field out of `mayChange`, so it allows fewer pushes only on as many moves. Write the score's type, bounds, and owner checks beside it. Reads `resource.data`, so on create the call is an error and the rule denies."}],relatedKeys:["lifecycle","state"]},ng={key:"timing",kind:"user-module",description:"User-authored module: cooldown / rate-limit enforcement (cooldownElapsed). Self-contained. Live-verified against the production engine.",purpose:"Rules CAN rate-limit: compare `request.time` against a stored server timestamp with duration arithmetic. Enforces a minimum interval between writes to a document.",whenToUse:"Reach for `timing` to throttle per-document writes — game move intervals, post cooldowns, retry backoff. ALWAYS pair with lifecycle's `isServerTimestamp(field)` on the same write so the stored timestamp cannot be forged by the client. Per-document intervals only; sliding-window quotas need a counter document plus this guard.",entries:[{signature:"cooldownElapsed(field: string, seconds: int): bool",cost:{min:12,max:12},reads:0,description:"`request.time > resource.data[field] + duration.value(seconds, 's')` — the stored timestamp is STRICTLY older than the window. Update rules only (needs `resource`); a missing or non-timestamp field errors, which denies (fail-closed).",examples:["allow update: if cooldownElapsed('lastMoveAt', 2) && isServerTimestamp('lastMoveAt');"]}],relatedKeys:["lifecycle","timestamp","duration"]},sg={key:"content",kind:"user-module",description:"User-authored module: author-owned documents (validAuthorCreate, isAuthor, canReadContent, notDeleted) and hidden per-player documents (ownerOnlyUntil). Self-contained; ownerOnlyUntil reads the parent match with one get(). Field names are parameters, not conventions.",purpose:"The most common Firebase app shape — posts, notes, docs, comments, tasks. Covers the create/read/update/delete lifecycle of documents that belong to their author, with draft/published visibility and soft delete.",whenToUse:"Reach for `content` on any collection whose documents have an author/owner field. Compose with lifecycle.onlyFieldsChanged to keep authorship immutable on edits.",entries:[{signature:"validAuthorCreate(authorField: string): bool",cost:{min:6,max:16},reads:0,description:"Create guard: signed in AND the incoming doc's author field is the caller's uid.",examples:["allow create: if validAuthorCreate('author');"]},{signature:"isAuthor(authorField: string): bool",cost:{min:6,max:15},reads:0,description:"The caller is the EXISTING document's author. Update/delete rules.",examples:["allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body']);"]},{signature:"canReadContent(statusField: string, authorField: string): bool",cost:{min:8,max:23},reads:0,description:"Published content is public; anything else is visible to its author only. `get` rules — a bare collection `list` will be denied unless the query proves `status == 'published'` via filters (rules are not filters).",examples:["allow read: if canReadContent('status', 'author') && notDeleted();"]},{signature:"notDeleted(): bool",cost:{min:8,max:8},reads:0,description:"Soft-delete guard: `resource.data.get('deleted', false) != true`. `get()` returns the default for a missing key, so a document WITHOUT the field passes. Dotted or bracket access of a missing key is an error in production and would deny it."},{signature:"ownerOnlyUntil(parentPath: path, ownerUid: string, statuses: list): bool",cost:{min:6,max:20},reads:1,description:"Read rule for a hidden per-player document under a match: the owner reads it at any time, and any other signed-in caller reads it once the match at `parentPath` has a `status` in `statuses`.",examples:["allow read: if ownerOnlyUntil(/databases/$(database)/documents/battleship/$(matchId), uid, ['won', 'resigned']);"],notes:"The document lives at {collection}/{matchId}/{sub}/{uid}. Pass the `uid` wildcard as the owner when the document id is the owner's UID, or `resource.data.<field>` when the owner is a field. Pass one status as a one-item list, such as ['finished']. The owner check runs before the `get()`, so the owner's read spends no read; everyone else pays one `get()` of the parent. A missing parent match is an error and denies every caller but the owner."}],relatedKeys:["auth","lifecycle","validation"]},rg={key:"spaces",kind:"user-module",description:"User-authored module: cross-document membership gating (isSpaceMember, hasSpaceRole, validMemberCreate). Explicit param — pass the parent doc data from a get(). Live-verified against the production engine.",purpose:"Shared spaces — teams, rooms, groups, projects, parties: a PARENT document's members field gates its children. The second-most-common app shape after author-owned content.",whenToUse:"Reach for `spaces` whenever a subcollection is gated by a parent doc. Define ONE helper in the child match block — `function space() { return get(/databases/$(database)/documents/spaces/$(spaceId)).data; }` — and pass it to every function: get() is cached per request, so all rules on the request share a single read of the 10-get budget. Do NOT inline a get() per allow clause.",entries:[{signature:"isSpaceMember(spaceData: map): bool",cost:{min:6,max:13},reads:0,description:"The caller's uid is in `spaceData.members`. `in` covers BOTH shapes: list membership (`members: ['a','b']`) and map keys (`members: {a: 'admin'}`). Missing field / non-member / missing parent doc all fail closed.",examples:["allow read: if isSpaceMember(space());"]},{signature:"hasSpaceRole(spaceData: map, role: string): bool",cost:{min:6,max:15},reads:0,description:"The caller's role in a MAP-shaped members field equals `role` (`spaceData.members[request.auth.uid] == role`). List-shaped members carry no roles — denies.",examples:["allow delete: if hasSpaceRole(space(), 'admin');"]},{signature:"validMemberCreate(spaceData: map, authorField: string): bool",cost:{min:9,max:26},reads:0,description:`Member-gated authored create: caller is a member AND the incoming child doc's author field is the caller. The "post a message / add a task" guard.`,examples:["allow create: if validMemberCreate(space(), 'author');"]}],relatedKeys:["membership","content","builtins"]},ig={key:"joining",kind:"user-module",description:"User-authored module: safe self-service membership changes (onlyAddedSelf, onlyRemovedSelf). Self-contained. Live-verified against the production engine.",purpose:"How membership CHANGES without an admin backend: users join and leave a MAP-shaped members field (uid -> role) with zero privilege escalation — no self-granted roles, no touching other members, no-op writes denied.",whenToUse:"Reach for `joining` on the PARENT doc's update rule wherever spaces gates the children. ALWAYS compose with lifecycle's onlyFieldsChanged(['members']) so a join/leave write cannot modify anything else on the doc. Invite-doc consumption (single-use invites) is a Pattern, not a function — it needs a batch write + getAfter().",entries:[{signature:"onlyAddedSelf(membersField: string, role: string): bool",cost:{min:20,max:53},reads:0,description:"The write adds EXACTLY the caller to the members map at EXACTLY `role` — changing nobody, removing nobody; a no-op write denies (uses set equality `diff.addedKeys() == [uid].toSet()`, not hasOnly, which passes on an empty diff). Update rules only.",examples:["allow update: if onlyFieldsChanged(['members']) && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));"]},{signature:"onlyRemovedSelf(membersField: string): bool",cost:{min:19,max:40},reads:0,description:"The write removes EXACTLY the caller — adding nobody, changing nobody. Self-service leave. Update rules only."}],relatedKeys:["spaces","lifecycle","membership"]},og={key:"atomic",kind:"user-module",description:"User-authored module: cross-document BATCH-write integrity via get()/getAfter() (companionChangedBy, consumedFlag). Explicit param. Live-verified against a real production database.",purpose:"Rules that require a COMPANION write in the same atomic batch: denormalized counters (create task + increment team.taskCount), single-use invite consumption (join + mark invite used), paired documents. getAfter(path) returns the post-batch state of another doc in the batch; for docs not in the batch it equals get(path).",whenToUse:"Reach for `atomic` when two documents must change together. Define before()/after() helpers — `get(path).data` and `getAfter(path).data` for the SAME companion path — and pass both. Every write in a batch is rules-evaluated: the companion write needs its own allow rule. The client must use a batch/transaction (writeBatch / runTransaction); solo writes deny by construction.",entries:[{signature:"companionChangedBy(before: map, after: map, field: string, n: int): bool",cost:{min:10,max:10},reads:0,description:"The companion doc's field changed by EXACTLY n in this batch (`after[field] == before[field] + n`). A solo write denies: without a companion write, getAfter == get, so the delta is 0.",examples:["allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);"]},{signature:"consumedFlag(before: map, after: map, flagField: string): bool",cost:{min:7,max:13},reads:0,description:"A single-use flag was consumed IN THIS BATCH: pre-batch false AND post-batch true. Replays deny (already true before the batch); solo writes deny (false != true when getAfter == get). Pair with an allow rule on the flag doc itself (e.g. invitee-only, resource.used == false).",examples:["allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');"]}],relatedKeys:["counters","joining","spaces","builtins"]},ag={key:"storage/uploads",kind:"user-module",description:"Storage module: inclusive upload-size limits and declared MIME metadata allowlists.",purpose:"Apply bounded upload policies to the incoming Storage object. MIME helpers inspect declared metadata; they do not inspect or authenticate the uploaded bytes.",whenToUse:"Use for Storage create or update rules that limit object size or accepted content-type metadata.",entries:[{signature:"sizeAtMost(maxBytes: int): bool",cost:{min:6,max:6},reads:0,description:"The incoming object size is at most the inclusive byte limit."},{signature:"sizeBetween(minBytes: int, maxBytes: int): bool",cost:{min:7,max:13},reads:0,description:"The incoming object size is inside the inclusive byte range."},{signature:"contentTypeMatches(pattern: string): bool",cost:{min:6,max:6},reads:0,description:"The incoming content-type metadata matches the entire RE2 pattern.",notes:"This checks declared metadata, not the uploaded bytes."},{signature:"contentTypeIsOneOf(types: list): bool",cost:{min:6,max:6},reads:0,description:"The incoming content-type metadata equals one allowlisted value.",notes:"This checks declared metadata, not the uploaded bytes."}],relatedKeys:["auth","membership","storage/metadata","storage/objects"]},cg={key:"storage/metadata",kind:"user-module",description:"Storage module: required custom metadata, bounded string values, and metadata ownership.",purpose:"Validate the flat string map in Storage custom metadata and connect incoming or existing ownership metadata to the authenticated UID.",whenToUse:"Use when object paths alone do not carry every upload invariant and custom metadata must be present, bounded, or owner-bound.",entries:[{signature:"hasRequiredMetadata(keys: list): bool",cost:{min:7,max:7},reads:0,description:"The incoming custom metadata contains every required key."},{signature:"metadataString(key: string, min: int, max: int): bool",cost:{min:28,max:28},reads:0,description:"The incoming metadata value is a string within the inclusive size range."},{signature:"incomingMetadataOwner(key: string): bool",cost:{min:6,max:16},reads:0,description:"The incoming metadata value equals the authenticated UID."},{signature:"existingMetadataOwner(key: string): bool",cost:{min:6,max:15},reads:0,description:"The existing metadata value equals the authenticated UID."}],relatedKeys:["auth","membership","storage/uploads","storage/objects"]},ug={key:"storage/objects",kind:"user-module",description:"Storage module: distinguish create, update, and delete operations safely, read segments of the object name, and tie an object to the Firestore document that names it.",purpose:"Branch Storage authorization by request method without relying on missing resource bindings or null checks, and check an object by its name: one segment at a time, or against a field of a Firestore document.",whenToUse:"Use when create, update, and delete require different ownership or validation checks, when the object name carries an owner or key, or when an upload is allowed only once a Firestore document names it.",entries:[{signature:"isCreate(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'create'."},{signature:"isUpdate(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'update'."},{signature:"isDelete(): bool",cost:{min:5,max:5},reads:0,description:"The Storage request method is 'delete'."},{signature:"nameSegment(index: int): string",cost:{min:17,max:18},reads:0,description:"Segment `index` of the object name split on '/', counting from 0. The name is `request.resource.name` on create and update and `resource.name` on get and delete.",examples:["allow create: if nameSegment(1) == request.auth.uid;"],notes:"An index past the last segment is an error that denies the request, and a name with no '/' has one segment. A create may have no stored object, and a get or delete carries no incoming object, so the name comes from the binding each operation has."},{signature:"matchesDocument(path: path, field: string): bool",cost:{min:6,max:26},reads:1,description:"The caller is signed in, and the Firestore document at `path` exists and its `field` equals the object name.",examples:["allow create: if matchesDocument(/databases/(default)/documents/scores/$(request.auth.uid), 'object');"],notes:"Each call reads one document. A Storage rule reads at most two distinct Firestore documents, so a rule may call matchesDocument at most twice with different paths; a third distinct document denies the request. A missing document or field is an error that denies the request. The lookup reads the (default) database."}],relatedKeys:["auth","membership","storage/uploads","storage/metadata"]},lg={key:"storage/time",kind:"user-module",description:"Storage module: strict freshness windows over server-owned object timestamps.",purpose:"Check whether an existing Storage object was created or updated within a bounded number of seconds.",whenToUse:"Use for access policies whose validity expires relative to an existing object timestamp.",entries:[{signature:"createdWithin(seconds: int): bool",cost:{min:10,max:10},reads:0,description:"Request time is strictly before creation time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."},{signature:"updatedWithin(seconds: int): bool",cost:{min:10,max:10},reads:0,description:"Request time is strictly before update time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."}],relatedKeys:["storage/objects","auth","membership"]};function dg(t){if(t.kind!=="user-module")return["firestore"];const e=Eo[t.key];return e?e.map(n=>n==="firebase.storage"?"storage":"firestore"):["firestore"]}const fg=[Rm,Lm,Nm,Mm,Dm,$m,Pm,jm,Fm,qm,Um,Bm,zm,Wm,Vm,Gm,Hm,Km,Zm,Jm,Qm,Ym,Xm,eg,tg,ng,sg,rg,ig,og,ag,cg,ug,lg].map(t=>({...t,services:dg(t)}));function xl(t){return JSON.stringify([t.parameters,t.lets.map(e=>[e.name,se(e.value)]),se(t.body)])}let Jr=null;function hg(){if(Jr)return Jr;const t=new Map;for(const e of fg){if(e.kind!=="user-module")continue;const n=e.entries.map(a=>a.signature.slice(0,a.signature.indexOf("("))),s=e.services.includes("firestore")?"service cloud.firestore { match /databases/{database}/documents { } }":"service firebase.storage { match /b/{bucket}/o { } }",r=Tm(`rules_version = '2+modules';
|
|
1701
1701
|
import { ${n.join(", ")} } from '${e.key}';
|
|
1702
1702
|
${s}
|
|
1703
|
-
`);if(!r.success)continue;const i=vo(r.data.resolved);if(!i)continue;const o=new Map;for(const a of[...i.functions??[],...i.service.functions??[]])o.set(a.name,a);for(const a of e.entries){const c=a.signature.slice(0,a.signature.indexOf("(")),u=o.get(c);!u||!a.cost||t.set(c,{module:e.key,name:c,cost:a.cost,reads:a.reads??0,fingerprint:xl(u)})}}return Jr=t,t}function lg(t){const e=ug().get(t.name);if(!e||e.fingerprint!==xl(t))return null;const{fingerprint:n,...s}=e;return s}function dg(t){const e=[];for(const n of Cp(t)){const s=[];for(const{fn:r,count:i}of n.calls){const o=lg(r);o&&s.push({...o,count:i})}s.length!==0&&(s.sort((r,i)=>i.cost.max*i.count-r.cost.max*r.count||r.name.localeCompare(i.name)),e.push({ruleIndex:n.ruleIndex,matchPath:n.matchPath,blockPath:n.blockPath,...n.line!==void 0?{line:n.line}:{},calls:s}))}return e}const Ct={SOURCE_SIZE:256*1024,LET_LIMIT:Wu,CALL_DEPTH_WARN:18,CALL_DEPTH_LIMIT:Zn,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function fg(t,e){t.length>Ct.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function hg(t,e){for(const n of t)n.lets.length>Ct.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${Ct.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function pg(t,e){const n=new Set;for(const s of t){if(s.code!=="NESTING_DEPTH")continue;const r=`${s.functionName??""}@${s.line??""}`;if(n.has(r))continue;n.add(r);const i=s.functionName!==void 0?`Function '${s.functionName}'`:s.line!==void 0?`The rule at line ${s.line}`:"An allow rule";e.push({rule:"NESTING_DEPTH",severity:"error",message:`${i} nests an expression deeper than ${po} levels. Production rejects the ruleset: "${Vu}"`,...s.functionName!==void 0?{location:{functionName:s.functionName}}:{},fix:"Remove redundant parentheses, or move a nested group into its own function and call it."})}}function mg(t,e){for(const n of t){if(n.code!=="SLASH_STARTS_PATH")continue;let s="in an allow rule";if(n.functionName!==void 0){const r=n.line===void 0?"":` at line ${n.line}`;s=`in function '${n.functionName}'${r}`}else n.line!==void 0&&(s=`in the rule at line ${n.line}`);e.push({rule:"SLASH_STARTS_PATH",severity:"error",message:`A '/' ${s} is directly followed by a character other than whitespace, which production reads as the start of a path. Production rejects the ruleset: "${Gu}"`,...n.functionName!==void 0?{location:{functionName:n.functionName}}:{},fix:"To divide, put whitespace after the '/': `a / b`."})}}function gg(t,e){for(const n of t){if(n.code!=="GLOB_MATCH_COUNT")continue;const s={rule:"GLOB_MATCH_COUNT",severity:"error",message:n.message,fix:"Restructure match blocks so a path contains at most one recursive wildcard `{name=**}`."};n.scope!==void 0&&(s.location={matchPath:n.scope}),e.push(s)}}function yg(t,e,n){for(const s of e)switch(s.code){case"UNSUPPORTED_RULES_VERSION":n.push({rule:"UNSUPPORTED_RULES_VERSION",severity:"error",message:s.message,fix:"Set rules_version to '1', '2', or '2+modules'."});break;case"UNRESOLVED_MODULES":t.version!=="2+modules"&&n.push({rule:"UNRESOLVED_MODULES",severity:"error",message:s.message,fix:"Set `rules_version = '2+modules';` or resolve module imports before compiling."});break;case"INVALID_REGEX_PATTERN":n.push({rule:"INVALID_REGEX_PATTERN",severity:"error",message:s.message,...s.functionName!==void 0?{location:{functionName:s.functionName}}:{},fix:"Rewrite the regular expression using RE2-compatible syntax (no lookahead, lookbehind, or backreferences)."});break;case"FUNCTION_REDEFINED":n.push({rule:"FUNCTION_REDEFINED",severity:"error",message:s.message,...s.functionName!==void 0||s.scope!==void 0?{location:{...s.functionName!==void 0?{functionName:s.functionName}:{},...s.scope!==void 0?{matchPath:s.scope}:{}}}:{},fix:`Rename or remove the duplicate declaration of '${s.functionName??"function"}' in ${s.scope??"this scope"}.`});break}}const Pa=4900;function bg(t,e,n){const s=[];for(const r of e){for(const i of r.lets)s.push({expr:i.value,functionName:r.name});s.push({expr:r.body,functionName:r.name})}for(const{rule:r}of Ao(t.service.match))s.push({expr:r.condition,...r.loc===void 0?{}:{line:r.loc.line}});for(const r of s){let i=0;const o=[r.expr];for(;o.length>0;){const c=o.pop();let u=1,l=c;for(;l.type==="memberAccess";)u++,l=l.object;c.type==="memberAccess"&&(i=Math.max(i,u)),o.push(...vg(l))}if(i<Pa)continue;const a=r.functionName!==void 0?`Function '${r.functionName}'`:r.line!==void 0?`The rule at line ${r.line}`:"An allow rule";n.push({rule:"MEMBER_CHAIN_LENGTH",severity:"error",message:`${a} reads a member chain of ${i} terms. The Rules Test API answered a ruleset holding a ${Pa.toLocaleString("en-US")}-term member chain with an internal error instead of compiling it.`,...r.functionName!==void 0?{location:{functionName:r.functionName}}:{},fix:"Shorten the chain: bind a value partway along it to a `let` or a function parameter, and read the rest of the chain from that name."})}}function vg(t){switch(t.type){case"literal":case"identifier":return[];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end];case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args}}function wg(t,e){const n=new Map;for(let s=0;s<t.length;s++){const r=t[s];if(!r.rule.operations.some(a=>a==="update"||a==="write"))continue;const i=se(ml(r.rule.condition)),o=r.path;n.has(o)||n.set(o,[]),n.get(o).push({index:s,gate:i,ops:r.rule.operations})}for(const[s,r]of n){const i=new Map;for(const o of r)i.has(o.gate)||i.set(o.gate,[]),i.get(o.gate).push(o.index);for(const[o,a]of i)a.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${a.length} allow rules in '${s}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${a.join(", ")}.`,location:{matchPath:s},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function Sg(t,e){for(const n of t)n.grantCost===null||n.grantCost<os||e.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${n.ruleIndex} in '${n.blockPath}' can evaluate up to ~${n.grantCost} expressions for a request it grants, counting the earlier rules that deny it first. Production denies a request that reaches ${os}.`,location:{ruleIndex:n.ruleIndex,matchPath:n.blockPath},fix:"Put a cheap discriminator first in each rule so earlier rules fail at their gate, split expensive checks so a request evaluates only the branch it needs, or move lookup work into documents."})}function Ag(t,e){for(const n of dg(t)){const s=n.calls.slice(0,3).map(r=>{const i=r.cost.min===r.cost.max?`${r.cost.max}`:`${r.cost.min} to ${r.cost.max}`,o=r.reads>0?`, ${r.reads} read${r.reads===1?"":"s"} per call`:"";return`${r.name} (${r.module}): ${r.count} call${r.count===1?"":"s"}, ${i} expressions per call${o}`});e.push({rule:"EXPRESSION_LIBRARY_CALLS",severity:"info",message:`Rule #${n.ruleIndex} in '${n.blockPath}' spends most on these library calls: ${s.join("; ")}. Calls are not memoized: each call pays again.`,location:{ruleIndex:n.ruleIndex,matchPath:n.blockPath}})}}function kg(t,e){const{depths:n,cyclic:s}=qh(t),r=new Set;for(const o of t.functions)for(const a of cl(o).callees)a!==o.fn&&r.add(a);let i=!1;for(const o of t.functions){if(s.has(o.fn)){i||(i=!0,e.push({rule:"CALL_DEPTH",severity:"error",message:`Function '${o.fn.name}' is part of a recursive call cycle, exceeding the call depth limit of ${Ct.CALL_DEPTH_LIMIT}.`,location:{functionName:o.fn.name,matchPath:o.label},fix:"Remove recursion between helper functions; Firestore rules do not allow recursive calls."}));continue}if(r.has(o.fn))continue;const a=n.get(o.fn)??1;if(a<Ct.CALL_DEPTH_WARN)continue;const c=a>Ct.CALL_DEPTH_LIMIT;e.push({rule:"CALL_DEPTH",severity:c?"error":"warning",message:`Function '${o.fn.name}' starts a function call chain of depth ${a}. Limit is ${Ct.CALL_DEPTH_LIMIT}.`,location:{functionName:o.fn.name,matchPath:o.label},...c?{fix:"Inline intermediate functions to reduce call depth."}:{}})}return n}function Eg(t,e,n,s,r=!1){const i=new Map,o=r?2:Ct.GET_COUNT_ERROR,a=r?2:Ct.GET_COUNT_WARN,c=r?"firestore.get()/firestore.exists()":"get()/exists()/getAfter()/existsAfter()";for(let u=0;u<t.length;u++){const l=e.get(t[u].rule)??i,d=il(t[u].rule.condition,l,new Set,n);d>o?s.push({rule:"GET_COUNT",severity:"error",message:`Rule #${u} may invoke ${d} ${c} calls. Limit is ${o}.`,location:{ruleIndex:u},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):d>=a&&s.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${u} invokes ${d} ${c} calls. Limit is ${o}.`,location:{ruleIndex:u}})}}function Ig(t,e,n,s){const r=new Map;for(let i=0;i<t.length;i++){const o=e.get(t[i].rule)??r,a=new Set(o.keys()),c=Xh(t[i].rule.condition,a);for(const[u,l]of c)l>=2&&gl(u,o,new Set,n)&&s.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${u}' (contains get/exists) is called ${l} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${l} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${u}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function _g(t,e,n,s,r){const i=new Map,o=new Set;for(let c=0;c<t.length;c++){const u=e.get(t[c].rule)??i;Ai(t[c].rule.condition,u,new Set,n)&&o.add(c)}if(o.size===0)return;function a(c,u){const l=c.split("/").filter(Boolean),d=u.split("/").filter(Boolean);if(l.length!==d.length)return!1;for(let f=0;f<l.length;f++){const p=l[f];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==d[f])return!1}return!0}for(const c of s)if(!c.requestTime)for(const u of o)a(t[u].path,c.path)&&r.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${c.description}" targets rule #${u} (path '${t[u].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:u,matchPath:t[u].path,testCaseDescription:c.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}const xg=new Set(["write","create","update","delete"]);function Cg(t,e,n,s=!1){for(let r=0;r<t.length;r++){const i=t[r];if(qt(i.rule.condition)!==!0||!i.rule.operations.some(c=>xg.has(c)))continue;const a=i.rule.operations.join(", ");n.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${a} at ${i.path} resolves to a constant true predicate — this disables write security for ${e.get(i.rule)?.description??"the matched paths"}. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:i.path},fix:s?"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.size < 5 * 1024 * 1024 && request.resource.contentType.matches('image/.*')).":"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Cl(t,e,n){const s=[...e,...t.path.segments],r=$h(s);r&&t.allows.forEach((i,o)=>n.set(i,{...r,ruleIndex:o}));for(const i of t.children)Cl(i,s,n);return n}function Og(t,e){for(const[n,s]of t)s.kind!=="subtree"||qt(n.condition)!==!0||e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`match ${s.fullPath} allows ${n.operations.join(", ")} on ${s.description} with an always-true condition.`,location:{ruleIndex:s.ruleIndex,matchPath:s.fullPath},fix:"Narrow the match path to the collections that must be open, for example match /{path=**}/<collection>/{id} for one collection group, or replace `if true` with a real predicate (auth identity, ownership, role)."})}function Tg(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function Rg(t){return t.map(Tg).join("/")}function _i(t,e){const n=Rg(t.path.segments),s=e?`${e}/${n}`:n,r=[{block:t,normalizedPath:s}];for(const i of t.children)r.push(..._i(i,s));return r}function Lg(t,e,n){const s=_i(t,""),r=_i(e,""),i=new Map;for(const{block:o,normalizedPath:a}of s)i.has(a)||i.set(a,o);for(const{block:o,normalizedPath:a}of r){const c=i.get(a);if(!c){o.allows.length>0&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${a}`,location:{matchPath:a}});continue}for(const u of o.allows){const l=[...u.operations].sort().join(","),d=c.allows.find(m=>[...m.operations].sort().join(",")===l),f=u.operations.join(", ");if(!d){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${a} allow ${f}`,location:{matchPath:a}});continue}const p=Ks(u.condition).map(pe),h=new Set(Ks(d.condition).map(pe));for(const m of p)h.has(m)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${a} allow ${f}: ${m}`,location:{matchPath:a}})}}}function xi(t,e={}){const n=[];n.push(...cp(t)),fg(t,n);const s=Es(t);if(!s.ok)return{warnings:n,metrics:ja(t),parseError:s.error};try{return Mg(s.ast,t,e,n)}catch(r){if(!(r instanceof RangeError))throw r;return n.push(Ng()),{warnings:n,metrics:ja(t)}}}function ja(t){return{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0}}function Ng(){return{rule:"EXPRESSION_TOO_DEEP",severity:"error",message:"An expression chains or nests more terms, counting the bodies of the functions it calls, than the linter can analyze, so the remaining checks did not run. This is a limit of the linter; production's limit for this expression is not measured.",fix:"Shorten the chain: bind a value partway along it to a `let` or a function parameter, and read the rest of the chain from that name."}}function Mg(t,e,n,s){const r=t.service?.name==="firebase.storage",i=ep(t),o=Ao(t.service.match),a=al(t),c=new Map(a.functions.map(v=>[v.fn,v.functions])),u=new Map(a.rules.map(v=>[v.rule,v.functions]));bg(t,i,s);const l=mo(t);pg(l,s),mg(l,s),gg(l,s),yg(t,l,s),hg(i,s),wg(o,s);const d=_p(t);Sg(d.rules,s),Ag(t,s);const f=kg(a,s);Eg(o,u,c,s,r),Ig(o,u,c,s),s.push(...Sp(t,{allowDebug:n.allowDebug}));const p=new Map;for(const v of t.service.match.children)Cl(v,[],p);if(Cg(o,p,s,r),Og(p,s),n.testCases&&n.testCases.length>0&&_g(o,u,c,n.testCases,s),n.previousSource){const v=Es(n.previousSource);v.ok&&Lg(t.service.match,v.ast.service.match,s)}let h={depth:0,op:""},m={count:0,fn:""};for(const v of i){const E=Yh(v.body);E.depth>h.depth&&(h={depth:E.depth,op:E.op}),v.lets.length>m.count&&(m={count:v.lets.length,fn:v.name})}let g=0;for(const v of f.values())v>g&&(g=v);const b=new Map;let y=0;for(const v of d.rules)v.grantCost!==null&&v.grantCost>y&&(y=v.grantCost);let w=0;for(const v of o){const E=u.get(v.rule)??b,I=il(v.rule.condition,E,new Set,c);I>w&&(w=I)}return{warnings:s,metrics:{sourceSize:e.length,functionCount:i.length,allowRuleCount:o.length,maxChainDepth:h.depth,maxChainOp:h.op,maxLetBindings:m.count,maxLetBindingsFunction:m.fn,maxCallDepth:g,maxEstimatedExpressions:y,getCallCount:w}}}class _ extends Error{expr;constructor(e,n){super(e),this.expr=n,this.name="EvalError"}}class cn extends _{constructor(e,n){super(e,n),this.name="ResourceLimitError"}}class Ol extends cn{position;constructor(e,n){super(e),this.position=n,this.name="ExpressionLimitError"}}const Dg="Divide by zero error.";function ts(t){return`Function not found error: Name: [${t}].`}const ge=Symbol.for("pyric.RulesValue.NO_OP");class oe{field(e){return null}callMethod(e,n){return ge}binaryOp(e,n){return ge}}function Ge(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function J(t){return t===null?"null":t===void 0?"undefined":t instanceof oe?t.typeName:t instanceof fe?"set":t instanceof Js?"map_diff":typeof t=="number"?Number.isInteger(t)?"int":"float":typeof t=="boolean"?"bool":Array.isArray(t)?"list":Ge(t)?"map":typeof t}function Ts(t,e){if(e<0||e>=t.length)return!1;const n=t[e];if(n.length!==1)return!1;const s=n.charCodeAt(0);return s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||s===95}function xo(t,e,n,s){const r=/\\[1-9]/.test(e),i=/\(\?<?[=!]/.test(e);if(r||i){const o=r?"backreference":"lookaround";throw new Error(`${t}() pattern uses an RE2-unsupported construct (${o}) that production would reject`)}try{return new RegExp(ho(n),s)}catch(o){throw new Error(`Invalid regex '${e}' in ${t}(): ${o.message}`)}}function $g(t,e){xo("matches",t,`^(?:${t})$`);const n=Pg(t),s=[{kind:"accept"}],r=u=>{const l=s.length;return s.push(u),l},i=(u,l)=>{switch(u.kind){case"empty":return l;case"char":return r({kind:"char",test:u.test,out:l});case"assert":return r({kind:"assert",check:u.check,out:l});case"seq":{let d=l;for(let f=u.items.length-1;f>=0;f--)d=i(u.items[f],d);return d}case"alt":{const d=i(u.left,l),f=i(u.right,l);return r({kind:"split",out1:d,out2:f})}case"rep":{let d=l;if(u.max===1/0){const f=r({kind:"split",out1:0,out2:l}),p=i(u.body,f);s[f]={kind:"split",out1:p,out2:l},d=f}else for(let f=u.min;f<u.max;f++){const p=i(u.body,d);d=r({kind:"split",out1:p,out2:d})}for(let f=u.min-1;f>=0;f--)d=i(u.body,d);return d}}},o=Array.from(e),a=i(n,0);let c=Fa([a],s,o,0);for(let u=0;u<o.length&&c.length>0;u++){const l=o[u],d=[];for(const f of c){const p=s[f];p.kind==="char"&&p.test(l)&&d.push(p.out)}c=Fa(d,s,o,u+1)}return c.includes(0)}function Fa(t,e,n,s){const r=new Uint8Array(e.length),i=[...t],o=[];for(;i.length>0;){const a=i.pop();if(r[a])continue;r[a]=1;const c=e[a];c.kind==="split"?i.push(c.out1,c.out2):c.kind==="assert"?c.check(n,s)&&i.push(c.out):o.push(a)}return o}function Xt(t,e){let n="u";e&&(n="iu");try{const s=new RegExp(`^${t}$`,n);return r=>s.test(r)}catch{const s=e?"i":"",r=new RegExp(`^${t}$`,s);return i=>r.test(i)}}function Pg(t){let e=0,n=!1,s=!1,r=!1;const i=d=>{let f=!1;for(const p of d)p==="-"?f=!0:p==="i"?n=!f:p==="m"?s=!f:p==="s"&&(r=!f)},o=()=>{let d=a();for(;e<t.length&&t[e]==="|";){e++;const f=a();d={kind:"alt",left:d,right:f}}return d},a=()=>{const d=[];for(;e<t.length&&t[e]!=="|"&&t[e]!==")";)d.push(c());return d.length===0?{kind:"empty"}:d.length===1?d[0]:{kind:"seq",items:d}},c=()=>{let d=l();for(;e<t.length;){const f=t[e];if(f==="*"||f==="+"||f==="?"){e++,e<t.length&&t[e]==="?"&&e++;let p=0,h=1/0;f==="+"?p=1:f==="?"&&(h=1),d={kind:"rep",body:d,min:p,max:h}}else if(f==="{"){const p=/^\{(\d+)(?:,(\d*))?\}/.exec(t.slice(e));if(!p)break;e+=p[0].length,e<t.length&&t[e]==="?"&&e++;const h=Number(p[1]);let m=h;if(p[2]!==void 0&&(m=p[2]===""?1/0:Number(p[2])),h>m||h>1e3||m!==1/0&&m>1e3)throw new Error(`Invalid repeat count in '${t}'`);d={kind:"rep",body:d,min:h,max:m}}else break}return d},u=(d,f)=>{if(f){const p=d.toLowerCase(),h=d.toUpperCase();return{kind:"char",test:m=>m===p||m===h}}return{kind:"char",test:p=>p===d}},l=()=>{const d=t[e];if(d==="("){e++;const h=n,m=s,g=r;if(t[e]==="?")if(e++,t[e]===":")e++;else if(t[e]==="<"||t[e]==="P"&&t[e+1]==="<")e=t.indexOf(">",e)+1;else{const y=/^[imsU-]+/.exec(t.slice(e));if(y){if(i(y[0]),e+=y[0].length,t[e]===")")return e++,{kind:"empty"};t[e]===":"&&e++}}const b=o();return t[e]===")"&&e++,n=h,s=m,r=g,b}if(d==="["){const h=e;for(e++,t[e]==="^"&&e++,t[e]==="]"&&e++;e<t.length&&t[e]!=="]";)t[e]==="\\"?e+=2:e++;t[e]==="]"&&e++;const m=ho(t.slice(h,e));return{kind:"char",test:Xt(m,n)}}if(d==="^"){e++;const h=s;return{kind:"assert",check:(m,g)=>g===0||h&&g>0&&m[g-1]===`
|
|
1703
|
+
`);if(!r.success)continue;const i=vo(r.data.resolved);if(!i)continue;const o=new Map;for(const a of[...i.functions??[],...i.service.functions??[]])o.set(a.name,a);for(const a of e.entries){const c=a.signature.slice(0,a.signature.indexOf("(")),u=o.get(c);!u||!a.cost||t.set(c,{module:e.key,name:c,cost:a.cost,reads:a.reads??0,fingerprint:xl(u)})}}return Jr=t,t}function pg(t){const e=hg().get(t.name);if(!e||e.fingerprint!==xl(t))return null;const{fingerprint:n,...s}=e;return s}function mg(t){const e=[];for(const n of Lp(t)){const s=[];for(const{fn:r,count:i}of n.calls){const o=pg(r);o&&s.push({...o,count:i})}s.length!==0&&(s.sort((r,i)=>i.cost.max*i.count-r.cost.max*r.count||r.name.localeCompare(i.name)),e.push({ruleIndex:n.ruleIndex,matchPath:n.matchPath,blockPath:n.blockPath,...n.line!==void 0?{line:n.line}:{},calls:s}))}return e}const Ct={SOURCE_SIZE:256*1024,LET_LIMIT:Wu,CALL_DEPTH_WARN:18,CALL_DEPTH_LIMIT:Zn,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function gg(t,e){t.length>Ct.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function yg(t,e){for(const n of t)n.lets.length>Ct.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${Ct.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function bg(t,e){const n=new Set;for(const s of t){if(s.code!=="NESTING_DEPTH")continue;const r=`${s.functionName??""}@${s.line??""}`;if(n.has(r))continue;n.add(r);const i=s.functionName!==void 0?`Function '${s.functionName}'`:s.line!==void 0?`The rule at line ${s.line}`:"An allow rule";e.push({rule:"NESTING_DEPTH",severity:"error",message:`${i} nests an expression deeper than ${po} levels. Production rejects the ruleset: "${Vu}"`,...s.functionName!==void 0?{location:{functionName:s.functionName}}:{},fix:"Remove redundant parentheses, or move a nested group into its own function and call it."})}}function vg(t,e){for(const n of t){if(n.code!=="SLASH_STARTS_PATH")continue;let s="in an allow rule";if(n.functionName!==void 0){const r=n.line===void 0?"":` at line ${n.line}`;s=`in function '${n.functionName}'${r}`}else n.line!==void 0&&(s=`in the rule at line ${n.line}`);e.push({rule:"SLASH_STARTS_PATH",severity:"error",message:`A '/' ${s} is directly followed by a character other than whitespace, which production reads as the start of a path. Production rejects the ruleset: "${Gu}"`,...n.functionName!==void 0?{location:{functionName:n.functionName}}:{},fix:"To divide, put whitespace after the '/': `a / b`."})}}function wg(t,e){for(const n of t){if(n.code!=="GLOB_MATCH_COUNT")continue;const s={rule:"GLOB_MATCH_COUNT",severity:"error",message:n.message,fix:"Restructure match blocks so a path contains at most one recursive wildcard `{name=**}`."};n.scope!==void 0&&(s.location={matchPath:n.scope}),e.push(s)}}function Sg(t,e,n){for(const s of e)switch(s.code){case"UNSUPPORTED_RULES_VERSION":n.push({rule:"UNSUPPORTED_RULES_VERSION",severity:"error",message:s.message,fix:"Set rules_version to '1', '2', or '2+modules'."});break;case"UNRESOLVED_MODULES":t.version!=="2+modules"&&n.push({rule:"UNRESOLVED_MODULES",severity:"error",message:s.message,fix:"Set `rules_version = '2+modules';` or resolve module imports before compiling."});break;case"INVALID_REGEX_PATTERN":n.push({rule:"INVALID_REGEX_PATTERN",severity:"error",message:s.message,...s.functionName!==void 0?{location:{functionName:s.functionName}}:{},fix:"Rewrite the regular expression using RE2-compatible syntax (no lookahead, lookbehind, or backreferences)."});break;case"FUNCTION_REDEFINED":n.push({rule:"FUNCTION_REDEFINED",severity:"error",message:s.message,...s.functionName!==void 0||s.scope!==void 0?{location:{...s.functionName!==void 0?{functionName:s.functionName}:{},...s.scope!==void 0?{matchPath:s.scope}:{}}}:{},fix:`Rename or remove the duplicate declaration of '${s.functionName??"function"}' in ${s.scope??"this scope"}.`});break}}const Pa=4900;function Ag(t,e,n){const s=[];for(const r of e){for(const i of r.lets)s.push({expr:i.value,functionName:r.name});s.push({expr:r.body,functionName:r.name})}for(const{rule:r}of Ao(t.service.match))s.push({expr:r.condition,...r.loc===void 0?{}:{line:r.loc.line}});for(const r of s){let i=0;const o=[r.expr];for(;o.length>0;){const c=o.pop();let u=1,l=c;for(;l.type==="memberAccess";)u++,l=l.object;c.type==="memberAccess"&&(i=Math.max(i,u)),o.push(...kg(l))}if(i<Pa)continue;const a=r.functionName!==void 0?`Function '${r.functionName}'`:r.line!==void 0?`The rule at line ${r.line}`:"An allow rule";n.push({rule:"MEMBER_CHAIN_LENGTH",severity:"error",message:`${a} reads a member chain of ${i} terms. The Rules Test API answered a ruleset holding a ${Pa.toLocaleString("en-US")}-term member chain with an internal error instead of compiling it.`,...r.functionName!==void 0?{location:{functionName:r.functionName}}:{},fix:"Shorten the chain: bind a value partway along it to a `let` or a function parameter, and read the rest of the chain from that name."})}}function kg(t){switch(t.type){case"literal":case"identifier":return[];case"memberAccess":return[t.object];case"methodCall":return[t.object,...t.args];case"bracketAccess":return[t.object,t.index];case"sliceAccess":return[t.object,t.start,t.end];case"binaryOp":return[t.left,t.right];case"unaryOp":return[t.operand];case"ternary":return[t.condition,t.consequent,t.alternate];case"inExpr":return[t.element,t.collection];case"isExpr":return[t.value];case"listLiteral":return t.elements;case"mapLiteral":return t.entries.flatMap(e=>[e.key,e.value]);case"pathLiteral":return t.segments.filter(e=>typeof e!="string");case"functionCall":return t.args}}function Eg(t,e){const n=new Map;for(let s=0;s<t.length;s++){const r=t[s];if(!r.rule.operations.some(a=>a==="update"||a==="write"))continue;const i=se(ml(r.rule.condition)),o=r.path;n.has(o)||n.set(o,[]),n.get(o).push({index:s,gate:i,ops:r.rule.operations})}for(const[s,r]of n){const i=new Map;for(const o of r)i.has(o.gate)||i.set(o.gate,[]),i.get(o.gate).push(o.index);for(const[o,a]of i)a.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${a.length} allow rules in '${s}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${a.join(", ")}.`,location:{matchPath:s},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function Ig(t,e){for(const n of t)n.grantCost===null||n.grantCost<os||e.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${n.ruleIndex} in '${n.blockPath}' can evaluate up to ~${n.grantCost} expressions for a request it grants, counting the earlier rules that deny it first. Production denies a request that reaches ${os}.`,location:{ruleIndex:n.ruleIndex,matchPath:n.blockPath},fix:"Put a cheap discriminator first in each rule so earlier rules fail at their gate, split expensive checks so a request evaluates only the branch it needs, or move lookup work into documents."})}function _g(t,e){for(const n of mg(t)){const s=n.calls.slice(0,3).map(r=>{const i=r.cost.min===r.cost.max?`${r.cost.max}`:`${r.cost.min} to ${r.cost.max}`,o=r.reads>0?`, ${r.reads} read${r.reads===1?"":"s"} per call`:"";return`${r.name} (${r.module}): ${r.count} call${r.count===1?"":"s"}, ${i} expressions per call${o}`});e.push({rule:"EXPRESSION_LIBRARY_CALLS",severity:"info",message:`Rule #${n.ruleIndex} in '${n.blockPath}' spends most on these library calls: ${s.join("; ")}. Calls are not memoized: each call pays again.`,location:{ruleIndex:n.ruleIndex,matchPath:n.blockPath}})}}function xg(t,e){const{depths:n,cyclic:s}=Wh(t),r=new Set;for(const o of t.functions)for(const a of cl(o).callees)a!==o.fn&&r.add(a);let i=!1;for(const o of t.functions){if(s.has(o.fn)){i||(i=!0,e.push({rule:"CALL_DEPTH",severity:"error",message:`Function '${o.fn.name}' is part of a recursive call cycle, exceeding the call depth limit of ${Ct.CALL_DEPTH_LIMIT}.`,location:{functionName:o.fn.name,matchPath:o.label},fix:"Remove recursion between helper functions; Firestore rules do not allow recursive calls."}));continue}if(r.has(o.fn))continue;const a=n.get(o.fn)??1;if(a<Ct.CALL_DEPTH_WARN)continue;const c=a>Ct.CALL_DEPTH_LIMIT;e.push({rule:"CALL_DEPTH",severity:c?"error":"warning",message:`Function '${o.fn.name}' starts a function call chain of depth ${a}. Limit is ${Ct.CALL_DEPTH_LIMIT}.`,location:{functionName:o.fn.name,matchPath:o.label},...c?{fix:"Inline intermediate functions to reduce call depth."}:{}})}return n}function Cg(t,e,n,s,r=!1){const i=new Map,o=r?2:Ct.GET_COUNT_ERROR,a=r?2:Ct.GET_COUNT_WARN,c=r?"firestore.get()/firestore.exists()":"get()/exists()/getAfter()/existsAfter()";for(let u=0;u<t.length;u++){const l=e.get(t[u].rule)??i,d=il(t[u].rule.condition,l,new Set,n);d>o?s.push({rule:"GET_COUNT",severity:"error",message:`Rule #${u} may invoke ${d} ${c} calls. Limit is ${o}.`,location:{ruleIndex:u},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):d>=a&&s.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${u} invokes ${d} ${c} calls. Limit is ${o}.`,location:{ruleIndex:u}})}}function Og(t,e,n,s){const r=new Map;for(let i=0;i<t.length;i++){const o=e.get(t[i].rule)??r,a=new Set(o.keys()),c=sp(t[i].rule.condition,a);for(const[u,l]of c)l>=2&&gl(u,o,new Set,n)&&s.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${u}' (contains get/exists) is called ${l} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${l} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${u}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function Tg(t,e,n,s,r){const i=new Map,o=new Set;for(let c=0;c<t.length;c++){const u=e.get(t[c].rule)??i;Ai(t[c].rule.condition,u,new Set,n)&&o.add(c)}if(o.size===0)return;function a(c,u){const l=c.split("/").filter(Boolean),d=u.split("/").filter(Boolean);if(l.length!==d.length)return!1;for(let f=0;f<l.length;f++){const p=l[f];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==d[f])return!1}return!0}for(const c of s)if(!c.requestTime)for(const u of o)a(t[u].path,c.path)&&r.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${c.description}" targets rule #${u} (path '${t[u].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:u,matchPath:t[u].path,testCaseDescription:c.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}const Rg=new Set(["write","create","update","delete"]);function Lg(t,e,n,s=!1){for(let r=0;r<t.length;r++){const i=t[r];if(qt(i.rule.condition)!==!0||!i.rule.operations.some(c=>Rg.has(c)))continue;const a=i.rule.operations.join(", ");n.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${a} at ${i.path} resolves to a constant true predicate — this disables write security for ${e.get(i.rule)?.description??"the matched paths"}. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:i.path},fix:s?"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.size < 5 * 1024 * 1024 && request.resource.contentType.matches('image/.*')).":"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Cl(t,e,n){const s=[...e,...t.path.segments],r=qh(s);r&&t.allows.forEach((i,o)=>n.set(i,{...r,ruleIndex:o}));for(const i of t.children)Cl(i,s,n);return n}function Ng(t,e){for(const[n,s]of t)s.kind!=="subtree"||qt(n.condition)!==!0||e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`match ${s.fullPath} allows ${n.operations.join(", ")} on ${s.description} with an always-true condition.`,location:{ruleIndex:s.ruleIndex,matchPath:s.fullPath},fix:"Narrow the match path to the collections that must be open, for example match /{path=**}/<collection>/{id} for one collection group, or replace `if true` with a real predicate (auth identity, ownership, role)."})}function Mg(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function Dg(t){return t.map(Mg).join("/")}function _i(t,e){const n=Dg(t.path.segments),s=e?`${e}/${n}`:n,r=[{block:t,normalizedPath:s}];for(const i of t.children)r.push(..._i(i,s));return r}function $g(t,e,n){const s=_i(t,""),r=_i(e,""),i=new Map;for(const{block:o,normalizedPath:a}of s)i.has(a)||i.set(a,o);for(const{block:o,normalizedPath:a}of r){const c=i.get(a);if(!c){o.allows.length>0&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${a}`,location:{matchPath:a}});continue}for(const u of o.allows){const l=[...u.operations].sort().join(","),d=c.allows.find(m=>[...m.operations].sort().join(",")===l),f=u.operations.join(", ");if(!d){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${a} allow ${f}`,location:{matchPath:a}});continue}const p=Ks(u.condition).map(pe),h=new Set(Ks(d.condition).map(pe));for(const m of p)h.has(m)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${a} allow ${f}: ${m}`,location:{matchPath:a}})}}}function xi(t,e={}){const n=[];n.push(...fp(t)),gg(t,n);const s=Es(t);if(!s.ok)return{warnings:n,metrics:ja(t),parseError:s.error};try{return jg(s.ast,t,e,n)}catch(r){if(!(r instanceof RangeError))throw r;return n.push(Pg()),{warnings:n,metrics:ja(t)}}}function ja(t){return{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0}}function Pg(){return{rule:"EXPRESSION_TOO_DEEP",severity:"error",message:"An expression chains or nests more terms, counting the bodies of the functions it calls, than the linter can analyze, so the remaining checks did not run. This is a limit of the linter; production's limit for this expression is not measured.",fix:"Shorten the chain: bind a value partway along it to a `let` or a function parameter, and read the rest of the chain from that name."}}function jg(t,e,n,s){const r=t.service?.name==="firebase.storage",i=rp(t),o=Ao(t.service.match),a=al(t),c=new Map(a.functions.map(v=>[v.fn,v.functions])),u=new Map(a.rules.map(v=>[v.rule,v.functions]));Ag(t,i,s);const l=mo(t);bg(l,s),vg(l,s),wg(l,s),Sg(t,l,s),yg(i,s),Eg(o,s);const d=Tp(t);Ig(d.rules,s),_g(t,s);const f=xg(a,s);Cg(o,u,c,s,r),Og(o,u,c,s),s.push(...Ip(t,{allowDebug:n.allowDebug}));const p=new Map;for(const v of t.service.match.children)Cl(v,[],p);if(Lg(o,p,s,r),Ng(p,s),n.testCases&&n.testCases.length>0&&Tg(o,u,c,n.testCases,s),n.previousSource){const v=Es(n.previousSource);v.ok&&$g(t.service.match,v.ast.service.match,s)}let h={depth:0,op:""},m={count:0,fn:""};for(const v of i){const E=np(v.body);E.depth>h.depth&&(h={depth:E.depth,op:E.op}),v.lets.length>m.count&&(m={count:v.lets.length,fn:v.name})}let g=0;for(const v of f.values())v>g&&(g=v);const b=new Map;let y=0;for(const v of d.rules)v.grantCost!==null&&v.grantCost>y&&(y=v.grantCost);let w=0;for(const v of o){const E=u.get(v.rule)??b,I=il(v.rule.condition,E,new Set,c);I>w&&(w=I)}return{warnings:s,metrics:{sourceSize:e.length,functionCount:i.length,allowRuleCount:o.length,maxChainDepth:h.depth,maxChainOp:h.op,maxLetBindings:m.count,maxLetBindingsFunction:m.fn,maxCallDepth:g,maxEstimatedExpressions:y,getCallCount:w}}}class _ extends Error{expr;constructor(e,n){super(e),this.expr=n,this.name="EvalError"}}class cn extends _{constructor(e,n){super(e,n),this.name="ResourceLimitError"}}class Ol extends cn{position;constructor(e,n){super(e),this.position=n,this.name="ExpressionLimitError"}}const Fg="Divide by zero error.";function ts(t){return`Function not found error: Name: [${t}].`}function qg(t,e){return Rl(Tl(t),e)}function J0(t){const e=Tl(t);if(e.hasAsserts)return s=>Rl(e,s);const n=new Bg(e);return s=>n.matches(s)}function Tl(t){const e=[{kind:"accept"}],n=o=>{const a=e.length;return e.push(o),a},s=(o,a)=>{switch(o.kind){case"empty":return a;case"char":return n({kind:"char",test:o.test,out:a});case"assert":return n({kind:"assert",check:o.check,out:a});case"seq":{let c=a;for(let u=o.items.length-1;u>=0;u--)c=s(o.items[u],c);return c}case"alt":{const c=s(o.left,a),u=s(o.right,a);return n({kind:"split",out1:c,out2:u})}case"rep":{let c=a;if(o.max===1/0){const u=n({kind:"split",out1:0,out2:a}),l=s(o.body,u);e[u]={kind:"split",out1:l,out2:a},c=u}else for(let u=o.min;u<o.max;u++){const l=s(o.body,c);c=n({kind:"split",out1:l,out2:c})}for(let u=o.min-1;u>=0;u--)c=s(o.body,c);return c}}},r=s(t,0),i=e.some(o=>o.kind==="assert");return{states:e,start:r,hasAsserts:i}}function Rl(t,e){const n=new Nl(t.states);let s=n.of([t.start],e,0);for(let r=0;r<e.length&&s.length>0;r++)s=n.of(Ll(t.states,s,e[r]),e,r+1);return s.includes(0)}function Ll(t,e,n){const s=[];for(const r of e){const i=t[r];i.kind==="char"&&i.test(n)&&s.push(i.out)}return s}class Nl{states;marks;mark=0;constructor(e){this.states=e,this.marks=new Uint32Array(e.length)}of(e,n,s){this.nextMark();const r=[...e],i=[];for(;r.length>0;){const o=r.pop();if(this.marks[o]===this.mark)continue;this.marks[o]=this.mark;const a=this.states[o];a.kind==="split"?r.push(a.out1,a.out2):a.kind==="assert"?a.check(n,s)&&r.push(a.out):i.push(o)}return i}nextMark(){this.mark++,this.mark===4294967295&&(this.marks.fill(0),this.mark=1)}}const Ug=1<<22,Fa=[];class Bg{nfa;closure;sets=[];accepting=[];transitions=[];index=new Map;stored=0;start=0;constructor(e){this.nfa=e,this.closure=new Nl(e.states),this.reset()}matches(e){let n=this.start;for(const s of e)if(n=this.step(n,s),this.sets[n].length===0)return!1;return this.accepting[n]}step(e,n){const s=this.transitions[e].get(n);if(s!==void 0)return s;const r=this.closure.of(Ll(this.nfa.states,this.sets[e],n),Fa,0);if(this.stored+r.length+1>Ug)return this.reset(),this.intern(r);const i=this.intern(r);return this.transitions[e].set(n,i),this.stored++,i}intern(e){e.sort((i,o)=>i-o);const n=e.join(","),s=this.index.get(n);if(s!==void 0)return s;const r=this.sets.length;return this.sets.push(e),this.accepting.push(e.includes(0)),this.transitions.push(new Map),this.index.set(n,r),this.stored+=e.length,r}reset(){this.sets=[],this.accepting=[],this.transitions=[],this.index=new Map,this.stored=0,this.start=this.intern(this.closure.of([this.nfa.start],Fa,0))}}const ge=Symbol.for("pyric.RulesValue.NO_OP");class oe{field(e){return null}callMethod(e,n){return ge}binaryOp(e,n){return ge}}function Ge(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function J(t){return t===null?"null":t===void 0?"undefined":t instanceof oe?t.typeName:t instanceof fe?"set":t instanceof Js?"map_diff":typeof t=="number"?Number.isInteger(t)?"int":"float":typeof t=="boolean"?"bool":Array.isArray(t)?"list":Ge(t)?"map":typeof t}function Ts(t,e){if(e<0||e>=t.length)return!1;const n=t[e];if(n.length!==1)return!1;const s=n.charCodeAt(0);return s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||s===95}function xo(t,e,n,s){const r=/\\[1-9]/.test(e),i=/\(\?<?[=!]/.test(e);if(r||i){const o=r?"backreference":"lookaround";throw new Error(`${t}() pattern uses an RE2-unsupported construct (${o}) that production would reject`)}try{return new RegExp(ho(n),s)}catch(o){throw new Error(`Invalid regex '${e}' in ${t}(): ${o.message}`)}}function zg(t,e){xo("matches",t,`^(?:${t})$`);const n=Wg(t);return qg(n,Array.from(e))}function Xt(t,e){let n="u";e&&(n="iu");try{const s=new RegExp(`^${t}$`,n);return r=>s.test(r)}catch{const s=e?"i":"",r=new RegExp(`^${t}$`,s);return i=>r.test(i)}}function Wg(t){let e=0,n=!1,s=!1,r=!1;const i=d=>{let f=!1;for(const p of d)p==="-"?f=!0:p==="i"?n=!f:p==="m"?s=!f:p==="s"&&(r=!f)},o=()=>{let d=a();for(;e<t.length&&t[e]==="|";){e++;const f=a();d={kind:"alt",left:d,right:f}}return d},a=()=>{const d=[];for(;e<t.length&&t[e]!=="|"&&t[e]!==")";)d.push(c());return d.length===0?{kind:"empty"}:d.length===1?d[0]:{kind:"seq",items:d}},c=()=>{let d=l();for(;e<t.length;){const f=t[e];if(f==="*"||f==="+"||f==="?"){e++,e<t.length&&t[e]==="?"&&e++;let p=0,h=1/0;f==="+"?p=1:f==="?"&&(h=1),d={kind:"rep",body:d,min:p,max:h}}else if(f==="{"){const p=/^\{(\d+)(?:,(\d*))?\}/.exec(t.slice(e));if(!p)break;e+=p[0].length,e<t.length&&t[e]==="?"&&e++;const h=Number(p[1]);let m=h;if(p[2]!==void 0&&(m=p[2]===""?1/0:Number(p[2])),h>m||h>1e3||m!==1/0&&m>1e3)throw new Error(`Invalid repeat count in '${t}'`);d={kind:"rep",body:d,min:h,max:m}}else break}return d},u=(d,f)=>{if(f){const p=d.toLowerCase(),h=d.toUpperCase();return{kind:"char",test:m=>m===p||m===h}}return{kind:"char",test:p=>p===d}},l=()=>{const d=t[e];if(d==="("){e++;const h=n,m=s,g=r;if(t[e]==="?")if(e++,t[e]===":")e++;else if(t[e]==="<"||t[e]==="P"&&t[e+1]==="<")e=t.indexOf(">",e)+1;else{const y=/^[imsU-]+/.exec(t.slice(e));if(y){if(i(y[0]),e+=y[0].length,t[e]===")")return e++,{kind:"empty"};t[e]===":"&&e++}}const b=o();return t[e]===")"&&e++,n=h,s=m,r=g,b}if(d==="["){const h=e;for(e++,t[e]==="^"&&e++,t[e]==="]"&&e++;e<t.length&&t[e]!=="]";)t[e]==="\\"?e+=2:e++;t[e]==="]"&&e++;const m=ho(t.slice(h,e));return{kind:"char",test:Xt(m,n)}}if(d==="^"){e++;const h=s;return{kind:"assert",check:(m,g)=>g===0||h&&g>0&&m[g-1]===`
|
|
1704
1704
|
`}}if(d==="$"){e++;const h=s;return{kind:"assert",check:(m,g)=>g===m.length||h&&g<m.length&&m[g]===`
|
|
1705
1705
|
`}}if(d==="."){e++;const h=r;return{kind:"char",test:m=>h||m!==`
|
|
1706
|
-
`&&m!=="\r"}}if(d==="\\"){const h=e;e++;const m=t[e];if(m==="b")return e++,{kind:"assert",check:(y,w)=>Ts(y,w-1)!==Ts(y,w)};if(m==="B")return e++,{kind:"assert",check:(y,w)=>Ts(y,w-1)===Ts(y,w)};if(m==="A")return e++,{kind:"assert",check:(y,w)=>w===0};if(m==="z")return e++,{kind:"assert",check:(y,w)=>w===y.length};if((m==="x"||m==="u")&&t[e+1]==="{"){const y=t.indexOf("}",e+2),w=t.slice(e+2,y);return e=y+1,u(String.fromCodePoint(parseInt(w,16)),n)}if((m==="p"||m==="P")&&t[e+1]==="{"){e=t.indexOf("}",e+2)+1;const w=t.slice(h,e);return{kind:"char",test:Xt(w,n)}}if(m==="d"||m==="D"||m==="w"||m==="W"||m==="s"||m==="S"||m==="t"||m==="n"||m==="r"||m==="v"||m==="f"){e++;const y=t.slice(h,e);return{kind:"char",test:Xt(y,n)}}if(m==="x")return e+=3,{kind:"char",test:Xt(t.slice(h,e),n)};if(m==="u")return e+=5,{kind:"char",test:Xt(t.slice(h,e),n)};if(m==="c")return e+=2,{kind:"char",test:Xt(t.slice(h,e),n)};if(m>="0"&&m<="7"){const y=/^[0-7]{1,3}/.exec(t.slice(e));return e+=y[0].length,{kind:"char",test:Xt(t.slice(h,e),n)}}const g=t.codePointAt(e),b=String.fromCodePoint(g);return e+=b.length,u(b,n)}const f=t.codePointAt(e),p=String.fromCodePoint(f);return e+=p.length,u(p,n)};return o()}function jg(t,e,n){const s=xo("replace",e,e,"g"),r=new RegExp(`${s.source}|`).exec(""),i=r===null?0:r.length-1;return t.replace(s,(...o)=>{const a=o.slice(0,i+1),c=o[o.length-1];let u={};return typeof c=="object"&&c!==null&&(u=c),Fg(n,a,u)})}function Fg(t,e,n){const s=e.length-1;let r="",i=0;for(;i<t.length;){const o=t[i];if(o==="\\"){if(i+1>=t.length)throw new Error("replace() replacement ends with an escape character");r+=t[i+1],i+=2;continue}if(o!=="$"){r+=o,i+=1;continue}const a=t[i+1];if(a==="{"){const l=t.indexOf("}",i+2);if(l===-1)throw new Error(`replace() replacement has an unclosed group name: ${t.slice(i)}`);const d=t.slice(i+2,l);if(!Object.hasOwn(n,d))throw new Error(`replace() replacement names no group: ${t.slice(i,l+1)}`);r+=n[d]??"",i=l+1;continue}if(a===void 0||a<"0"||a>"9")throw new Error(`replace() replacement has an illegal group reference: ${t.slice(i)}`);let c=Number(a),u=i+2;for(;u<t.length&&t[u]>="0"&&t[u]<="9";){const l=c*10+Number(t[u]);if(l>s)break;c=l,u+=1}if(c>s)throw new Error(`replace() replacement names group ${c}, but the pattern has ${s}`);r+=e[c]??"",i=u}return r}function qg(t){const e=t.toExponential();if(e.includes("."))return e;const n=t.toExponential(1);return Number(n)===t?n:e}function Ug(t){if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if(t===0)return Object.is(t,-0)?"-0.0":"0.0";const e=Math.abs(t);if(e>=.001&&e<1e7){const i=String(t);return i.includes(".")?i:`${i}.0`}const[n,s]=qg(t).split("e");return`${n.includes(".")?n:`${n}.0`}E${Number(s)}`}class re extends oe{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Ug(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof re?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,n){const s=n instanceof re?n.value:typeof n=="number"?n:void 0;if(s===void 0)return ge;const r=this.value;switch(e){case"+":return new re(r+s);case"-":return new re(r-s);case"*":return new re(r*s);case"/":return new re(r/s);case"%":return new re(r%s);case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:return ge}}}function qa(t,e){return xr(t,e,(n,s)=>n.value===s.value,Oo)}function Co(t,e){return xr(t,e,(n,s)=>n.float===s.float&&n.value===s.value,Oo)}function et(t,e){return xr(t,e,(n,s)=>n.value===s.value||Number.isNaN(n.value)&&Number.isNaN(s.value),et)}function Oo(t,e){return xr(t,e,(n,s)=>n.float===s.float&&n.value===s.value&&Object.is(n.value,s.value),Oo)}function Ua(t){if(t instanceof re)return{value:t.value,float:!0};if(typeof t=="number")return{value:t,float:!Number.isInteger(t)}}function xr(t,e,n,s){const r=Ua(t),i=Ua(e);if(r||i)return r!==void 0&&i!==void 0&&n(r,i);if(t instanceof oe)return t.equals(e);if(e instanceof oe)return e.equals(t);if(t instanceof fe||e instanceof fe)return t instanceof fe&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,a)=>s(o,e[a]));if(Ge(t)||Ge(e)){if(!Ge(t)||!Ge(e))return!1;const o=Object.keys(t);return o.length!==Object.keys(e).length?!1:o.every(a=>Object.hasOwn(e,a)&&s(t[a],e[a]))}return t===e}class fe{items;constructor(e){this.items=[];for(const n of e)this.items.some(s=>et(s,n))||this.items.push(n)}hasOnly(e){const n=e instanceof fe?e.toArray():e;return this.items.every(s=>n.some(r=>et(s,r)))}equals(e){return!(e instanceof fe)||e.items.length!==this.items.length?!1:this.items.every(n=>e.items.some(s=>et(n,s)))}hasAll(e){const n=e instanceof fe?e.toArray():e;for(const s of n)if(!this.items.some(r=>et(r,s)))return!1;return!0}hasAny(e){const n=e instanceof fe?e.toArray():e;for(const s of n)if(this.items.some(r=>et(r,s)))return!0;return!1}has(e){return this.items.some(n=>et(n,e))}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const n=e.toArray(),s=[];for(const r of this.items)n.some(i=>et(r,i))||s.push(r);return new fe(s)}union(e){const n=e.toArray();return new fe([...this.items,...n])}intersection(e){const n=e.toArray(),s=[];for(const r of this.items)n.some(i=>et(r,i))&&s.push(r);return new fe(s)}}class tn{message;constructor(e){this.message=e}}const Bg=["hasAll","hasAny","hasOnly"],zg=["difference","intersection","union"],Ci=new Set(zg);function Wg(t){return Bg.includes(t)}function Vg(t,e,n){if(e==="size")return n.length!==0?new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: set.size().`):t.size();if(Wg(e)){const s=`set.${e}(set), set.${e}(list)`;if(n.length!==1)return new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: ${s}.`);const[r]=n;return!Array.isArray(r)&&!(r instanceof fe)?new tn(`Unsupported operation error. Received: set.${e}(${J(r)}). Expected: ${s}.`):t[e](r)}if(Ci.has(e)){const s=e;if(n.length!==1)return new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: set.${s}(set).`);const[r]=n;return r instanceof fe?t[s](r):new tn(`Unsupported operation error. Received: set.${s}(${J(r)}). Expected: set.${s}(set).`)}return new tn(ts(e))}class Js{before;after;constructor(e,n){this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))Object.hasOwn(this.before,n)||e.push(n);return new fe(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))Object.hasOwn(this.after,n)||e.push(n);return new fe(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))Object.hasOwn(this.before,n)&&!et(this.before[n],this.after[n])&&e.push(n);return new fe(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const s of n)(!Object.hasOwn(this.before,s)||!Object.hasOwn(this.after,s)||!et(this.before[s],this.after[s]))&&e.push(s);return new fe(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))Object.hasOwn(this.after,n)&&et(this.before[n],this.after[n])&&e.push(n);return new fe(e)}}class Tl{message;constructor(e){this.message=e}}const Ba=new Set(["diff","get","keys","values"]),Rl=new WeakMap;function Gg(t){const e={},n=[];for(const[s,r]of t)Object.hasOwn(e,s)||n.push(s),Object.defineProperty(e,s,{value:r,enumerable:!0,writable:!0,configurable:!0});return Rl.set(e,n),e}function Hg(t,e,n){return n.length!==0?new Tl(`Incorrect number of arguments. Received: ${n.length}. Expected: map.${t}().`):t==="keys"?Kg(e):Zg(e)}function Kg(t){return Object.keys(t).sort(Jg)}function Zg(t){return(Rl.get(t)??Object.keys(t)).map(n=>t[n])}function Jg(t,e){const n=Math.min(t.length,e.length);for(let s=0;s<n;s+=1)if(t.charCodeAt(s)!==e.charCodeAt(s))return t.codePointAt(s)-e.codePointAt(s);return t.length-e.length}function Qg(t,e,n){for(const s of[t,e-1])if(s<0||s>=n)return Cr(s,n);return t>e?`Illegal range error. From index: [${t}] , To index: [${e}].`:null}class Re{message;constructor(e){this.message=e}}function Oi(t){return`Property ${t} is undefined on object.`}function Cr(t,e){return`Index out of bound error. Index: [${t}] , size: [${e}].`}function Yg(t,e){return typeof e!="number"||!Number.isInteger(e)?new Re(`Unsupported operation error. Received: list[${J(e)}]. Expected: list[int].`):e<0||e>=t.length?new Re(Cr(e,t.length)):t[e]}function Ll(t,e){if(!Object.hasOwn(t,e))return new Re(Oi(e));const n=t[e];return n===void 0?new Re(Oi(e)):n}function Xg(t,e){return typeof e!="number"||!Number.isInteger(e)?new Re(`Unsupported operation error. Received: string[${J(e)}]. Expected: string[int].`):e<0||e>=t.length?new Re(Cr(e,t.length)):t[e]}function Nl(t){return t instanceof oe&&t.typeName==="path"}const ey="Function not found error: Name: [[]].";function Ml(t,e){if(Array.isArray(t))return Yg(t,e);if(typeof t=="string")return Xg(t,e);if(Nl(t)){if(typeof e=="number"&&Number.isInteger(e))return e>=0&&e<t.segments.length?t.segments[e]:new Re(Cr(e,t.segments.length));const n=String(e);return Object.hasOwn(t.bindings,n)?t.bindings[n]:new Re(Oi(n))}return t instanceof oe?new Re(ey):Ll(t,String(e))}function ty(t,e){return Ge(t)?Ll(t,e):Nl(t)?Ml(t,e):new Re(`Type error. Received: [${J(t)}] Expected: [map,path].`)}function ny(t,e,n){if(typeof e!="number"||!Number.isInteger(e))return new Re(`Slice start must be an integer, got ${J(e)}`);if(typeof n!="number"||!Number.isInteger(n))return new Re(`Slice end must be an integer, got ${J(n)}`);if(typeof t=="string"||Array.isArray(t)){const s=Qg(e,n,t.length);return s?new Re(s):t.slice(e,n)}return new Re(`Slice not supported on ${J(t)}`)}class Fs{message;constructor(e){this.message=e}}function sy(t,e){return e==null?new Fs("Null value error."):Array.isArray(e)?e.some(n=>Co(n,t)):e instanceof fe?e.has(t):Ge(e)?typeof t!="string"?new Fs(`Unsupported operation error. Received: map.in(${J(t)}). Expected: map.in(string).`):Object.hasOwn(e,t):new Fs("Function not found error: Name: [in].")}const za="0123456789ABCDEF";function ry(t){let e="";for(let n=0;n<t.length;n++){const s=t[n];e+=za[s>>>4]+za[s&15]}return e}function iy(t){let e="";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function oy(t,e){const n=Math.min(t.length,e.length);for(let s=0;s<n;s++)if(t[s]!==e[s])return t[s]<e[s]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let He=class Qn extends oe{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Qn(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const n=new Uint8Array(e.length/2);for(let s=0;s<n.length;s++)n[s]=parseInt(e.substr(s*2,2),16);return new Qn(n)}size(){return this.data.length}toBase64(){return iy(this.data)}toHexString(){return ry(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Qn)||this.data.length!==e.data.length)return!1;for(let n=0;n<this.data.length;n++)if(this.data[n]!==e.data[n])return!1;return!0}callMethod(e,n){switch(e){case"size":case"toBase64":case"toHexString":if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: bytes.${e}().`);return e==="size"?this.size():e==="toBase64"?this.toBase64():this.toHexString()}return ge}binaryOp(e,n){if(!(n instanceof Qn))return ge;const s=oy(this.data,n.data);switch(e){case"<":return s<0;case"<=":return s<=0;case">":return s>0;case">=":return s>=0}return ge}};const ay=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class nt extends oe{typeName="path";segments;bindings;constructor(e,n={}){super(),this.segments=e,this.bindings=n}static fromString(e){const n=e.startsWith("/")?e.slice(1):e;return n.length===0?new nt([]):new nt(n.split("/"))}bind(e){const n=[],s={...this.bindings};for(const r of this.segments){const i=r.match(ay);if(!i){n.push(r);continue}const o=i[1];if(Object.hasOwn(e,o)){const a=e[o];if(a==null)throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const c=String(a);n.push(c),s[o]=c}else n.push(r)}return new nt(n,s)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof nt)||this.segments.length!==e.segments.length)return!1;for(let n=0;n<this.segments.length;n++)if(this.segments[n]!==e.segments[n])return!1;return!0}callMethod(e,n){switch(e){case"bind":{if(n.length!==1)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: path.bind(map).`);const s=n[0];if(s==null||typeof s!="object"||Array.isArray(s)||s instanceof oe)throw new TypeError(`Path.bind() requires a Map argument, got ${s===null?"null":typeof s}`);return this.bind(s)}default:return ge}}}class Gt extends _{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class cy{entries=[];parents=[];frames=[];capture(e,n){const s=this.entries.length,r=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:Ae(e),kind:e.type,parent:r};e.type==="binaryOp"&&(i.operator=e.op),this.stampFrame(i),this.entries.push(i),this.parents.push(s);try{const o=n();return this.entries[s].value=o,o}catch(o){throw this.entries[s].error=o instanceof Error?o.message:String(o),o}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,s={source:Ae(e),kind:e.type,parent:n,skipped:!0};e.type==="binaryOp"&&(s.operator=e.op),this.stampFrame(s),this.entries.push(s)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,n){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:n})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function uy(t,e,n,s){const i=f=>f*Math.PI/180,o=i(t),a=i(n),c=i(n-t),u=i(s-e),l=Math.sin(c/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)))}class ut extends oe{typeName="latlng";lat;lng;constructor(e,n){super(),this.lat=e,this.lng=n}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof ut&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,n){switch(e){case"latitude":case"longitude":if(n.length!==0)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: latlng.${e}().`);return e==="latitude"?this.lat:this.lng;case"distance":{if(n.length!==1)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: latlng.distance(latlng).`);const s=n[0];if(!(s instanceof ut))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof s}`);return uy(this.lat,this.lng,s.lat,s.lng)}default:return ge}}}const En=1e9,Wa={w:10080*60,d:1440*60,h:3600,m:60,s:1};function ly(t,e){let n=t+Math.trunc(e/En),s=e%En;return n>0&&s<0?(n-=1,s+=En):n<0&&s>0&&(n+=1,s-=En),{seconds:n,nanos:s}}class ke extends oe{typeName="duration";seconds;nanos;constructor(e,n){super();const s=ly(e,n);this.seconds=s.seconds,this.nanos=s.nanos}static fromValue(e,n){if(n in Wa)return new ke(e*Wa[n],0);if(n==="ms"){const s=Math.trunc(e/1e3),r=e-s*1e3;return new ke(s,r*1e6)}if(n==="ns"){const s=Math.trunc(e/En),r=e-s*En;return new ke(s,r)}throw new Error(`Unknown duration unit '${n}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,n,s,r){return new ke(e*3600+n*60+s,r)}static abs(e){return new ke(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,n=Math.abs(this.seconds),s=Math.abs(this.nanos);return`${e?"-":""}${n}.${s.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ke&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){switch(e){case"seconds":case"nanos":if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: duration.${e}().`);return e==="seconds"?this.seconds:this.nanos;default:return ge}}binaryOp(e,n){if(!(n instanceof ke))return ge;switch(e){case"+":return new ke(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new ke(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return ge}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const Va=1e9,dy=864e5,Qr=86400,Yr=60;function fy(t,e){const n=Math.floor(e/Va);return{seconds:t+n,nanos:e-n*Va}}let ve=class It extends oe{typeName="timestamp";seconds;nanos;constructor(e,n){super();const s=fy(e,n);this.seconds=s.seconds,this.nanos=s.nanos}static fromMillis(e){const n=Math.floor(e/1e3),s=e-n*1e3;return new It(n,s*1e6)}static fromYMD(e,n,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(s)||e<1||e>9999||n<1||n>12||s<1||s>31)throw new RangeError(`Date is not valid. year: ${e}, month: ${n} day: ${s}.`);const r=new Date(0);if(r.setUTCFullYear(e,n-1,s),r.setUTCHours(0,0,0,0),r.getUTCFullYear()!==e||r.getUTCMonth()!==n-1||r.getUTCDate()!==s)throw new RangeError(`Date is not valid. year: ${e}, month: ${n} day: ${s}.`);return It.fromMillis(r.getTime())}static fromIsoString(e){return It.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),n=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${n}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof It&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){const s=()=>{if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: timestamp.${e}().`)};switch(e){case"seconds":return s(),(this.seconds%Yr+Yr)%Yr;case"nanos":return s(),this.nanos;case"toMillis":return s(),this.toMillis();case"year":return s(),this.asDate().getUTCFullYear();case"month":return s(),this.asDate().getUTCMonth()+1;case"day":return s(),this.asDate().getUTCDate();case"hours":return s(),this.asDate().getUTCHours();case"minutes":return s(),this.asDate().getUTCMinutes();case"dayOfWeek":{s();const r=this.asDate().getUTCDay();return r===0?7:r}case"dayOfYear":{s();const r=this.asDate(),i=Date.UTC(r.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-i)/dy)+1}case"date":return s(),It.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{s();const r=(this.seconds%Qr+Qr)%Qr,i=Math.floor(r/3600),o=Math.floor(r%3600/60),a=r%60;return ke.fromTime(i,o,a,this.nanos)}default:return ge}}asDate(){return new Date(this.toMillis())}binaryOp(e,n){if(n instanceof It)switch(e){case"-":return new ke(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return ge}if(n instanceof ke)switch(e){case"+":return new It(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new It(this.seconds-n.seconds,this.nanos-n.nanos);default:return ge}return ge}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};class Is{message;constructor(e){this.message=e}}const Ga=-9223372036854776e3,Ha=2**63,hy=-(2n**63n),py=2n**63n-1n,my=/^[+-]?\d+$/,gy=/^[+-]?(?:NaN|Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?[fFdD]?)$/,yy=/^([+-]?)0[xX]([0-9a-fA-F]*)(?:\.([0-9a-fA-F]*))?[pP]([+-]?\d+)[fFdD]?$/;function Ti(t,e){return new Is(`Type conversion error. Argument: [${t}], From type: [string], To type: [${e}].`)}function To(t,e,n){return new Is(`Unsupported operation error. Received: ${t}(${J(e)}). Expected: ${n}.`)}function by(t){return Number.isNaN(t)?0:t<=Ga?Ga:t>=Ha?Ha:Math.trunc(t)+0}function vy(t){if(!my.test(t))return Ti(t,"int");const e=BigInt(t);return e<hy||e>py?Ti(t,"int"):Number(e)}function wy(t){const[,e,n,s="",r]=t;if(n.length+s.length===0)return;const o=[...n+s].reduce((a,c)=>a*16+parseInt(c,16),0)*2**(Number(r)-4*s.length);return e==="-"?-o:o}function Sy(t){const e=t.replace(/^[\x00-\x20]+|[\x00-\x20]+$/g,"");if(gy.test(e))return parseFloat(e.replace(/[fFdD]$/,""));const n=yy.exec(e),s=n?wy(n):void 0;return s===void 0?Ti(t,"float"):s}const Ay={overloads:"int(int), int(float), int(string)",convert(t){return typeof t=="number"?t:t instanceof re?by(t.value):typeof t=="string"?vy(t):To("int",t,this.overloads)}},ky={overloads:"float(int), float(float), float(string)",convert(t){if(t instanceof re)return t;if(typeof t=="number")return new re(t);if(typeof t=="string"){const e=Sy(t);return typeof e=="number"?new re(e):e}return To("float",t,this.overloads)}},Ey={overloads:"string(int), string(float), string(null), string(string), string(bool), string(path)",convert(t){return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t===null?"null":t instanceof re||t instanceof oe&&t.typeName==="path"?t.toString():To("string",t,this.overloads)}},Iy=new Map([["int",Ay],["float",ky],["string",Ey]]);function Dl(t){return Iy.get(t)}function $l(t,e){return e.length!==1?new Is(`Incorrect number of arguments. Received: ${e.length}. Expected: ${t.overloads}.`):t.convert(e[0])}class qs{message;constructor(e){this.message=e}}const Ri=-9223372036854776e3,Ka=2**63;function _y(t){return Number.isNaN(t)?0:t<=Ri?Ri:t>=Ka?Ka:Math.round(t)+0}const zn=t=>new re(t),xy=new Map([["abs",{overloads:"math.abs(int), math.abs(float)",arity:1,apply:([t],[e])=>e?zn(Math.abs(t)):t===Ri?t:Math.abs(t)}],["ceil",{overloads:"math.ceil(float)",arity:1,apply:([t])=>zn(Math.ceil(t))}],["floor",{overloads:"math.floor(float)",arity:1,apply:([t])=>zn(Math.floor(t))}],["round",{overloads:"math.round(float)",arity:1,apply:([t])=>_y(t)}],["sqrt",{overloads:"math.sqrt(float)",arity:1,apply:([t])=>zn(Math.sqrt(t))}],["pow",{overloads:"math.pow(float, float)",arity:2,apply:([t,e])=>zn(Math.pow(t,e))}],["isNaN",{overloads:"math.isNaN(float)",arity:1,apply:([t])=>Number.isNaN(t)}]]);function Cy(t){if(t instanceof re)return{value:t.value,isFloat:!0};if(typeof t=="number")return{value:t,isFloat:!Number.isInteger(t)}}function Oy(t,e){const n=xy.get(t);if(!n)return new qs(`Function not found error: Name: [math.${t}].`);if(e.length!==n.arity)return new qs(`Incorrect number of arguments. Received: ${e.length}. Expected: ${n.overloads}.`);const s=e.map(Cy);return s.some(r=>r===void 0)?new qs(`Unsupported operation error. Received: math.${t}(${e.map(J).join(", ")}). Expected: ${n.overloads}.`):n.apply(s.map(r=>r.value),s.map(r=>r.isFloat))}class Mt{message;constructor(e){this.message=e}}const Ty=Dl("string");function Or(t,e,n){if(n.length!==1)return new Mt(`Incorrect number of arguments. Received: ${n.length}. Expected: list.${t}(${e}).`);const[s]=n;return(e==="list"?Array.isArray(s):typeof s=="string")?s:new Mt(`Unsupported operation error. Received: list.${t}(${J(s)}). Expected: list.${t}(${e}).`)}function Ry(t,e){const n=Or("concat","list",e);return n instanceof Mt?n:[...t,...n]}function Ly(t,e){const n=Or("removeAll","list",e);return n instanceof Mt?n:t.filter(s=>!n.some(r=>Co(s,r)))}function Ny(t,e,n){const s=Or(t,"list",n);if(s instanceof Mt)return s;const r=(o,a)=>o.some(c=>Co(c,a)),i=s;return t==="hasAll"?i.every(o=>r(e,o)):t==="hasAny"?i.some(o=>r(e,o)):e.every(o=>r(i,o))}const Za=new Set(["concat","hasAll","hasAny","hasOnly","join","removeAll","toSet"]);function My(t,e){const n=Or("join","string",e);if(n instanceof Mt)return n;const s=[];for(const r of t){const i=$l(Ty,[r]);if(i instanceof Is)return new Mt(i.message);s.push(i)}return s.join(n)}class wt extends oe{typeName="reference";path;constructor(e){super(),this.path=Dy(e)}static fromResourceName(e){return new wt(Pl(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof wt?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,n){return ge}}function Dy(t){let e=Pl(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Pl(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class Ht extends oe{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let n=0;n<e.length;n++)if(typeof e[n]!="number")throw new TypeError(`Vector: element at index ${n} is not a number (got ${typeof e[n]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Ht)||e.value.length!==this.value.length)return!1;for(let n=0;n<this.value.length;n++)if(e.value[n]!==this.value[n])return!1;return!0}callMethod(e,n){return ge}}function jl(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}const $y=new Set(["id","path","bypassRules","auth","env"]);function Py(t){const e=Object.keys(t);if(e.length<2||!e.every(s=>$y.has(s))||typeof t.id!="string"||typeof t.path!="string")return!1;const n=t.path.split("/");return n.length>=2&&n.length%2===0&&n.every(s=>s.length>0)&&n[n.length-1]===t.id}function jy(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),s=atob(e+n),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);return r}function Fy(t){const e=atob(t),n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n}function qy(t){return typeof t=="object"&&t!==null&&(t.__type==="serverTimestamp"||t._methodName==="serverTimestamp"||t._methodName==="FieldValue.serverTimestamp")}function Li(t,e){const n={};for(const[s,r]of Object.entries(t))n[s]=Fl(r,e);return n}function Fl(t,e){return qy(t)?e:Array.isArray(t)?t.map(n=>Fl(n,e)):jl(t)?Li(t,e):t}function tt(t){if(typeof t=="number"&&!Number.isInteger(t))return new re(t);if(Array.isArray(t))return t.map(tt);if(jl(t)){if(typeof t.__type=="string")switch(t.__type){case"float":if(typeof t.value=="number")return new re(t.value);break;case"timestamp":if(typeof t.seconds=="number"&&typeof t.nanos=="number")return new ve(t.seconds,t.nanos);break;case"bytes":if(typeof t.base64=="string")return new He(jy(t.base64));break;case"latlng":if(typeof t.lat=="number"&&typeof t.lng=="number")return new ut(t.lat,t.lng);break;case"duration":if(typeof t.seconds=="number"&&typeof t.nanos=="number")return new ke(t.seconds,t.nanos);break;case"reference":if(typeof t.path=="string")return new wt(t.path);break;case"path":if(Array.isArray(t.segments))return new nt(t.segments);break}if(t.__type__==="__vector__"&&Array.isArray(t.value))return new Ht(Object.freeze(t.value.slice()));if(typeof t.type=="string")switch(t.type){case"firestore/timestamp/1.0":if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number")return new ve(t.seconds,t.nanoseconds);break;case"firestore/bytes/1.0":if(typeof t.bytes=="string")return new He(Fy(t.bytes));break;case"firestore/geoPoint/1.0":if(typeof t.latitude=="number"&&typeof t.longitude=="number")return new ut(t.latitude,t.longitude);break;case"firestore/vectorValue/1.0":if(Array.isArray(t.vectorValues))return new Ht(Object.freeze(t.vectorValues.slice()));break}return Py(t)?new wt(t.path):Object.fromEntries(Object.entries(t).map(([e,n])=>[e,tt(n)]))}return t}function Ja(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function Tr(t){const e=typeof t=="string"?t.split("/").filter(Boolean):t;return e.length===0||e.length%2!==0?!1:!e.some(n=>/^\{.*\}$/.test(n))}function Mn(t){let e=t.replace(/\$\(database\)/g,"(default)");const n="/databases/(default)/documents/";e.startsWith(n)?e=e.slice(n.length):e.startsWith("/databases/(default)/documents")&&(e=e.slice(30)),e.startsWith("/")&&(e=e.slice(1));const s=e.split("/").filter(i=>i.length>0&&i!=="."),r=[];for(const i of s)i===".."?r.length>1&&r.pop():r.push(i);return r.join("/")}function Ni(t,e){const n=t.split("/").filter(Boolean);return{data:tt(e),id:n.at(-1)??"",__name__:new nt(["databases","(default)","documents",...n])}}function Qa(t,e){const n=Mn(t),s=n.split("/").filter(Boolean);if(!Tr(s))throw new _(`get() requires a path pointing to a document (even segment count), got '${n}'`);let r=e.mockDocuments.get(n);if(!r&&e.getDoc){const i=e.getDoc(n);if(i){const o=tt(i);e.mockDocuments.set(n,o),r=o}}if(r){const i=tt(r);return e.identitylessFunctionMocks?.has(n)?{data:i}:Ni(n,i)}throw new _(`get() of non-existent document '${n}' (guard with exists() first)`)}function Ya(t,e){const n=Mn(t),s=n.split("/").filter(Boolean);if(!Tr(s))throw new _(`exists() requires a path pointing to a document (even segment count), got '${n}'`);const r=e.existsMocks?.get(n);if(r!==void 0)return r;if(e.mockDocuments.has(n))return!0;if(e.getDoc){const i=e.getDoc(n);if(i)return e.mockDocuments.set(n,tt(i)),!0}return!1}const Mi=10,Uy=20,By=Symbol.for("pyric.firestore.lookupCollector"),Xa=new WeakMap;function zy(t){const e=Xa.get(t);if(e!==void 0)return e;const n=new ql(Uy);return Xa.set(t,n),n}class Wy extends cn{constructor(e){super(e),this.name="LookupBudgetError"}}class ql{limit;accessed=new Set;constructor(e=Mi){this.limit=e}charge(e,n){const s=`${e}:${n}`;if(this.accessed.has(s))return;const r=this.limit===Mi;if(this.accessed.size>=this.limit){let i=`multi-document batch/transaction (${this.limit} allowed across the atomic operation)`;throw r&&(i="request (production allows 10 per request; the 11th distinct access fails the evaluation)"),new Wy(`document access limit exceeded: already read ${this.limit} distinct documents via get()/exists()/getAfter()/existsAfter() in this ${i}`)}this.accessed.add(s)}}function Rs(t,e,n){if(!t.lookupBudget)return;const s=Mn(n);if(!Tr(s))return;if(e==="doc"){const a=globalThis[By];a!==void 0&&a.add(s)}t.lookupBudget.charge(e,s);const i=t.batchProjection;i!==void 0&&zy(i).charge(e,s)}function Vy(t){if(t instanceof He)return t;if(typeof t=="string")return He.fromUtf8(t);throw new _(`hashing.* requires Bytes or String, got ${typeof t}`)}function Gy(t,e){if(t!=="md5"&&t!=="sha256"&&t!=="crc32"&&t!=="crc32c")throw new _(ts(`hashing.${t}`));if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: hashing.${t}(bytes), hashing.${t}(string).`);const n=Vy(e[0]);switch(t){case"md5":return new He(Xy(n.data));case"sha256":return new He(tb(n.data));case"crc32":{const s=Ky(n.data);return new He(ec(s))}case"crc32c":{const s=Jy(n.data);return new He(ec(s))}}}function ec(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const Hy=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let s=0;s<8;s++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Ky(t){let e=4294967295;for(let n=0;n<t.length;n++)e=Hy[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const Zy=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let s=0;s<8;s++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Jy(t){let e=4294967295;for(let n=0;n<t.length;n++)e=Zy[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function Ul(t,e){const n=(t.length+8>>>6)+1<<6,s=new Uint8Array(n);s.set(t),s[t.length]=128;const r=new DataView(s.buffer),i=t.length<<3>>>0,o=Math.floor(t.length/536870912);return e?(r.setUint32(n-8,i,!0),r.setUint32(n-4,o,!0)):(r.setUint32(n-8,o,!1),r.setUint32(n-4,i,!1)),r}const Qy=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],Yy=new Uint32Array([3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745]);function Xy(t){const e=Ul(t,!0);let n=1732584193,s=4023233417,r=2562383102,i=271733878;const o=new Uint32Array(16);for(let u=0;u<e.byteLength;u+=64){for(let h=0;h<16;h++)o[h]=e.getUint32(u+h*4,!0);let l=n,d=s,f=r,p=i;for(let h=0;h<64;h++){let m,g;h<16?(m=d&f|~d&p,g=h):h<32?(m=p&d|~p&f,g=5*h+1&15):h<48?(m=d^f^p,g=3*h+5&15):(m=f^(d|~p),g=7*h&15);const b=l+m+Yy[h]+o[g]|0,y=Qy[h];l=p,p=f,f=d,d=d+(b<<y|b>>>32-y)|0}n=n+l|0,s=s+d|0,r=r+f|0,i=i+p|0}const a=new Uint8Array(16),c=new DataView(a.buffer);return c.setUint32(0,n>>>0,!0),c.setUint32(4,s>>>0,!0),c.setUint32(8,r>>>0,!0),c.setUint32(12,i>>>0,!0),a}const eb=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function dt(t,e){return t>>>e|t<<32-e}function tb(t){const e=Ul(t,!1),n=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Int32Array(64);for(let o=0;o<e.byteLength;o+=64){for(let m=0;m<16;m++)s[m]=e.getInt32(o+m*4,!1);for(let m=16;m<64;m++){const g=s[m-15],b=s[m-2],y=dt(g,7)^dt(g,18)^g>>>3,w=dt(b,17)^dt(b,19)^b>>>10;s[m]=s[m-16]+y+s[m-7]+w|0}let a=n[0],c=n[1],u=n[2],l=n[3],d=n[4],f=n[5],p=n[6],h=n[7];for(let m=0;m<64;m++){const g=dt(d,6)^dt(d,11)^dt(d,25),b=d&f^~d&p,y=h+g+b+eb[m]+s[m]|0,w=dt(a,2)^dt(a,13)^dt(a,22),v=a&c^a&u^c&u,E=w+v|0;h=p,p=f,f=d,d=l+y|0,l=u,u=c,c=a,a=y+E|0}n[0]=n[0]+a|0,n[1]=n[1]+c|0,n[2]=n[2]+u|0,n[3]=n[3]+l|0,n[4]=n[4]+d|0,n[5]=n[5]+f|0,n[6]=n[6]+p|0,n[7]=n[7]+h|0}const r=new Uint8Array(32),i=new DataView(r.buffer);for(let o=0;o<8;o++)i.setInt32(o*4,n[o],!1);return r}const tc=new WeakSet,Bl=new WeakMap;function nb(t){if(tc.has(t))return;tc.add(t);const e=al(t);for(const n of e.functions)Bl.set(n.fn,n)}function sb(t){return Bl.get(t)}function zl(t){return`/${t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}`}function ds(t,e,n,s){const r=[...n,...t.functions],i=t.path.segments,o={},a=[];let c=0,u,l;for(let m=0;m<i.length;m++){const g=i[m];if(g.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==g.value){u="literal-mismatch";break}c++}else if(g.type==="wildcard"){if(c>=e.length){u="request-shorter";break}o[g.name]=e[c],c===e.length-1&&a.push(g.name),c++}else{const b=i.length-m-1,y=e.length-c-b;if(y<0){u="request-shorter";break}o[g.name]=e.slice(c,c+y).join("/"),b===0&&(l={name:g.name,start:c},y>0&&a.push(g.name)),c+=y}}const d=m=>({...t.loc?{line:t.loc.line}:{},blockPath:zl(t),matchedSegments:c,totalSegments:i.length,bindings:o,matched:!1,...m});if(u!==void 0)return s?.push(d({reason:u})),[];if(l){const m=[{block:t,pathVariables:o,candidateVariables:a,functions:r},...rb(t,e,r,o,l,s)];return s?.push(d({matched:!0})),m}const f=e.slice(c),p=[],h=f.length>0?t.children:t.children.filter(m=>m.path.segments.every(g=>g.type==="recursive"));f.length===0&&p.push({block:t,pathVariables:o,candidateVariables:a,functions:r});for(const m of h)for(const g of ds(m,f,r,s))g.pathVariables={...o,...g.pathVariables},g.candidateVariables=[...a,...g.candidateVariables],p.push(g);return s?.push(d(p.length>0?{matched:!0}:{reason:"no-matching-child"})),p}function rb(t,e,n,s,r,i){if(t.children.length===0)return[];const o=[],a=new Set;let c;for(let u=e.length-1;u>=r.start;u--){const l=e.slice(u),d={...s,[r.name]:e.slice(r.start,u).join("/")},f=[];let p=!1;for(const h of t.children)for(const m of ds(h,l,n,{push:g=>f.push(g)}))a.has(m.block)||(a.add(m.block),p=!0,m.pathVariables={...d,...m.pathVariables},o.push(m));if(c??=f,p)for(const h of f)i?.push(h)}if(o.length===0)for(const u of c??[])i?.push(u);return o}function Ls(t,e,n,s){if(e.length!==1)throw at(e,n,s),new _(`Incorrect number of arguments. Received: ${e.length}. Expected: ${t}(path).`);const r=xe(e[0],n,s);if(!(r instanceof nt)||r.segments.some(i=>/^\{.*\}$/.test(i)))throw new _(`Function not found error: Name: [${t}].`);return String(r)}function nc(t,e){if(e.split("/").some(s=>s==="."||s===".."))throw new _(`${t}() path '${e}' has a '.' or '..' segment, which is not a valid document id`);const n=Mn(e);if(!Tr(n.split("/").filter(Boolean)))throw new _(`${t}() requires a path pointing to a document (even segment count), got '${n}'`);return n}function sc(t){return Mn(t.afterStatePath.toString())}function ib(t,e,n,s){const r=n.functions?.get(t);if(r)return ob(t,r,e,n,s);switch(t){case"get":{const i=Ls("get",e,n,s);return Rs(n,"doc",i),Qa(i,n)}case"exists":{const i=Ls("exists",e,n,s);return Rs(n,"doc",i),Ya(i,n)}case"getAfter":{const i=Ls("getAfter",e,n,s),o=nc("getAfter",i);if(Rs(n,"after",o),o===sc(n)){if(n.afterState===null)throw new _(`getAfter() of non-existent document '${i}' (guard with existsAfter() first)`);return Ni(o,n.afterState)}if(n.batchProjection?.has(o)){const a=n.batchProjection.get(o);if(a===null)throw new _(`getAfter() of non-existent document '${i}' (guard with existsAfter() first)`);return Ni(o,a)}return Qa(i,n)}case"existsAfter":{const i=Ls("existsAfter",e,n,s),o=nc("existsAfter",i);return Rs(n,"after",o),o===sc(n)?n.existsAfter:n.batchProjection?.has(o)?n.batchProjection.get(o)!==null:Ya(i,n)}case"string":case"int":case"float":{const i=$l(Dl(t),at(e,n,s));if(i instanceof Is)throw new _(i.message);return i}case"path":{if(e.length!==1)throw at(e,n,s),new _(`Incorrect number of arguments. Received: ${e.length}. Expected: path(string).`);const i=xe(e[0],n,s);if(typeof i=="string")return nt.fromString(i);throw new _(`path() requires a string argument, got ${typeof i}`)}}throw new _(`Unknown function: ${t}`)}function ob(t,e,n,s,r){if(n.length!==e.parameters.length)throw at(n,s,r),new _(`Incorrect number of arguments. Received: ${n.length}. Expected: ${t}(${e.parameters.join(", ")}).`);const i=Object.create(null);for(let c=0;c<e.parameters.length;c++)i[e.parameters[c]]=ac(n[c],s,r);const o=sb(e);let a=s;if(o){const c={};for(const u of o.captures)Object.hasOwn(s.pathVariables,u)&&(c[u]=s.pathVariables[u]);a={...s,functions:o.functions,pathVariables:c,database:o.captures.has("database")?s.database:""}}s.trace?.enterFrame(t);try{for(const c of e.lets){const u=s.trace?s.trace.entries.length:-1;i[c.name]=ac(c.value,a,i),s.expressionBudget?.letBinding(c),u>=0&&s.trace?.markEntryAsLetBinding(u,c.name)}return xe(e.body,a,i)}finally{s.trace?.exitFrame()}}function ab(t,e,n,s,r){if(t.type==="identifier"){const a=t.name;if(rc(a)&&!Object.hasOwn(r,a)&&!Object.hasOwn(s.pathVariables,a)){const c=at(n,s,r);return s.expressionBudget?.node(t),ub(a,e,c)}if(!rc(a)&&!Object.hasOwn(r,a)&&!Object.hasOwn(s.pathVariables,a)&&!yb(a))throw new Gt(`Unknown namespace or method '${a}.${e}()'`)}const[i,...o]=at([t,...n],s,r);if(i instanceof oe){let a;try{a=i.callMethod(e,o)}catch(c){throw c instanceof _?c:new _(c.message)}if(a===ge)throw e==="size"||e==="toSet"||Za.has(e)||Ci.has(e)||Ba.has(e)?new _(ts(e)):new Gt(`Unknown method '${e}' on ${i.typeName}`);return i instanceof ut&&typeof a=="number"?new re(a):a}if(e==="diff"&&Ge(i)){if(o.length!==1)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.diff(map).`);const a=o[0];if(Ge(a))return new Js(a,i);throw new _("diff() requires a map argument")}if(typeof i=="function")return i(...o);if(i instanceof fe){const a=Vg(i,e,o);if(a instanceof tn)throw new _(a.message);return a}if(i instanceof Js){switch(e){case"addedKeys":case"removedKeys":case"changedKeys":case"affectedKeys":case"unchangedKeys":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map_diff.${e}().`);return i[e]()}throw new _(ts(e))}if(Ge(i)){const a=i;switch(e){case"keys":case"values":{const c=Hg(e,a,o);if(c instanceof Tl)throw new _(c.message);return c}case"size":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.size().`);return Object.keys(a).length;case"get":{if(o.length!==2)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.get(string, any), map.get(list, any).`);const c=o[0],u=o[1];if(Array.isArray(c)){let l=a;for(const d of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof oe)return u;const f=String(d);if(!Object.hasOwn(l,f))return u;l=l[f]}return l}if(typeof c!="string")throw new _(`Unsupported operation error. Received: map.get(${J(c)}, ${J(u)}). Expected: map.get(string, any), map.get(list, any).`);return Object.hasOwn(a,c)?a[c]:u}}}if(Array.isArray(i))switch(e){case"size":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: list.size().`);return i.length;case"hasAll":case"hasAny":case"hasOnly":{const a=Ny(e,i,o);if(a instanceof Mt)throw new _(a.message);return a}case"concat":case"join":case"removeAll":{let a;if(e==="concat"?a=Ry(i,o):e==="join"?a=My(i,o):a=Ly(i,o),a instanceof Mt)throw new _(a.message);return a}case"toSet":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: list.toSet().`);return new fe(i)}if(typeof i=="string")switch(e){case"size":case"lower":case"upper":case"trim":case"toUtf8":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.${e}().`);return e==="size"?i.length:e==="lower"?i.toLowerCase():e==="upper"?i.toUpperCase():e==="trim"?i.trim():He.fromUtf8(i);case"split":case"matches":{if(o.length!==1)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.${e}(string).`);const a=o[0];if(typeof a!="string")throw new _(`Unsupported operation error. Received: string.${e}(${J(a)}). Expected: string.${e}(string).`);try{return e==="matches"?$g(a,i):i.split(xo("split",a,a,"g"))}catch(c){throw new _(c.message)}}case"replace":{if(o.length!==2)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.replace(string, string).`);const[a,c]=o;if(typeof a!="string"||typeof c!="string")throw new _(`Unsupported operation error. Received: string.replace(${J(a)}, ${J(c)}). Expected: string.replace(string, string).`);try{return jg(i,a,c)}catch(u){throw new _(u.message)}}}throw Za.has(e)||Ci.has(e)||Ba.has(e)?new _(ts(e)):new _(`Unknown method '${e}' on ${typeof i}`)}const cb=new Set(["math","timestamp","duration","latlng","hashing"]);function rc(t){return cb.has(t)}function ub(t,e,n){switch(t){case"math":return db(e,n);case"timestamp":return pb(e,n);case"duration":return mb(e,n);case"latlng":return lb(e,n);case"hashing":return Gy(e,n)}throw new Gt(`Unknown namespace '${t}'`)}function ic(t){return t instanceof re?t.value:t}function lb(t,e){switch(t){case"value":{if(e.length!==2)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: latlng.value(float, float).`);const n=ic(e[0]),s=ic(e[1]);if(typeof n!="number"||typeof s!="number"||!Number.isFinite(n)||!Number.isFinite(s))throw new _(`Unsupported operation error. Received: latlng.value(${J(e[0])}, ${J(e[1])}). Expected: latlng.value(float, float).`);if(n<-90||n>90||s<-180||s>180)throw new _(" Latitude must be in range [-90.0, +90.0] and longitude must be in range [-180.0, +180.0]");return new ut(n,s)}}throw new Gt(`Unknown latlng method '${t}'`)}function db(t,e){const n=Oy(t,e);if(n instanceof qs)throw new _(n.message);return n}const fb=-621355968e5,hb=0xe677d21fdbff;function pb(t,e){switch(t){case"date":{if(e.length!==3)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: timestamp.date(int, int, int).`);if(!e.every(i=>typeof i=="number"&&Number.isInteger(i)))throw new _(`Unsupported operation error. Received: timestamp.date(${e.map(J).join(", ")}). Expected: timestamp.date(int, int, int).`);const[n,s,r]=e;try{return ve.fromYMD(n,s,r)}catch(i){throw new _(i.message)}}case"value":{if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: timestamp.value(int).`);const n=e[0];if(typeof n!="number"||!Number.isInteger(n))throw new _(`Unsupported operation error. Received: timestamp.value(${J(n)}). Expected: timestamp.value(int).`);if(n<fb||n>hb)throw new _("Timestamp out of range");return ve.fromMillis(n)}}throw new Gt(`Unknown timestamp method '${t}'`)}function mb(t,e){switch(t){case"value":{if(e.length!==2)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.value(int, string).`);const[n,s]=e;if(typeof n!="number"||!Number.isInteger(n)||typeof s!="string")throw new _(`Unsupported operation error. Received: duration.value(${J(n)}, ${J(s)}). Expected: duration.value(int, string).`);try{return ke.fromValue(n,s)}catch(r){throw new _(r.message)}}case"time":{if(e.length!==4)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.time(int, int, int, int).`);if(!e.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new _(`Unsupported operation error. Received: duration.time(${e.map(J).join(", ")}). Expected: duration.time(int, int, int, int).`);const[n,s,r,i]=e;return ke.fromTime(n,s,r,i)}case"abs":{if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.abs(duration).`);const n=e[0];if(!(n instanceof ke))throw new _(`duration.abs() requires a Duration argument, got ${typeof n}`);return ke.abs(n)}}throw new Gt(`Unknown duration method '${t}'`)}function xe(t,e,n={}){return e.trace?e.trace.capture(t,()=>oc(t,e,n)):oc(t,e,n)}function oc(t,e,n){const s=e.expressionBudget;if(!s)return Xr(t,e,n);if(t.type==="functionCall")return s.call(t),Xr(t,e,n);let r;try{r=Xr(t,e,n)}catch(i){throw i instanceof cn||s.node(t),i}return s.node(t),r}function Xr(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new re(t.value):t.value instanceof Uint8Array?new He(t.value):t.value;case"identifier":return gb(t.name,e,n);case"binaryOp":return vb(t,e,n);case"unaryOp":{if(t.op==="!")return!fs(xe(t.operand,e,n),t.operand);if(t.op==="-"){const s=xe(t.operand,e,n);if(s instanceof re)return new re(-s.value);if(typeof s=="number")return-s;throw new _(`Unsupported operation error. Received: -${J(s)}. Expected: -int, -float, -duration.`,t)}throw new _(`Unknown unary op: ${t.op}`,t)}case"ternary":return e.expressionBudget?.ternary(t),fs(xe(t.condition,e,n),t.condition)?xe(t.consequent,e,n):(e.expressionBudget?.ternaryElse(t),xe(t.alternate,e,n));case"memberAccess":{const s=xe(t.object,e,n);if(s==null)throw new _(`Property '${t.property}' accessed on ${s===null?"null":"undefined"} value`,t);if(s instanceof oe&&s.typeName!=="path")return s.field(t.property);if(!Ge(s)){const r=ty(s,t.property);if(r instanceof Re)throw new _(r.message,t);return r}if(Object.hasOwn(s,t.property))return s[t.property];throw new _(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const[s,r]=at([t.index,t.object],e,n);if(r==null)throw new _(`Index access on ${r===null?"null":"undefined"} value`,t);const i=Ml(r,s);if(i instanceof Re)throw new _(i.message,t);return i}case"sliceAccess":{const[s,r,i]=at([t.object,t.start,t.end],e,n),o=ny(s,r,i);if(o instanceof Re)throw new _(o.message,t);return o}case"inExpr":{const[s,r]=at([t.collection,t.element],e,n),i=sy(r,s);if(i instanceof Fs)throw new _(i.message,t);return i}case"isExpr":{const s=xe(t.value,e,n);switch(t.typeName){case"string":return typeof s=="string";case"int":return s instanceof oe?!1:typeof s=="number";case"float":return s instanceof re;case"number":return s instanceof re?!0:s instanceof oe?!1:typeof s=="number";case"bool":return typeof s=="boolean";case"null":return s===null;case"list":return Array.isArray(s);case"set":return s instanceof fe;case"map":return s instanceof oe||s instanceof Js||s instanceof fe?!1:typeof s=="object"&&s!==null&&!Array.isArray(s);default:return s instanceof oe?s.typeName===t.typeName:!1}}case"listLiteral":return at(t.elements,e,n);case"mapLiteral":{const s=at(t.entries.flatMap(i=>[i.key,i.value]),e,n),r=[];for(let i=0;i<s.length;i+=2){const o=s[i];if(typeof o!="string")throw new _(`Type error. Received: [${J(o)}] Expected: [string].`,t);r.push([o,s[i+1]])}return Gg(r)}case"functionCall":return ib(t.name,t.args,e,n);case"methodCall":return ab(t.object,t.method,t.args,e,n);case"pathLiteral":{const s=[];let r;for(const i of t.segments)if(typeof i=="string")e.expressionBudget?.pathSegment(t),s.push(i);else try{const o=xe(i,e,n);if(typeof o!="string"&&(typeof o!="number"||!Number.isInteger(o)))throw new _(`Type error. Received: [${J(o)}] Expected: [string].`,i);s.push(String(o))}catch(o){r=Lo(r,o)}if(r)throw r;return new nt(s)}default:throw new _(`Unknown expression type: ${t.type}`,t)}}function gb(t,e,n){if(Object.hasOwn(n,t)){const s=n[t];if(s instanceof _)throw s;return s}if(Object.hasOwn(e.pathVariables,t))return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new _("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new _(`Undefined variable '${t}'`)}function yb(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function bb(t){return t instanceof _&&!(t instanceof cn)&&!(t instanceof Gt)}function Ro(t){if(bb(t))return t;throw t}function Lo(t,e){const n=Ro(e);return t??n}function at(t,e,n){const s=new Array(t.length);let r;for(let i=0;i<t.length;i++)try{s[i]=xe(t[i],e,n)}catch(o){r=Lo(r,o)}if(r)throw r;return s}function ac(t,e,n){try{return xe(t,e,n)}catch(s){return Ro(s)}}function cc(t,e,n,s,r,i){let o,a;try{o=fs(xe(n,r,i),n)}catch(l){a=l}if(a instanceof cn)throw a;if(a===void 0&&o===e)return r.trace?.skip(s),e;r.expressionBudget?.logicalRight(t);let c,u;try{c=fs(xe(s,r,i),s)}catch(l){u=l}if(u instanceof cn)throw u;if(u===void 0&&c===e)return e;if(a!==void 0)throw a;if(u!==void 0)throw u;return c}function vb(t,e,n){const{op:s,left:r,right:i}=t;if(s==="&&")return cc(t,!1,r,i,e,n);if(s==="||")return cc(t,!0,r,i,e,n);let o,a,c;try{o=xe(r,e,n)}catch(u){c=Ro(u)}try{a=xe(i,e,n)}catch(u){c=Lo(c,u)}if(c)throw c;if(s!=="=="&&s!=="!="){if(o instanceof oe){const u=o.binaryOp(s,a);if(u!==ge)return u}if(typeof o=="number"&&a instanceof re){const u=new re(o).binaryOp(s,a);if(u!==ge)return u}if(a instanceof oe&&(s==="+"||s==="*")){const u=a.binaryOp(s,o);if(u!==ge)return u}if(o instanceof oe||a instanceof oe)throw new _(`Operator '${s}' is not defined between ${J(o)} and ${J(a)}`)}if((s==="<"||s===">"||s==="<="||s===">=")&&!(typeof o=="number"&&typeof a=="number"||typeof o=="string"&&typeof a=="string"))throw new _(`Operator '${s}' is not defined between ${typeof o} and ${typeof a}`);switch(s){case"==":return o===a||qa(o,a);case"!=":return!(o===a||qa(o,a));case"<":return o<a;case">":return o>a;case"<=":return o<=a;case">=":return o>=a;case"+":{if(typeof o=="string"&&typeof a=="string"||typeof o=="number"&&typeof a=="number")return o+a;throw new _(`Operator '+' is not defined between ${J(o)} and ${J(a)}`)}case"-":case"*":case"/":case"%":{if(typeof o!="number"||typeof a!="number")throw new _(`Unsupported operation error. Received: ${J(o)} ${s} ${J(a)}.`);if(s==="-")return o-a;if(s==="*")return o*a;if(a===0)throw new _(Dg);return s==="/"?Math.trunc(o/a):o%a}default:throw new _(`Unknown binary op: ${s}`)}}function fs(t,e){if(typeof t=="boolean")return t;throw new _(`Type error. Received: [${J(t)}] Expected: [bool].`,e)}const wb=`Unable to evaluate the expression as the maximum of ${os} expressions to evaluate has been reached.`;function Sb(t,e){return e===void 0?t:`${ph(e)}: ${t}`}class Ab{exhausted;limit;evaluated=0;constructor(e,n=os){this.exhausted=e,this.limit=n}node(e){this.charge(e===void 0?void 0:Zu(e))}call(e){this.charge(e===void 0?void 0:bn(e))}logicalRight(e){this.charge(e===void 0?void 0:bn(e))}ternary(e){this.charge(e===void 0?void 0:bn(e))}ternaryElse(e){const n=e===void 0?void 0:bn(e);this.charge(n),this.charge(n)}pathSegment(e){this.charge(e===void 0?void 0:bn(e))}letBinding(e){this.charge(e===void 0?void 0:bn(e))}charge(e){if(this.evaluated>=this.limit)throw this.exhausted(wb,e);this.evaluated++}}const kb=new Set(["__proto__","prototype","constructor"]);function Qs(t){if(kb.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Wl(t,e){const n={...t};for(const[s,r]of Object.entries(e)){Qs(s);const i=Object.hasOwn(n,s)?n[s]:void 0;Ge(r)&&Ge(i)?n[s]=Wl(i,r):n[s]=r}return n}function Eb(t,e,n){let s=t;for(let i=0;i<e.length-1;i++){const o=e[i];Qs(o);const a=Object.hasOwn(s,o)?s[o]:void 0,c=Ge(a)?{...a}:{};s[o]=c,s=c}const r=e[e.length-1];Qs(r),s[r]=n}function Ib(t,e){const n={...t};for(const[s,r]of Object.entries(e))s.includes(".")?Eb(n,s.split("."),r):(Qs(s),n[s]=r);return n}function _b(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?Wl(e??{},n):n;case"update":return Ib(e??{},n);case"delete":return null}}const xb="Paths are document-relative, from the first segment after /databases/<database>/documents, such as orders/o2.",uc=3;function Cb(t){const e=t.split("/").filter(Boolean);return e.length>uc&&e[0]==="databases"&&e[2]==="documents"?e.slice(uc).join("/"):e.join("/")}const Di=t=>t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t),Ft=t=>({type:"literal",value:t,raw:JSON.stringify(t)});function Ys(t){return t.type==="memberAccess"?{object:t.object,property:t.property}:t.type==="bracketAccess"&&t.index.type==="literal"&&typeof t.index.value=="string"?{object:t.object,property:t.index.value}:null}function Ob(t){const e=Ys(t);return!e||e.property!=="data"?!1:e.object.type==="identifier"&&e.object.name==="resource"}function Bt(t){const e=Ys(t);return!e||e.property.length===0||e.property.includes(".")||!Ob(e.object)?null:e.property}function Vl(t){const e=Ys(t);if(!e||e.property!=="uid")return!1;const n=Ys(e.object);return!n||n.property!=="auth"?!1:n.object.type==="identifier"&&n.object.name==="request"}function No(t){const e=new Map;for(const n of t.where??[]){let s;if(n.op==="=="&&Di(n.value)?s=[n.value]:n.op==="in"&&Array.isArray(n.value)&&n.value.length>0&&n.value.length<=30&&n.value.every(Di)&&(s=Array.from(new Set(n.value))),s===void 0)continue;const r=e.get(n.field);r===void 0?e.set(n.field,[s]):r.push(s)}return e}function Mo(t){const e=new Map;for(const[n,s]of No(t)){let r=s[0];for(let i=1;i<s.length;i++){const o=s[i];r=r.filter(a=>o.includes(a))}e.set(n,r)}return e}function Tb(t,e,n=new Set){let s=500;const r=(i,o)=>{if(--s<0)return null;if(i.type==="functionCall"&&e.has(i.name)){if(o.has(i.name))return null;const a=e.get(i.name);if(a.parameters.length!==i.args.length)return null;const c=new Map;for(let l=0;l<a.parameters.length;l++){const d=r(i.args[l],o);if(!d)return null;c.set(a.parameters[l],d)}const u=new Set(o).add(i.name);for(const l of a.lets){const d=r(Kt(l.value,c),u);if(!d)return null;c.set(l.name,d)}return r(Kt(a.body,c),u)}switch(i.type){case"literal":case"identifier":return i;case"memberAccess":{const a=r(i.object,o);return a?{...i,object:a}:null}case"bracketAccess":{const a=r(i.object,o),c=r(i.index,o);return!a||!c?null:{...i,object:a,index:c}}case"binaryOp":{const a=r(i.left,o),c=r(i.right,o);return!a||!c?null:{...i,left:a,right:c}}default:return i}};return r(t,n)}function Ns(t,e,n){return{type:"binaryOp",op:n,left:t,right:e}}function wn(t){return{type:"unaryOp",op:"!",operand:t}}function Do(t,e){if(t.type==="literal"&&Di(t.value))return t.value;if(Vl(t))return e}function ei(t,e,n,s){const r=Do(e,s);return r===void 0?!1:(n.where??[]).some(i=>i.field===t&&i.op==="array-contains"&&i.value===r)}function Rb(t,e,n,s){const r=(i,o)=>{const a=Bt(i);if(a===null)return!1;const c=n.get(a);if(!c)return!1;const u=Do(o,s);return u===void 0?!1:c.some(l=>l.length===1&&l[0]===u)};return r(t,e)||r(e,t)}function Lb(t,e,n,s){const r=Bt(t);if(r===null||e.type!=="listLiteral")return!1;const i=n.get(r);if(!i)return!1;const o=[];for(const a of e.elements){const c=Do(a,s);if(c===void 0)return!1;o.push(c)}return i.some(a=>a.every(c=>o.includes(c)))}function Nb(t,e,n,s){let r=!1;const i=No(e),o=Mo(e),a=new Map;for(const[l,d]of o)d.length>0&&a.set(l,d);let c=[new Map];for(const[l,d]of a){if(c.length*d.length>30)return;c=c.flatMap(f=>d.map(p=>new Map([...f,[l,p]])))}const u=[];for(const l of c){let f=function(h,m=new Set){if(--d<0)throw new Error("proof expansion budget");const g=Bt(h);if(g!==null&&l.has(g))return Ft(l.get(g));if(h.type==="functionCall"&&n.has(h.name)){if(sn(h,n))return h;if(m.has(h.name))throw new Error("recursive proof helper");const y=n.get(h.name);if(y.parameters.length!==h.args.length)throw new Error("proof arity");const w=new Map(y.parameters.map((v,E)=>[v,h.args[E]]));for(const v of y.lets)w.set(v.name,Kt(v.value,w));return f(Kt(y.body,w),new Set([...m,h.name]))}if(h.type==="inExpr"){const y=f(h.element,m),w=f(h.collection,m),v=Bt(w);return v!==null&&ei(v,y,e,s)||Lb(y,w,i,s)?Ft(!0):{...h,element:y,collection:w}}const b=y=>f(y,m);switch(h.type){case"literal":case"identifier":return h;case"memberAccess":{const y={...h,object:b(h.object)},w=Bt(y);return w!==null&&l.has(w)?Ft(l.get(w)):y}case"bracketAccess":{const y={...h,object:b(h.object),index:b(h.index)},w=Bt(y);return w!==null&&l.has(w)?Ft(l.get(w)):y}case"sliceAccess":return{...h,object:b(h.object),start:b(h.start),end:b(h.end)};case"binaryOp":{const y=b(h.left),w=b(h.right);return h.op==="=="&&Rb(y,w,i,s)?Ft(!0):{...h,left:y,right:w}}case"unaryOp":return{...h,operand:b(h.operand)};case"ternary":return{...h,condition:b(h.condition),consequent:b(h.consequent),alternate:b(h.alternate)};case"isExpr":return{...h,value:b(h.value)};case"methodCall":{const y=b(h.object),w=h.args.map(b),v=Bt(y);if(v!==null&&w.length===1&&w[0].type==="listLiteral"&&w[0].elements.every(E=>sn(E,n))){const E=w[0].elements;if(h.method==="hasAny"&&E.some(I=>ei(v,I,e,s))||h.method==="hasAll"&&E.length>0&&E.every(I=>ei(v,I,e,s)))return Ft(!0)}return{...h,object:y,args:w}}case"functionCall":return{...h,args:h.args.map(b)};case"listLiteral":return{...h,elements:h.elements.map(b)};case"mapLiteral":return{...h,entries:h.entries.map(y=>({key:b(y.key),value:b(y.value)}))};case"pathLiteral":return{...h,segments:h.segments.map(y=>typeof y=="string"?y:b(y))}}},p=function(h){if(sn(h,n))return h;if(h.type==="unaryOp"&&h.op==="!"){const b=h.operand;if(b.type==="binaryOp"&&b.op==="&&")return p(Ns(wn(b.left),wn(b.right),"||"));if(b.type==="binaryOp"&&b.op==="||")return p(Ns(wn(b.left),wn(b.right),"&&"));if(b.type==="unaryOp"&&b.op==="!"){const y=p(b.operand);return y?wn(wn(y)):void 0}return}if(h.type!=="binaryOp"||h.op!=="&&"&&h.op!=="||")return;const m=p(h.left),g=p(h.right);if(m&&g)return Ns(m,g,h.op);if(h.op==="||")return r=!0,m??g},d=2e3;try{const h=p(f(t));if(!h)return;u.push(h)}catch{return}}return{condition:u.reduce((l,d)=>Ns(l,d,"&&")),partial:r}}function Mb(t,e,n=new Map,s){const r=Db(t,e,n,s);if(r.provable||r.kind==="constraints-not-satisfied")return r;const i=Nb(t,e,n,s);return i?{provable:!0,reason:"query-guaranteed facts reduce every candidate alternative to a document-independent residual",residualCondition:i.condition,proofFailure:i.partial?r:void 0}:r}function Db(t,e,n=new Map,s){if(sn(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const r=Pb(t,n,s);if(!r.ok||r.required.length===0){const f="list rule depends on per-document data through a predicate the query cannot discharge (unconstrained candidate fields or unsupported query facts remain after helper expansion)";return{provable:!1,kind:"unsupported-predicate",reason:`${f} — Pyric cannot establish whether Firebase would allow this query`,residual:{missing:[],mismatched:[],outOfScope:f,...r.ok?{}:{predicate:Ae(r.predicate),predicateLoc:r.predicateLoc}}}}const i=r.required,o=e.where??[],a=No(e),c=Mo(e),u=[],l=[];let d=!1;for(const f of i){const p=c.get(f.field),h=a.get(f.field),m=p!==void 0&&p.length===1&&ti(p[0],f.value),g=h!==void 0&&h.some(w=>w.length===1&&ti(w[0],f.value));if(m||g){(p?.length??0)===0&&(d=!0);continue}const y=o.find(w=>w.field===f.field&&w.op==="=="&&!ti(w.value,f.value));y?l.push({field:f.field,expectedValue:f.value,actualValue:y.value}):u.push({field:f.field,expectedValue:f.value,fromAuthUid:f.fromAuthUid})}if(u.length===0&&l.length===0){const f={provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"};return d&&(f.residualCondition=r.residual),f}return{provable:!1,kind:"constraints-not-satisfied",reason:$b(u,l),residual:{missing:u,mismatched:l}}}function $b(t,e){const n=[];if(t.length>0){const s=t.map(r=>`resource.data.${r.field} == ${r.fromAuthUid?"request.auth.uid":JSON.stringify(r.expectedValue)}`).join(", ");n.push(`the query has no matching where(...) equality for [${s}]`)}if(e.length>0){const s=e.map(r=>`resource.data.${r.field} == ${JSON.stringify(r.expectedValue)} but the query pins ${JSON.stringify(r.actualValue)}`).join(", ");n.push(`the query where(...) value does not match [${s}]`)}return`${n.join("; ")} — Pyric cannot prove the query safe ("rules are not filters")`}function sn(t,e=new Map,n=new Set){const s=r=>{switch(r.type){case"literal":return!0;case"identifier":return r.name!=="resource";case"memberAccess":return s(r.object);case"bracketAccess":return s(r.object)&&s(r.index);case"sliceAccess":return s(r.object)&&s(r.start)&&s(r.end);case"binaryOp":return s(r.left)&&s(r.right);case"unaryOp":return s(r.operand);case"ternary":return s(r.condition)&&s(r.consequent)&&s(r.alternate);case"inExpr":return s(r.element)&&s(r.collection);case"isExpr":return s(r.value);case"listLiteral":return r.elements.every(s);case"mapLiteral":return r.entries.every(i=>s(i.key)&&s(i.value));case"pathLiteral":return r.segments.every(i=>typeof i=="string"||s(i));case"methodCall":return s(r.object)&&r.args.every(s);case"functionCall":{if(!r.args.every(s))return!1;const i=e.get(r.name);if(!i)return!0;if(n.has(r.name))return!1;const o=new Set(n).add(r.name),a=new Map;i.parameters.forEach((c,u)=>{const l=r.args[u];l&&a.set(c,l)});for(const c of i.lets){const u=Kt(c.value,a);if(!sn(u,e,o))return!1;a.set(c.name,u)}return sn(Kt(i.body,a),e,o)}default:return!1}};return s(t)}function Pb(t,e,n){const s=[];let r=t,i=t.loc;const o=(c,u,l=t.loc)=>{if(c.type==="binaryOp"&&c.op==="&&"){const p=o(c.left,u,l);if(!p)return null;const h=o(c.right,u,l);return h?{type:"binaryOp",op:"&&",left:p,right:h}:null}if(c.type==="functionCall"&&e.has(c.name)&&!u.has(c.name)){const p=e.get(c.name),h=new Map;p.parameters.forEach((b,y)=>{const w=c.args[y];w&&h.set(b,w)});for(const b of p.lets)h.set(b.name,Kt(b.value,h));const m=Kt(p.body,h),g=new Set(u).add(c.name);return o(m,g,p.loc??l)}const d=jb(c,e,n,u);return d?(s.push(d),{type:"literal",value:!0,raw:"true"}):sn(c,e)?c:(r=c,i=c.loc??l,null)},a=o(t,new Set);return a?{ok:!0,required:s,residual:a}:{ok:!1,predicate:r,predicateLoc:i}}function jb(t,e,n,s){const r=Tb(t,e,s);if(!r||r.type!=="binaryOp"||r.op!=="==")return null;const i=(o,a)=>{const c=Bt(o);return c===null?null:a.type==="literal"?{field:c,value:a.value,fromAuthUid:!1}:n!==void 0&&Vl(a)?{field:c,value:n,fromAuthUid:!0}:null};return i(r.left,r.right)??i(r.right,r.left)}function Kt(t,e){const n=s=>{switch(s.type){case"identifier":return e.get(s.name)??s;case"literal":return s;case"memberAccess":return{...s,object:n(s.object)};case"methodCall":return{...s,object:n(s.object),args:s.args.map(n)};case"bracketAccess":return{...s,object:n(s.object),index:n(s.index)};case"sliceAccess":return{...s,object:n(s.object),start:n(s.start),end:n(s.end)};case"binaryOp":return{...s,left:n(s.left),right:n(s.right)};case"unaryOp":return{...s,operand:n(s.operand)};case"ternary":return{...s,condition:n(s.condition),consequent:n(s.consequent),alternate:n(s.alternate)};case"inExpr":return{...s,element:n(s.element),collection:n(s.collection)};case"isExpr":return{...s,value:n(s.value)};case"listLiteral":return{...s,elements:s.elements.map(n)};case"mapLiteral":return{...s,entries:s.entries.map(r=>({key:n(r.key),value:n(r.value)}))};case"pathLiteral":return{...s,segments:s.segments.map(r=>typeof r=="string"?r:n(r))};case"functionCall":return{...s,args:s.args.map(n)}}};return n(t)}function ti(t,e){return t===e}function Gl(t){const e=new Map,n=new Set;for(const s of t)e.has(s.name)&&n.add(s.name),e.set(s.name,s);return{functions:e,ambiguousNames:n}}function Hl(t,e,n,s=Fb){const r=new Set;return{pathInvariant:!Us(t,e,n,s,new Set,r),requiredFunctions:r}}function Us(t,e,n,s,r,i){const o=a=>Us(a,e,n,s,r,i);switch(t.type){case"literal":return!1;case"identifier":return e.has(t.name)||t.name==="request";case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!dc.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&dc.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(a=>o(a.key)||o(a.value));case"pathLiteral":return t.segments.some(a=>typeof a!="string"&&o(a));case"functionCall":{for(const l of t.args)if(!ni(l)&&o(l))return!0;if(s.has(t.name))return!0;const a=n.get(t.name);if(!a)return t.args.some(ni);if(t.args.length!==a.parameters.length||(i.add(a.name),r.has(a.name)))return!0;const c=new Set(r).add(a.name),u=new Map;for(let l=0;l<a.parameters.length;l++)u.set(a.parameters[l],t.args[l]);for(const l of a.lets){const d=lc(l.value,u);if(!ni(d)&&Us(d,e,n,s,c,i))return!0;u.set(l.name,d)}return Us(lc(a.body,u),e,n,s,c,i)}}}function ni(t){return t.type==="identifier"&&t.name==="request"}function lc(t,e){const n=s=>{switch(s.type){case"identifier":return e.get(s.name)??s;case"literal":return s;case"memberAccess":return{...s,object:n(s.object)};case"methodCall":return{...s,object:n(s.object),args:s.args.map(n)};case"bracketAccess":return{...s,object:n(s.object),index:n(s.index)};case"sliceAccess":return{...s,object:n(s.object),start:n(s.start),end:n(s.end)};case"binaryOp":return{...s,left:n(s.left),right:n(s.right)};case"unaryOp":return{...s,operand:n(s.operand)};case"ternary":return{...s,condition:n(s.condition),consequent:n(s.consequent),alternate:n(s.alternate)};case"inExpr":return{...s,element:n(s.element),collection:n(s.collection)};case"isExpr":return{...s,value:n(s.value)};case"listLiteral":return{...s,elements:s.elements.map(n)};case"mapLiteral":return{...s,entries:s.entries.map(r=>({key:n(r.key),value:n(r.value)}))};case"pathLiteral":return{...s,segments:s.segments.map(r=>typeof r=="string"?r:n(r))};case"functionCall":return{...s,args:s.args.map(n)}}};return n(t)}const dc=new Set(["auth","method","query","time"]),Fb=new Set;function Kl(t,e,n,s,r){if(t!==null===!1)return{kind:"no-rule"};const o=e.split("/").filter(m=>m.length>0),a=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const m of t.service.match.children)c.push(...ds(m,o,a));if(c.length===0)return{kind:"no-rule"};const l=[],d=new Map;let f=0;for(const m of c){const g=Gl(m.functions),b=g.functions;for(const y of m.block.allows){if(y.operations.some(V=>V==="list"?!0:V==="read")===!1)continue;if(f++,Hl(y.condition,new Set(m.candidateVariables),b,g.ambiguousNames).pathInvariant===!0===!1){l.push({kind:"unsupported-path",reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:fc(y,r)});continue}const I=Mb(y.condition,s,b,n?.uid);I.provable===!0&&d.set(y,I.residualCondition?{...y,condition:I.residualCondition}:y);const W=I.provable?I.proofFailure:I;W&&l.push({kind:W.kind,reason:W.reason,residual:W.residual,rule:fc(y,r),...W.residual.predicate?{predicate:Zl(W.residual.predicate,W.residual.predicateLoc??y.loc,r)}:{}})}}if(f===0)return{kind:"no-rule"};if(d.size===0){const m=l[0];return{kind:"unprovable",failures:l,reason:m.reason,residual:m.residual,...m.rule?{rule:{...m.rule,verdict:"deny"}}:{}}}return{kind:"provable",failures:l,evaluationAst:qb(t,d),syntheticResource:Ub(s)}}function fc(t,e=""){return Zl(Ae(t.condition),t.loc,e)}function Zl(t,e,n=""){if(!e)return{expression:t};const{line:s,col:r,file:i}=e,o=Sm(n,s,r,i,t);return o?{...o,column:o.col,expression:o.expression??t}:{line:s,col:r,column:r,file:i??"firestore.rules",citation:`${i??"firestore.rules"}:${s}:${r}`,expression:t}}function qb(t,e){const n=s=>({...s,allows:s.allows.filter(r=>e.has(r)).map(r=>e.get(r)),children:s.children.map(n)});return{...t,service:{...t.service,match:n(t.service.match)}}}function Ub(t){const e={};for(const[n,s]of Mo(t))s.length===1&&(e[n]=s[0]);return e}function Bb(t){return t?{...t.where!==void 0?{where:t.where}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.offset!==void 0?{offset:t.offset}:{},...t.orderBy!==void 0?{orderBy:t.orderBy}:{}}:{}}function Jl(t){const e=t.where!==void 0&&t.where.length>0;if(!(!e&&t.limit==null&&t.offset==null&&t.orderBy==null))return{...e?{where:t.where.map(n=>({field:n.field,op:n.op,value:Array.isArray(n.value)?[...n.value]:n.value}))}:{},...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}function $i(t){const e=[];for(const s of t.missing)s.fromAuthUid?e.push(` .where('${s.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(s.expectedValue)}`):e.push(` .where('${s.field}', '==', ${JSON.stringify(s.expectedValue)})`);for(const s of t.mismatched)e.push(` .where('${s.field}', '==', ${JSON.stringify(s.expectedValue)}) // the query pins ${JSON.stringify(s.actualValue)}, but the rule requires ${JSON.stringify(s.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
|
|
1706
|
+
`&&m!=="\r"}}if(d==="\\"){const h=e;e++;const m=t[e];if(m==="b")return e++,{kind:"assert",check:(y,w)=>Ts(y,w-1)!==Ts(y,w)};if(m==="B")return e++,{kind:"assert",check:(y,w)=>Ts(y,w-1)===Ts(y,w)};if(m==="A")return e++,{kind:"assert",check:(y,w)=>w===0};if(m==="z")return e++,{kind:"assert",check:(y,w)=>w===y.length};if((m==="x"||m==="u")&&t[e+1]==="{"){const y=t.indexOf("}",e+2),w=t.slice(e+2,y);return e=y+1,u(String.fromCodePoint(parseInt(w,16)),n)}if((m==="p"||m==="P")&&t[e+1]==="{"){e=t.indexOf("}",e+2)+1;const w=t.slice(h,e);return{kind:"char",test:Xt(w,n)}}if(m==="d"||m==="D"||m==="w"||m==="W"||m==="s"||m==="S"||m==="t"||m==="n"||m==="r"||m==="v"||m==="f"){e++;const y=t.slice(h,e);return{kind:"char",test:Xt(y,n)}}if(m==="x")return e+=3,{kind:"char",test:Xt(t.slice(h,e),n)};if(m==="u")return e+=5,{kind:"char",test:Xt(t.slice(h,e),n)};if(m==="c")return e+=2,{kind:"char",test:Xt(t.slice(h,e),n)};if(m>="0"&&m<="7"){const y=/^[0-7]{1,3}/.exec(t.slice(e));return e+=y[0].length,{kind:"char",test:Xt(t.slice(h,e),n)}}const g=t.codePointAt(e),b=String.fromCodePoint(g);return e+=b.length,u(b,n)}const f=t.codePointAt(e),p=String.fromCodePoint(f);return e+=p.length,u(p,n)};return o()}function Vg(t,e,n){const s=xo("replace",e,e,"g"),r=new RegExp(`${s.source}|`).exec(""),i=r===null?0:r.length-1;return t.replace(s,(...o)=>{const a=o.slice(0,i+1),c=o[o.length-1];let u={};return typeof c=="object"&&c!==null&&(u=c),Gg(n,a,u)})}function Gg(t,e,n){const s=e.length-1;let r="",i=0;for(;i<t.length;){const o=t[i];if(o==="\\"){if(i+1>=t.length)throw new Error("replace() replacement ends with an escape character");r+=t[i+1],i+=2;continue}if(o!=="$"){r+=o,i+=1;continue}const a=t[i+1];if(a==="{"){const l=t.indexOf("}",i+2);if(l===-1)throw new Error(`replace() replacement has an unclosed group name: ${t.slice(i)}`);const d=t.slice(i+2,l);if(!Object.hasOwn(n,d))throw new Error(`replace() replacement names no group: ${t.slice(i,l+1)}`);r+=n[d]??"",i=l+1;continue}if(a===void 0||a<"0"||a>"9")throw new Error(`replace() replacement has an illegal group reference: ${t.slice(i)}`);let c=Number(a),u=i+2;for(;u<t.length&&t[u]>="0"&&t[u]<="9";){const l=c*10+Number(t[u]);if(l>s)break;c=l,u+=1}if(c>s)throw new Error(`replace() replacement names group ${c}, but the pattern has ${s}`);r+=e[c]??"",i=u}return r}function Hg(t){const e=t.toExponential();if(e.includes("."))return e;const n=t.toExponential(1);return Number(n)===t?n:e}function Kg(t){if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if(t===0)return Object.is(t,-0)?"-0.0":"0.0";const e=Math.abs(t);if(e>=.001&&e<1e7){const i=String(t);return i.includes(".")?i:`${i}.0`}const[n,s]=Hg(t).split("e");return`${n.includes(".")?n:`${n}.0`}E${Number(s)}`}class re extends oe{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Kg(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof re?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,n){const s=n instanceof re?n.value:typeof n=="number"?n:void 0;if(s===void 0)return ge;const r=this.value;switch(e){case"+":return new re(r+s);case"-":return new re(r-s);case"*":return new re(r*s);case"/":return new re(r/s);case"%":return new re(r%s);case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:return ge}}}function qa(t,e){return xr(t,e,(n,s)=>n.value===s.value,Oo)}function Co(t,e){return xr(t,e,(n,s)=>n.float===s.float&&n.value===s.value,Oo)}function et(t,e){return xr(t,e,(n,s)=>n.value===s.value||Number.isNaN(n.value)&&Number.isNaN(s.value),et)}function Oo(t,e){return xr(t,e,(n,s)=>n.float===s.float&&n.value===s.value&&Object.is(n.value,s.value),Oo)}function Ua(t){if(t instanceof re)return{value:t.value,float:!0};if(typeof t=="number")return{value:t,float:!Number.isInteger(t)}}function xr(t,e,n,s){const r=Ua(t),i=Ua(e);if(r||i)return r!==void 0&&i!==void 0&&n(r,i);if(t instanceof oe)return t.equals(e);if(e instanceof oe)return e.equals(t);if(t instanceof fe||e instanceof fe)return t instanceof fe&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,a)=>s(o,e[a]));if(Ge(t)||Ge(e)){if(!Ge(t)||!Ge(e))return!1;const o=Object.keys(t);return o.length!==Object.keys(e).length?!1:o.every(a=>Object.hasOwn(e,a)&&s(t[a],e[a]))}return t===e}class fe{items;constructor(e){this.items=[];for(const n of e)this.items.some(s=>et(s,n))||this.items.push(n)}hasOnly(e){const n=e instanceof fe?e.toArray():e;return this.items.every(s=>n.some(r=>et(s,r)))}equals(e){return!(e instanceof fe)||e.items.length!==this.items.length?!1:this.items.every(n=>e.items.some(s=>et(n,s)))}hasAll(e){const n=e instanceof fe?e.toArray():e;for(const s of n)if(!this.items.some(r=>et(r,s)))return!1;return!0}hasAny(e){const n=e instanceof fe?e.toArray():e;for(const s of n)if(this.items.some(r=>et(r,s)))return!0;return!1}has(e){return this.items.some(n=>et(n,e))}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const n=e.toArray(),s=[];for(const r of this.items)n.some(i=>et(r,i))||s.push(r);return new fe(s)}union(e){const n=e.toArray();return new fe([...this.items,...n])}intersection(e){const n=e.toArray(),s=[];for(const r of this.items)n.some(i=>et(r,i))&&s.push(r);return new fe(s)}}class tn{message;constructor(e){this.message=e}}const Zg=["hasAll","hasAny","hasOnly"],Jg=["difference","intersection","union"],Ci=new Set(Jg);function Qg(t){return Zg.includes(t)}function Yg(t,e,n){if(e==="size")return n.length!==0?new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: set.size().`):t.size();if(Qg(e)){const s=`set.${e}(set), set.${e}(list)`;if(n.length!==1)return new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: ${s}.`);const[r]=n;return!Array.isArray(r)&&!(r instanceof fe)?new tn(`Unsupported operation error. Received: set.${e}(${J(r)}). Expected: ${s}.`):t[e](r)}if(Ci.has(e)){const s=e;if(n.length!==1)return new tn(`Incorrect number of arguments. Received: ${n.length}. Expected: set.${s}(set).`);const[r]=n;return r instanceof fe?t[s](r):new tn(`Unsupported operation error. Received: set.${s}(${J(r)}). Expected: set.${s}(set).`)}return new tn(ts(e))}class Js{before;after;constructor(e,n){this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))Object.hasOwn(this.before,n)||e.push(n);return new fe(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))Object.hasOwn(this.after,n)||e.push(n);return new fe(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))Object.hasOwn(this.before,n)&&!et(this.before[n],this.after[n])&&e.push(n);return new fe(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const s of n)(!Object.hasOwn(this.before,s)||!Object.hasOwn(this.after,s)||!et(this.before[s],this.after[s]))&&e.push(s);return new fe(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))Object.hasOwn(this.after,n)&&et(this.before[n],this.after[n])&&e.push(n);return new fe(e)}}class Ml{message;constructor(e){this.message=e}}const Ba=new Set(["diff","get","keys","values"]),Dl=new WeakMap;function Xg(t){const e={},n=[];for(const[s,r]of t)Object.hasOwn(e,s)||n.push(s),Object.defineProperty(e,s,{value:r,enumerable:!0,writable:!0,configurable:!0});return Dl.set(e,n),e}function ey(t,e,n){return n.length!==0?new Ml(`Incorrect number of arguments. Received: ${n.length}. Expected: map.${t}().`):t==="keys"?ty(e):ny(e)}function ty(t){return Object.keys(t).sort(sy)}function ny(t){return(Dl.get(t)??Object.keys(t)).map(n=>t[n])}function sy(t,e){const n=Math.min(t.length,e.length);for(let s=0;s<n;s+=1)if(t.charCodeAt(s)!==e.charCodeAt(s))return t.codePointAt(s)-e.codePointAt(s);return t.length-e.length}function ry(t,e,n){for(const s of[t,e-1])if(s<0||s>=n)return Cr(s,n);return t>e?`Illegal range error. From index: [${t}] , To index: [${e}].`:null}class Re{message;constructor(e){this.message=e}}function Oi(t){return`Property ${t} is undefined on object.`}function Cr(t,e){return`Index out of bound error. Index: [${t}] , size: [${e}].`}function iy(t,e){return typeof e!="number"||!Number.isInteger(e)?new Re(`Unsupported operation error. Received: list[${J(e)}]. Expected: list[int].`):e<0||e>=t.length?new Re(Cr(e,t.length)):t[e]}function $l(t,e){if(!Object.hasOwn(t,e))return new Re(Oi(e));const n=t[e];return n===void 0?new Re(Oi(e)):n}function oy(t,e){return typeof e!="number"||!Number.isInteger(e)?new Re(`Unsupported operation error. Received: string[${J(e)}]. Expected: string[int].`):e<0||e>=t.length?new Re(Cr(e,t.length)):t[e]}function Pl(t){return t instanceof oe&&t.typeName==="path"}const ay="Function not found error: Name: [[]].";function jl(t,e){if(Array.isArray(t))return iy(t,e);if(typeof t=="string")return oy(t,e);if(Pl(t)){if(typeof e=="number"&&Number.isInteger(e))return e>=0&&e<t.segments.length?t.segments[e]:new Re(Cr(e,t.segments.length));const n=String(e);return Object.hasOwn(t.bindings,n)?t.bindings[n]:new Re(Oi(n))}return t instanceof oe?new Re(ay):$l(t,String(e))}function cy(t,e){return Ge(t)?$l(t,e):Pl(t)?jl(t,e):new Re(`Type error. Received: [${J(t)}] Expected: [map,path].`)}function uy(t,e,n){if(typeof e!="number"||!Number.isInteger(e))return new Re(`Slice start must be an integer, got ${J(e)}`);if(typeof n!="number"||!Number.isInteger(n))return new Re(`Slice end must be an integer, got ${J(n)}`);if(typeof t=="string"||Array.isArray(t)){const s=ry(e,n,t.length);return s?new Re(s):t.slice(e,n)}return new Re(`Slice not supported on ${J(t)}`)}class Fs{message;constructor(e){this.message=e}}function ly(t,e){return e==null?new Fs("Null value error."):Array.isArray(e)?e.some(n=>Co(n,t)):e instanceof fe?e.has(t):Ge(e)?typeof t!="string"?new Fs(`Unsupported operation error. Received: map.in(${J(t)}). Expected: map.in(string).`):Object.hasOwn(e,t):new Fs("Function not found error: Name: [in].")}const za="0123456789ABCDEF";function dy(t){let e="";for(let n=0;n<t.length;n++){const s=t[n];e+=za[s>>>4]+za[s&15]}return e}function fy(t){let e="";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function hy(t,e){const n=Math.min(t.length,e.length);for(let s=0;s<n;s++)if(t[s]!==e[s])return t[s]<e[s]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let He=class Qn extends oe{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Qn(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const n=new Uint8Array(e.length/2);for(let s=0;s<n.length;s++)n[s]=parseInt(e.substr(s*2,2),16);return new Qn(n)}size(){return this.data.length}toBase64(){return fy(this.data)}toHexString(){return dy(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Qn)||this.data.length!==e.data.length)return!1;for(let n=0;n<this.data.length;n++)if(this.data[n]!==e.data[n])return!1;return!0}callMethod(e,n){switch(e){case"size":case"toBase64":case"toHexString":if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: bytes.${e}().`);return e==="size"?this.size():e==="toBase64"?this.toBase64():this.toHexString()}return ge}binaryOp(e,n){if(!(n instanceof Qn))return ge;const s=hy(this.data,n.data);switch(e){case"<":return s<0;case"<=":return s<=0;case">":return s>0;case">=":return s>=0}return ge}};const py=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class nt extends oe{typeName="path";segments;bindings;constructor(e,n={}){super(),this.segments=e,this.bindings=n}static fromString(e){const n=e.startsWith("/")?e.slice(1):e;return n.length===0?new nt([]):new nt(n.split("/"))}bind(e){const n=[],s={...this.bindings};for(const r of this.segments){const i=r.match(py);if(!i){n.push(r);continue}const o=i[1];if(Object.hasOwn(e,o)){const a=e[o];if(a==null)throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const c=String(a);n.push(c),s[o]=c}else n.push(r)}return new nt(n,s)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof nt)||this.segments.length!==e.segments.length)return!1;for(let n=0;n<this.segments.length;n++)if(this.segments[n]!==e.segments[n])return!1;return!0}callMethod(e,n){switch(e){case"bind":{if(n.length!==1)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: path.bind(map).`);const s=n[0];if(s==null||typeof s!="object"||Array.isArray(s)||s instanceof oe)throw new TypeError(`Path.bind() requires a Map argument, got ${s===null?"null":typeof s}`);return this.bind(s)}default:return ge}}}class Gt extends _{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class my{entries=[];parents=[];frames=[];capture(e,n){const s=this.entries.length,r=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:Ae(e),kind:e.type,parent:r};e.type==="binaryOp"&&(i.operator=e.op),this.stampFrame(i),this.entries.push(i),this.parents.push(s);try{const o=n();return this.entries[s].value=o,o}catch(o){throw this.entries[s].error=o instanceof Error?o.message:String(o),o}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,s={source:Ae(e),kind:e.type,parent:n,skipped:!0};e.type==="binaryOp"&&(s.operator=e.op),this.stampFrame(s),this.entries.push(s)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,n){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:n})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function gy(t,e,n,s){const i=f=>f*Math.PI/180,o=i(t),a=i(n),c=i(n-t),u=i(s-e),l=Math.sin(c/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)))}class ut extends oe{typeName="latlng";lat;lng;constructor(e,n){super(),this.lat=e,this.lng=n}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof ut&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,n){switch(e){case"latitude":case"longitude":if(n.length!==0)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: latlng.${e}().`);return e==="latitude"?this.lat:this.lng;case"distance":{if(n.length!==1)throw new TypeError(`Incorrect number of arguments. Received: ${n.length}. Expected: latlng.distance(latlng).`);const s=n[0];if(!(s instanceof ut))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof s}`);return gy(this.lat,this.lng,s.lat,s.lng)}default:return ge}}}const En=1e9,Wa={w:10080*60,d:1440*60,h:3600,m:60,s:1};function yy(t,e){let n=t+Math.trunc(e/En),s=e%En;return n>0&&s<0?(n-=1,s+=En):n<0&&s>0&&(n+=1,s-=En),{seconds:n,nanos:s}}class ke extends oe{typeName="duration";seconds;nanos;constructor(e,n){super();const s=yy(e,n);this.seconds=s.seconds,this.nanos=s.nanos}static fromValue(e,n){if(n in Wa)return new ke(e*Wa[n],0);if(n==="ms"){const s=Math.trunc(e/1e3),r=e-s*1e3;return new ke(s,r*1e6)}if(n==="ns"){const s=Math.trunc(e/En),r=e-s*En;return new ke(s,r)}throw new Error(`Unknown duration unit '${n}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,n,s,r){return new ke(e*3600+n*60+s,r)}static abs(e){return new ke(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,n=Math.abs(this.seconds),s=Math.abs(this.nanos);return`${e?"-":""}${n}.${s.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ke&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){switch(e){case"seconds":case"nanos":if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: duration.${e}().`);return e==="seconds"?this.seconds:this.nanos;default:return ge}}binaryOp(e,n){if(!(n instanceof ke))return ge;switch(e){case"+":return new ke(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new ke(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return ge}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const Va=1e9,by=864e5,Qr=86400,Yr=60;function vy(t,e){const n=Math.floor(e/Va);return{seconds:t+n,nanos:e-n*Va}}let ve=class It extends oe{typeName="timestamp";seconds;nanos;constructor(e,n){super();const s=vy(e,n);this.seconds=s.seconds,this.nanos=s.nanos}static fromMillis(e){const n=Math.floor(e/1e3),s=e-n*1e3;return new It(n,s*1e6)}static fromYMD(e,n,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(s)||e<1||e>9999||n<1||n>12||s<1||s>31)throw new RangeError(`Date is not valid. year: ${e}, month: ${n} day: ${s}.`);const r=new Date(0);if(r.setUTCFullYear(e,n-1,s),r.setUTCHours(0,0,0,0),r.getUTCFullYear()!==e||r.getUTCMonth()!==n-1||r.getUTCDate()!==s)throw new RangeError(`Date is not valid. year: ${e}, month: ${n} day: ${s}.`);return It.fromMillis(r.getTime())}static fromIsoString(e){return It.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),n=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${n}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof It&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){const s=()=>{if(n.length!==0)throw new RangeError(`Incorrect number of arguments. Received: ${n.length}. Expected: timestamp.${e}().`)};switch(e){case"seconds":return s(),(this.seconds%Yr+Yr)%Yr;case"nanos":return s(),this.nanos;case"toMillis":return s(),this.toMillis();case"year":return s(),this.asDate().getUTCFullYear();case"month":return s(),this.asDate().getUTCMonth()+1;case"day":return s(),this.asDate().getUTCDate();case"hours":return s(),this.asDate().getUTCHours();case"minutes":return s(),this.asDate().getUTCMinutes();case"dayOfWeek":{s();const r=this.asDate().getUTCDay();return r===0?7:r}case"dayOfYear":{s();const r=this.asDate(),i=Date.UTC(r.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-i)/by)+1}case"date":return s(),It.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{s();const r=(this.seconds%Qr+Qr)%Qr,i=Math.floor(r/3600),o=Math.floor(r%3600/60),a=r%60;return ke.fromTime(i,o,a,this.nanos)}default:return ge}}asDate(){return new Date(this.toMillis())}binaryOp(e,n){if(n instanceof It)switch(e){case"-":return new ke(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return ge}if(n instanceof ke)switch(e){case"+":return new It(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new It(this.seconds-n.seconds,this.nanos-n.nanos);default:return ge}return ge}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};class Is{message;constructor(e){this.message=e}}const Ga=-9223372036854776e3,Ha=2**63,wy=-(2n**63n),Sy=2n**63n-1n,Ay=/^[+-]?\d+$/,ky=/^[+-]?(?:NaN|Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?[fFdD]?)$/,Ey=/^([+-]?)0[xX]([0-9a-fA-F]*)(?:\.([0-9a-fA-F]*))?[pP]([+-]?\d+)[fFdD]?$/;function Ti(t,e){return new Is(`Type conversion error. Argument: [${t}], From type: [string], To type: [${e}].`)}function To(t,e,n){return new Is(`Unsupported operation error. Received: ${t}(${J(e)}). Expected: ${n}.`)}function Iy(t){return Number.isNaN(t)?0:t<=Ga?Ga:t>=Ha?Ha:Math.trunc(t)+0}function _y(t){if(!Ay.test(t))return Ti(t,"int");const e=BigInt(t);return e<wy||e>Sy?Ti(t,"int"):Number(e)}function xy(t){const[,e,n,s="",r]=t;if(n.length+s.length===0)return;const o=[...n+s].reduce((a,c)=>a*16+parseInt(c,16),0)*2**(Number(r)-4*s.length);return e==="-"?-o:o}function Cy(t){const e=t.replace(/^[\x00-\x20]+|[\x00-\x20]+$/g,"");if(ky.test(e))return parseFloat(e.replace(/[fFdD]$/,""));const n=Ey.exec(e),s=n?xy(n):void 0;return s===void 0?Ti(t,"float"):s}const Oy={overloads:"int(int), int(float), int(string)",convert(t){return typeof t=="number"?t:t instanceof re?Iy(t.value):typeof t=="string"?_y(t):To("int",t,this.overloads)}},Ty={overloads:"float(int), float(float), float(string)",convert(t){if(t instanceof re)return t;if(typeof t=="number")return new re(t);if(typeof t=="string"){const e=Cy(t);return typeof e=="number"?new re(e):e}return To("float",t,this.overloads)}},Ry={overloads:"string(int), string(float), string(null), string(string), string(bool), string(path)",convert(t){return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t===null?"null":t instanceof re||t instanceof oe&&t.typeName==="path"?t.toString():To("string",t,this.overloads)}},Ly=new Map([["int",Oy],["float",Ty],["string",Ry]]);function Fl(t){return Ly.get(t)}function ql(t,e){return e.length!==1?new Is(`Incorrect number of arguments. Received: ${e.length}. Expected: ${t.overloads}.`):t.convert(e[0])}class qs{message;constructor(e){this.message=e}}const Ri=-9223372036854776e3,Ka=2**63;function Ny(t){return Number.isNaN(t)?0:t<=Ri?Ri:t>=Ka?Ka:Math.round(t)+0}const zn=t=>new re(t),My=new Map([["abs",{overloads:"math.abs(int), math.abs(float)",arity:1,apply:([t],[e])=>e?zn(Math.abs(t)):t===Ri?t:Math.abs(t)}],["ceil",{overloads:"math.ceil(float)",arity:1,apply:([t])=>zn(Math.ceil(t))}],["floor",{overloads:"math.floor(float)",arity:1,apply:([t])=>zn(Math.floor(t))}],["round",{overloads:"math.round(float)",arity:1,apply:([t])=>Ny(t)}],["sqrt",{overloads:"math.sqrt(float)",arity:1,apply:([t])=>zn(Math.sqrt(t))}],["pow",{overloads:"math.pow(float, float)",arity:2,apply:([t,e])=>zn(Math.pow(t,e))}],["isNaN",{overloads:"math.isNaN(float)",arity:1,apply:([t])=>Number.isNaN(t)}]]);function Dy(t){if(t instanceof re)return{value:t.value,isFloat:!0};if(typeof t=="number")return{value:t,isFloat:!Number.isInteger(t)}}function $y(t,e){const n=My.get(t);if(!n)return new qs(`Function not found error: Name: [math.${t}].`);if(e.length!==n.arity)return new qs(`Incorrect number of arguments. Received: ${e.length}. Expected: ${n.overloads}.`);const s=e.map(Dy);return s.some(r=>r===void 0)?new qs(`Unsupported operation error. Received: math.${t}(${e.map(J).join(", ")}). Expected: ${n.overloads}.`):n.apply(s.map(r=>r.value),s.map(r=>r.isFloat))}class Mt{message;constructor(e){this.message=e}}const Py=Fl("string");function Or(t,e,n){if(n.length!==1)return new Mt(`Incorrect number of arguments. Received: ${n.length}. Expected: list.${t}(${e}).`);const[s]=n;return(e==="list"?Array.isArray(s):typeof s=="string")?s:new Mt(`Unsupported operation error. Received: list.${t}(${J(s)}). Expected: list.${t}(${e}).`)}function jy(t,e){const n=Or("concat","list",e);return n instanceof Mt?n:[...t,...n]}function Fy(t,e){const n=Or("removeAll","list",e);return n instanceof Mt?n:t.filter(s=>!n.some(r=>Co(s,r)))}function qy(t,e,n){const s=Or(t,"list",n);if(s instanceof Mt)return s;const r=(o,a)=>o.some(c=>Co(c,a)),i=s;return t==="hasAll"?i.every(o=>r(e,o)):t==="hasAny"?i.some(o=>r(e,o)):e.every(o=>r(i,o))}const Za=new Set(["concat","hasAll","hasAny","hasOnly","join","removeAll","toSet"]);function Uy(t,e){const n=Or("join","string",e);if(n instanceof Mt)return n;const s=[];for(const r of t){const i=ql(Py,[r]);if(i instanceof Is)return new Mt(i.message);s.push(i)}return s.join(n)}class wt extends oe{typeName="reference";path;constructor(e){super(),this.path=By(e)}static fromResourceName(e){return new wt(Ul(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof wt?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,n){return ge}}function By(t){let e=Ul(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ul(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class Ht extends oe{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let n=0;n<e.length;n++)if(typeof e[n]!="number")throw new TypeError(`Vector: element at index ${n} is not a number (got ${typeof e[n]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Ht)||e.value.length!==this.value.length)return!1;for(let n=0;n<this.value.length;n++)if(e.value[n]!==this.value[n])return!1;return!0}callMethod(e,n){return ge}}function Bl(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}const zy=new Set(["id","path","bypassRules","auth","env"]);function Wy(t){const e=Object.keys(t);if(e.length<2||!e.every(s=>zy.has(s))||typeof t.id!="string"||typeof t.path!="string")return!1;const n=t.path.split("/");return n.length>=2&&n.length%2===0&&n.every(s=>s.length>0)&&n[n.length-1]===t.id}function Vy(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),s=atob(e+n),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);return r}function Gy(t){const e=atob(t),n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n}function Hy(t){return typeof t=="object"&&t!==null&&(t.__type==="serverTimestamp"||t._methodName==="serverTimestamp"||t._methodName==="FieldValue.serverTimestamp")}function Li(t,e){const n={};for(const[s,r]of Object.entries(t))n[s]=zl(r,e);return n}function zl(t,e){return Hy(t)?e:Array.isArray(t)?t.map(n=>zl(n,e)):Bl(t)?Li(t,e):t}function tt(t){if(typeof t=="number"&&!Number.isInteger(t))return new re(t);if(Array.isArray(t))return t.map(tt);if(Bl(t)){if(typeof t.__type=="string")switch(t.__type){case"float":if(typeof t.value=="number")return new re(t.value);break;case"timestamp":if(typeof t.seconds=="number"&&typeof t.nanos=="number")return new ve(t.seconds,t.nanos);break;case"bytes":if(typeof t.base64=="string")return new He(Vy(t.base64));break;case"latlng":if(typeof t.lat=="number"&&typeof t.lng=="number")return new ut(t.lat,t.lng);break;case"duration":if(typeof t.seconds=="number"&&typeof t.nanos=="number")return new ke(t.seconds,t.nanos);break;case"reference":if(typeof t.path=="string")return new wt(t.path);break;case"path":if(Array.isArray(t.segments))return new nt(t.segments);break}if(t.__type__==="__vector__"&&Array.isArray(t.value))return new Ht(Object.freeze(t.value.slice()));if(typeof t.type=="string")switch(t.type){case"firestore/timestamp/1.0":if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number")return new ve(t.seconds,t.nanoseconds);break;case"firestore/bytes/1.0":if(typeof t.bytes=="string")return new He(Gy(t.bytes));break;case"firestore/geoPoint/1.0":if(typeof t.latitude=="number"&&typeof t.longitude=="number")return new ut(t.latitude,t.longitude);break;case"firestore/vectorValue/1.0":if(Array.isArray(t.vectorValues))return new Ht(Object.freeze(t.vectorValues.slice()));break}return Wy(t)?new wt(t.path):Object.fromEntries(Object.entries(t).map(([e,n])=>[e,tt(n)]))}return t}function Ja(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function Tr(t){const e=typeof t=="string"?t.split("/").filter(Boolean):t;return e.length===0||e.length%2!==0?!1:!e.some(n=>/^\{.*\}$/.test(n))}function Mn(t){let e=t.replace(/\$\(database\)/g,"(default)");const n="/databases/(default)/documents/";e.startsWith(n)?e=e.slice(n.length):e.startsWith("/databases/(default)/documents")&&(e=e.slice(30)),e.startsWith("/")&&(e=e.slice(1));const s=e.split("/").filter(i=>i.length>0&&i!=="."),r=[];for(const i of s)i===".."?r.length>1&&r.pop():r.push(i);return r.join("/")}function Ni(t,e){const n=t.split("/").filter(Boolean);return{data:tt(e),id:n.at(-1)??"",__name__:new nt(["databases","(default)","documents",...n])}}function Qa(t,e){const n=Mn(t),s=n.split("/").filter(Boolean);if(!Tr(s))throw new _(`get() requires a path pointing to a document (even segment count), got '${n}'`);let r=e.mockDocuments.get(n);if(!r&&e.getDoc){const i=e.getDoc(n);if(i){const o=tt(i);e.mockDocuments.set(n,o),r=o}}if(r){const i=tt(r);return e.identitylessFunctionMocks?.has(n)?{data:i}:Ni(n,i)}throw new _(`get() of non-existent document '${n}' (guard with exists() first)`)}function Ya(t,e){const n=Mn(t),s=n.split("/").filter(Boolean);if(!Tr(s))throw new _(`exists() requires a path pointing to a document (even segment count), got '${n}'`);const r=e.existsMocks?.get(n);if(r!==void 0)return r;if(e.mockDocuments.has(n))return!0;if(e.getDoc){const i=e.getDoc(n);if(i)return e.mockDocuments.set(n,tt(i)),!0}return!1}const Mi=10,Ky=20,Zy=Symbol.for("pyric.firestore.lookupCollector"),Xa=new WeakMap;function Jy(t){const e=Xa.get(t);if(e!==void 0)return e;const n=new Wl(Ky);return Xa.set(t,n),n}class Qy extends cn{constructor(e){super(e),this.name="LookupBudgetError"}}class Wl{limit;accessed=new Set;constructor(e=Mi){this.limit=e}charge(e,n){const s=`${e}:${n}`;if(this.accessed.has(s))return;const r=this.limit===Mi;if(this.accessed.size>=this.limit){let i=`multi-document batch/transaction (${this.limit} allowed across the atomic operation)`;throw r&&(i="request (production allows 10 per request; the 11th distinct access fails the evaluation)"),new Qy(`document access limit exceeded: already read ${this.limit} distinct documents via get()/exists()/getAfter()/existsAfter() in this ${i}`)}this.accessed.add(s)}}function Rs(t,e,n){if(!t.lookupBudget)return;const s=Mn(n);if(!Tr(s))return;if(e==="doc"){const a=globalThis[Zy];a!==void 0&&a.add(s)}t.lookupBudget.charge(e,s);const i=t.batchProjection;i!==void 0&&Jy(i).charge(e,s)}function Yy(t){if(t instanceof He)return t;if(typeof t=="string")return He.fromUtf8(t);throw new _(`hashing.* requires Bytes or String, got ${typeof t}`)}function Xy(t,e){if(t!=="md5"&&t!=="sha256"&&t!=="crc32"&&t!=="crc32c")throw new _(ts(`hashing.${t}`));if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: hashing.${t}(bytes), hashing.${t}(string).`);const n=Yy(e[0]);switch(t){case"md5":return new He(ob(n.data));case"sha256":return new He(cb(n.data));case"crc32":{const s=tb(n.data);return new He(ec(s))}case"crc32c":{const s=sb(n.data);return new He(ec(s))}}}function ec(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const eb=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let s=0;s<8;s++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function tb(t){let e=4294967295;for(let n=0;n<t.length;n++)e=eb[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const nb=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let s=0;s<8;s++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function sb(t){let e=4294967295;for(let n=0;n<t.length;n++)e=nb[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function Vl(t,e){const n=(t.length+8>>>6)+1<<6,s=new Uint8Array(n);s.set(t),s[t.length]=128;const r=new DataView(s.buffer),i=t.length<<3>>>0,o=Math.floor(t.length/536870912);return e?(r.setUint32(n-8,i,!0),r.setUint32(n-4,o,!0)):(r.setUint32(n-8,o,!1),r.setUint32(n-4,i,!1)),r}const rb=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],ib=new Uint32Array([3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745]);function ob(t){const e=Vl(t,!0);let n=1732584193,s=4023233417,r=2562383102,i=271733878;const o=new Uint32Array(16);for(let u=0;u<e.byteLength;u+=64){for(let h=0;h<16;h++)o[h]=e.getUint32(u+h*4,!0);let l=n,d=s,f=r,p=i;for(let h=0;h<64;h++){let m,g;h<16?(m=d&f|~d&p,g=h):h<32?(m=p&d|~p&f,g=5*h+1&15):h<48?(m=d^f^p,g=3*h+5&15):(m=f^(d|~p),g=7*h&15);const b=l+m+ib[h]+o[g]|0,y=rb[h];l=p,p=f,f=d,d=d+(b<<y|b>>>32-y)|0}n=n+l|0,s=s+d|0,r=r+f|0,i=i+p|0}const a=new Uint8Array(16),c=new DataView(a.buffer);return c.setUint32(0,n>>>0,!0),c.setUint32(4,s>>>0,!0),c.setUint32(8,r>>>0,!0),c.setUint32(12,i>>>0,!0),a}const ab=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function dt(t,e){return t>>>e|t<<32-e}function cb(t){const e=Vl(t,!1),n=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Int32Array(64);for(let o=0;o<e.byteLength;o+=64){for(let m=0;m<16;m++)s[m]=e.getInt32(o+m*4,!1);for(let m=16;m<64;m++){const g=s[m-15],b=s[m-2],y=dt(g,7)^dt(g,18)^g>>>3,w=dt(b,17)^dt(b,19)^b>>>10;s[m]=s[m-16]+y+s[m-7]+w|0}let a=n[0],c=n[1],u=n[2],l=n[3],d=n[4],f=n[5],p=n[6],h=n[7];for(let m=0;m<64;m++){const g=dt(d,6)^dt(d,11)^dt(d,25),b=d&f^~d&p,y=h+g+b+ab[m]+s[m]|0,w=dt(a,2)^dt(a,13)^dt(a,22),v=a&c^a&u^c&u,E=w+v|0;h=p,p=f,f=d,d=l+y|0,l=u,u=c,c=a,a=y+E|0}n[0]=n[0]+a|0,n[1]=n[1]+c|0,n[2]=n[2]+u|0,n[3]=n[3]+l|0,n[4]=n[4]+d|0,n[5]=n[5]+f|0,n[6]=n[6]+p|0,n[7]=n[7]+h|0}const r=new Uint8Array(32),i=new DataView(r.buffer);for(let o=0;o<8;o++)i.setInt32(o*4,n[o],!1);return r}const tc=new WeakSet,Gl=new WeakMap;function ub(t){if(tc.has(t))return;tc.add(t);const e=al(t);for(const n of e.functions)Gl.set(n.fn,n)}function lb(t){return Gl.get(t)}function Hl(t){return`/${t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}`}function ds(t,e,n,s){const r=[...n,...t.functions],i=t.path.segments,o={},a=[];let c=0,u,l;for(let m=0;m<i.length;m++){const g=i[m];if(g.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==g.value){u="literal-mismatch";break}c++}else if(g.type==="wildcard"){if(c>=e.length){u="request-shorter";break}o[g.name]=e[c],c===e.length-1&&a.push(g.name),c++}else{const b=i.length-m-1,y=e.length-c-b;if(y<0){u="request-shorter";break}o[g.name]=e.slice(c,c+y).join("/"),b===0&&(l={name:g.name,start:c},y>0&&a.push(g.name)),c+=y}}const d=m=>({...t.loc?{line:t.loc.line}:{},blockPath:Hl(t),matchedSegments:c,totalSegments:i.length,bindings:o,matched:!1,...m});if(u!==void 0)return s?.push(d({reason:u})),[];if(l){const m=[{block:t,pathVariables:o,candidateVariables:a,functions:r},...db(t,e,r,o,l,s)];return s?.push(d({matched:!0})),m}const f=e.slice(c),p=[],h=f.length>0?t.children:t.children.filter(m=>m.path.segments.every(g=>g.type==="recursive"));f.length===0&&p.push({block:t,pathVariables:o,candidateVariables:a,functions:r});for(const m of h)for(const g of ds(m,f,r,s))g.pathVariables={...o,...g.pathVariables},g.candidateVariables=[...a,...g.candidateVariables],p.push(g);return s?.push(d(p.length>0?{matched:!0}:{reason:"no-matching-child"})),p}function db(t,e,n,s,r,i){if(t.children.length===0)return[];const o=[],a=new Set;let c;for(let u=e.length-1;u>=r.start;u--){const l=e.slice(u),d={...s,[r.name]:e.slice(r.start,u).join("/")},f=[];let p=!1;for(const h of t.children)for(const m of ds(h,l,n,{push:g=>f.push(g)}))a.has(m.block)||(a.add(m.block),p=!0,m.pathVariables={...d,...m.pathVariables},o.push(m));if(c??=f,p)for(const h of f)i?.push(h)}if(o.length===0)for(const u of c??[])i?.push(u);return o}function Ls(t,e,n,s){if(e.length!==1)throw at(e,n,s),new _(`Incorrect number of arguments. Received: ${e.length}. Expected: ${t}(path).`);const r=xe(e[0],n,s);if(!(r instanceof nt)||r.segments.some(i=>/^\{.*\}$/.test(i)))throw new _(`Function not found error: Name: [${t}].`);return String(r)}function nc(t,e){if(e.split("/").some(s=>s==="."||s===".."))throw new _(`${t}() path '${e}' has a '.' or '..' segment, which is not a valid document id`);const n=Mn(e);if(!Tr(n.split("/").filter(Boolean)))throw new _(`${t}() requires a path pointing to a document (even segment count), got '${n}'`);return n}function sc(t){return Mn(t.afterStatePath.toString())}function fb(t,e,n,s){const r=n.functions?.get(t);if(r)return hb(t,r,e,n,s);switch(t){case"get":{const i=Ls("get",e,n,s);return Rs(n,"doc",i),Qa(i,n)}case"exists":{const i=Ls("exists",e,n,s);return Rs(n,"doc",i),Ya(i,n)}case"getAfter":{const i=Ls("getAfter",e,n,s),o=nc("getAfter",i);if(Rs(n,"after",o),o===sc(n)){if(n.afterState===null)throw new _(`getAfter() of non-existent document '${i}' (guard with existsAfter() first)`);return Ni(o,n.afterState)}if(n.batchProjection?.has(o)){const a=n.batchProjection.get(o);if(a===null)throw new _(`getAfter() of non-existent document '${i}' (guard with existsAfter() first)`);return Ni(o,a)}return Qa(i,n)}case"existsAfter":{const i=Ls("existsAfter",e,n,s),o=nc("existsAfter",i);return Rs(n,"after",o),o===sc(n)?n.existsAfter:n.batchProjection?.has(o)?n.batchProjection.get(o)!==null:Ya(i,n)}case"string":case"int":case"float":{const i=ql(Fl(t),at(e,n,s));if(i instanceof Is)throw new _(i.message);return i}case"path":{if(e.length!==1)throw at(e,n,s),new _(`Incorrect number of arguments. Received: ${e.length}. Expected: path(string).`);const i=xe(e[0],n,s);if(typeof i=="string")return nt.fromString(i);throw new _(`path() requires a string argument, got ${typeof i}`)}}throw new _(`Unknown function: ${t}`)}function hb(t,e,n,s,r){if(n.length!==e.parameters.length)throw at(n,s,r),new _(`Incorrect number of arguments. Received: ${n.length}. Expected: ${t}(${e.parameters.join(", ")}).`);const i=Object.create(null);for(let c=0;c<e.parameters.length;c++)i[e.parameters[c]]=ac(n[c],s,r);const o=lb(e);let a=s;if(o){const c={};for(const u of o.captures)Object.hasOwn(s.pathVariables,u)&&(c[u]=s.pathVariables[u]);a={...s,functions:o.functions,pathVariables:c,database:o.captures.has("database")?s.database:""}}s.trace?.enterFrame(t);try{for(const c of e.lets){const u=s.trace?s.trace.entries.length:-1;i[c.name]=ac(c.value,a,i),s.expressionBudget?.letBinding(c),u>=0&&s.trace?.markEntryAsLetBinding(u,c.name)}return xe(e.body,a,i)}finally{s.trace?.exitFrame()}}function pb(t,e,n,s,r){if(t.type==="identifier"){const a=t.name;if(rc(a)&&!Object.hasOwn(r,a)&&!Object.hasOwn(s.pathVariables,a)){const c=at(n,s,r);return s.expressionBudget?.node(t),gb(a,e,c)}if(!rc(a)&&!Object.hasOwn(r,a)&&!Object.hasOwn(s.pathVariables,a)&&!Eb(a))throw new Gt(`Unknown namespace or method '${a}.${e}()'`)}const[i,...o]=at([t,...n],s,r);if(i instanceof oe){let a;try{a=i.callMethod(e,o)}catch(c){throw c instanceof _?c:new _(c.message)}if(a===ge)throw e==="size"||e==="toSet"||Za.has(e)||Ci.has(e)||Ba.has(e)?new _(ts(e)):new Gt(`Unknown method '${e}' on ${i.typeName}`);return i instanceof ut&&typeof a=="number"?new re(a):a}if(e==="diff"&&Ge(i)){if(o.length!==1)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.diff(map).`);const a=o[0];if(Ge(a))return new Js(a,i);throw new _("diff() requires a map argument")}if(typeof i=="function")return i(...o);if(i instanceof fe){const a=Yg(i,e,o);if(a instanceof tn)throw new _(a.message);return a}if(i instanceof Js){switch(e){case"addedKeys":case"removedKeys":case"changedKeys":case"affectedKeys":case"unchangedKeys":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map_diff.${e}().`);return i[e]()}throw new _(ts(e))}if(Ge(i)){const a=i;switch(e){case"keys":case"values":{const c=ey(e,a,o);if(c instanceof Ml)throw new _(c.message);return c}case"size":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.size().`);return Object.keys(a).length;case"get":{if(o.length!==2)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: map.get(string, any), map.get(list, any).`);const c=o[0],u=o[1];if(Array.isArray(c)){let l=a;for(const d of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof oe)return u;const f=String(d);if(!Object.hasOwn(l,f))return u;l=l[f]}return l}if(typeof c!="string")throw new _(`Unsupported operation error. Received: map.get(${J(c)}, ${J(u)}). Expected: map.get(string, any), map.get(list, any).`);return Object.hasOwn(a,c)?a[c]:u}}}if(Array.isArray(i))switch(e){case"size":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: list.size().`);return i.length;case"hasAll":case"hasAny":case"hasOnly":{const a=qy(e,i,o);if(a instanceof Mt)throw new _(a.message);return a}case"concat":case"join":case"removeAll":{let a;if(e==="concat"?a=jy(i,o):e==="join"?a=Uy(i,o):a=Fy(i,o),a instanceof Mt)throw new _(a.message);return a}case"toSet":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: list.toSet().`);return new fe(i)}if(typeof i=="string")switch(e){case"size":case"lower":case"upper":case"trim":case"toUtf8":if(o.length!==0)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.${e}().`);return e==="size"?i.length:e==="lower"?i.toLowerCase():e==="upper"?i.toUpperCase():e==="trim"?i.trim():He.fromUtf8(i);case"split":case"matches":{if(o.length!==1)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.${e}(string).`);const a=o[0];if(typeof a!="string")throw new _(`Unsupported operation error. Received: string.${e}(${J(a)}). Expected: string.${e}(string).`);try{return e==="matches"?zg(a,i):i.split(xo("split",a,a,"g"))}catch(c){throw new _(c.message)}}case"replace":{if(o.length!==2)throw new _(`Incorrect number of arguments. Received: ${o.length}. Expected: string.replace(string, string).`);const[a,c]=o;if(typeof a!="string"||typeof c!="string")throw new _(`Unsupported operation error. Received: string.replace(${J(a)}, ${J(c)}). Expected: string.replace(string, string).`);try{return Vg(i,a,c)}catch(u){throw new _(u.message)}}}throw Za.has(e)||Ci.has(e)||Ba.has(e)?new _(ts(e)):new _(`Unknown method '${e}' on ${typeof i}`)}const mb=new Set(["math","timestamp","duration","latlng","hashing"]);function rc(t){return mb.has(t)}function gb(t,e,n){switch(t){case"math":return bb(e,n);case"timestamp":return Sb(e,n);case"duration":return Ab(e,n);case"latlng":return yb(e,n);case"hashing":return Xy(e,n)}throw new Gt(`Unknown namespace '${t}'`)}function ic(t){return t instanceof re?t.value:t}function yb(t,e){switch(t){case"value":{if(e.length!==2)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: latlng.value(float, float).`);const n=ic(e[0]),s=ic(e[1]);if(typeof n!="number"||typeof s!="number"||!Number.isFinite(n)||!Number.isFinite(s))throw new _(`Unsupported operation error. Received: latlng.value(${J(e[0])}, ${J(e[1])}). Expected: latlng.value(float, float).`);if(n<-90||n>90||s<-180||s>180)throw new _(" Latitude must be in range [-90.0, +90.0] and longitude must be in range [-180.0, +180.0]");return new ut(n,s)}}throw new Gt(`Unknown latlng method '${t}'`)}function bb(t,e){const n=$y(t,e);if(n instanceof qs)throw new _(n.message);return n}const vb=-621355968e5,wb=0xe677d21fdbff;function Sb(t,e){switch(t){case"date":{if(e.length!==3)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: timestamp.date(int, int, int).`);if(!e.every(i=>typeof i=="number"&&Number.isInteger(i)))throw new _(`Unsupported operation error. Received: timestamp.date(${e.map(J).join(", ")}). Expected: timestamp.date(int, int, int).`);const[n,s,r]=e;try{return ve.fromYMD(n,s,r)}catch(i){throw new _(i.message)}}case"value":{if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: timestamp.value(int).`);const n=e[0];if(typeof n!="number"||!Number.isInteger(n))throw new _(`Unsupported operation error. Received: timestamp.value(${J(n)}). Expected: timestamp.value(int).`);if(n<vb||n>wb)throw new _("Timestamp out of range");return ve.fromMillis(n)}}throw new Gt(`Unknown timestamp method '${t}'`)}function Ab(t,e){switch(t){case"value":{if(e.length!==2)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.value(int, string).`);const[n,s]=e;if(typeof n!="number"||!Number.isInteger(n)||typeof s!="string")throw new _(`Unsupported operation error. Received: duration.value(${J(n)}, ${J(s)}). Expected: duration.value(int, string).`);try{return ke.fromValue(n,s)}catch(r){throw new _(r.message)}}case"time":{if(e.length!==4)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.time(int, int, int, int).`);if(!e.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new _(`Unsupported operation error. Received: duration.time(${e.map(J).join(", ")}). Expected: duration.time(int, int, int, int).`);const[n,s,r,i]=e;return ke.fromTime(n,s,r,i)}case"abs":{if(e.length!==1)throw new _(`Incorrect number of arguments. Received: ${e.length}. Expected: duration.abs(duration).`);const n=e[0];if(!(n instanceof ke))throw new _(`duration.abs() requires a Duration argument, got ${typeof n}`);return ke.abs(n)}}throw new Gt(`Unknown duration method '${t}'`)}function xe(t,e,n={}){return e.trace?e.trace.capture(t,()=>oc(t,e,n)):oc(t,e,n)}function oc(t,e,n){const s=e.expressionBudget;if(!s)return Xr(t,e,n);if(t.type==="functionCall")return s.call(t),Xr(t,e,n);let r;try{r=Xr(t,e,n)}catch(i){throw i instanceof cn||s.node(t),i}return s.node(t),r}function Xr(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new re(t.value):t.value instanceof Uint8Array?new He(t.value):t.value;case"identifier":return kb(t.name,e,n);case"binaryOp":return _b(t,e,n);case"unaryOp":{if(t.op==="!")return!fs(xe(t.operand,e,n),t.operand);if(t.op==="-"){const s=xe(t.operand,e,n);if(s instanceof re)return new re(-s.value);if(typeof s=="number")return-s;throw new _(`Unsupported operation error. Received: -${J(s)}. Expected: -int, -float, -duration.`,t)}throw new _(`Unknown unary op: ${t.op}`,t)}case"ternary":return e.expressionBudget?.ternary(t),fs(xe(t.condition,e,n),t.condition)?xe(t.consequent,e,n):(e.expressionBudget?.ternaryElse(t),xe(t.alternate,e,n));case"memberAccess":{const s=xe(t.object,e,n);if(s==null)throw new _(`Property '${t.property}' accessed on ${s===null?"null":"undefined"} value`,t);if(s instanceof oe&&s.typeName!=="path")return s.field(t.property);if(!Ge(s)){const r=cy(s,t.property);if(r instanceof Re)throw new _(r.message,t);return r}if(Object.hasOwn(s,t.property))return s[t.property];throw new _(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const[s,r]=at([t.index,t.object],e,n);if(r==null)throw new _(`Index access on ${r===null?"null":"undefined"} value`,t);const i=jl(r,s);if(i instanceof Re)throw new _(i.message,t);return i}case"sliceAccess":{const[s,r,i]=at([t.object,t.start,t.end],e,n),o=uy(s,r,i);if(o instanceof Re)throw new _(o.message,t);return o}case"inExpr":{const[s,r]=at([t.collection,t.element],e,n),i=ly(r,s);if(i instanceof Fs)throw new _(i.message,t);return i}case"isExpr":{const s=xe(t.value,e,n);switch(t.typeName){case"string":return typeof s=="string";case"int":return s instanceof oe?!1:typeof s=="number";case"float":return s instanceof re;case"number":return s instanceof re?!0:s instanceof oe?!1:typeof s=="number";case"bool":return typeof s=="boolean";case"null":return s===null;case"list":return Array.isArray(s);case"set":return s instanceof fe;case"map":return s instanceof oe||s instanceof Js||s instanceof fe?!1:typeof s=="object"&&s!==null&&!Array.isArray(s);default:return s instanceof oe?s.typeName===t.typeName:!1}}case"listLiteral":return at(t.elements,e,n);case"mapLiteral":{const s=at(t.entries.flatMap(i=>[i.key,i.value]),e,n),r=[];for(let i=0;i<s.length;i+=2){const o=s[i];if(typeof o!="string")throw new _(`Type error. Received: [${J(o)}] Expected: [string].`,t);r.push([o,s[i+1]])}return Xg(r)}case"functionCall":return fb(t.name,t.args,e,n);case"methodCall":return pb(t.object,t.method,t.args,e,n);case"pathLiteral":{const s=[];let r;for(const i of t.segments)if(typeof i=="string")e.expressionBudget?.pathSegment(t),s.push(i);else try{const o=xe(i,e,n);if(typeof o!="string"&&(typeof o!="number"||!Number.isInteger(o)))throw new _(`Type error. Received: [${J(o)}] Expected: [string].`,i);s.push(String(o))}catch(o){r=Lo(r,o)}if(r)throw r;return new nt(s)}default:throw new _(`Unknown expression type: ${t.type}`,t)}}function kb(t,e,n){if(Object.hasOwn(n,t)){const s=n[t];if(s instanceof _)throw s;return s}if(Object.hasOwn(e.pathVariables,t))return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new _("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new _(`Undefined variable '${t}'`)}function Eb(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function Ib(t){return t instanceof _&&!(t instanceof cn)&&!(t instanceof Gt)}function Ro(t){if(Ib(t))return t;throw t}function Lo(t,e){const n=Ro(e);return t??n}function at(t,e,n){const s=new Array(t.length);let r;for(let i=0;i<t.length;i++)try{s[i]=xe(t[i],e,n)}catch(o){r=Lo(r,o)}if(r)throw r;return s}function ac(t,e,n){try{return xe(t,e,n)}catch(s){return Ro(s)}}function cc(t,e,n,s,r,i){let o,a;try{o=fs(xe(n,r,i),n)}catch(l){a=l}if(a instanceof cn)throw a;if(a===void 0&&o===e)return r.trace?.skip(s),e;r.expressionBudget?.logicalRight(t);let c,u;try{c=fs(xe(s,r,i),s)}catch(l){u=l}if(u instanceof cn)throw u;if(u===void 0&&c===e)return e;if(a!==void 0)throw a;if(u!==void 0)throw u;return c}function _b(t,e,n){const{op:s,left:r,right:i}=t;if(s==="&&")return cc(t,!1,r,i,e,n);if(s==="||")return cc(t,!0,r,i,e,n);let o,a,c;try{o=xe(r,e,n)}catch(u){c=Ro(u)}try{a=xe(i,e,n)}catch(u){c=Lo(c,u)}if(c)throw c;if(s!=="=="&&s!=="!="){if(o instanceof oe){const u=o.binaryOp(s,a);if(u!==ge)return u}if(typeof o=="number"&&a instanceof re){const u=new re(o).binaryOp(s,a);if(u!==ge)return u}if(a instanceof oe&&(s==="+"||s==="*")){const u=a.binaryOp(s,o);if(u!==ge)return u}if(o instanceof oe||a instanceof oe)throw new _(`Operator '${s}' is not defined between ${J(o)} and ${J(a)}`)}if((s==="<"||s===">"||s==="<="||s===">=")&&!(typeof o=="number"&&typeof a=="number"||typeof o=="string"&&typeof a=="string"))throw new _(`Operator '${s}' is not defined between ${typeof o} and ${typeof a}`);switch(s){case"==":return o===a||qa(o,a);case"!=":return!(o===a||qa(o,a));case"<":return o<a;case">":return o>a;case"<=":return o<=a;case">=":return o>=a;case"+":{if(typeof o=="string"&&typeof a=="string"||typeof o=="number"&&typeof a=="number")return o+a;throw new _(`Operator '+' is not defined between ${J(o)} and ${J(a)}`)}case"-":case"*":case"/":case"%":{if(typeof o!="number"||typeof a!="number")throw new _(`Unsupported operation error. Received: ${J(o)} ${s} ${J(a)}.`);if(s==="-")return o-a;if(s==="*")return o*a;if(a===0)throw new _(Fg);return s==="/"?Math.trunc(o/a):o%a}default:throw new _(`Unknown binary op: ${s}`)}}function fs(t,e){if(typeof t=="boolean")return t;throw new _(`Type error. Received: [${J(t)}] Expected: [bool].`,e)}const xb=`Unable to evaluate the expression as the maximum of ${os} expressions to evaluate has been reached.`;function Cb(t,e){return e===void 0?t:`${bh(e)}: ${t}`}class Ob{exhausted;limit;evaluated=0;constructor(e,n=os){this.exhausted=e,this.limit=n}node(e){this.charge(e===void 0?void 0:Zu(e))}call(e){this.charge(e===void 0?void 0:bn(e))}logicalRight(e){this.charge(e===void 0?void 0:bn(e))}ternary(e){this.charge(e===void 0?void 0:bn(e))}ternaryElse(e){const n=e===void 0?void 0:bn(e);this.charge(n),this.charge(n)}pathSegment(e){this.charge(e===void 0?void 0:bn(e))}letBinding(e){this.charge(e===void 0?void 0:bn(e))}charge(e){if(this.evaluated>=this.limit)throw this.exhausted(xb,e);this.evaluated++}}const Tb=new Set(["__proto__","prototype","constructor"]);function Qs(t){if(Tb.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Kl(t,e){const n={...t};for(const[s,r]of Object.entries(e)){Qs(s);const i=Object.hasOwn(n,s)?n[s]:void 0;Ge(r)&&Ge(i)?n[s]=Kl(i,r):n[s]=r}return n}function Rb(t,e,n){let s=t;for(let i=0;i<e.length-1;i++){const o=e[i];Qs(o);const a=Object.hasOwn(s,o)?s[o]:void 0,c=Ge(a)?{...a}:{};s[o]=c,s=c}const r=e[e.length-1];Qs(r),s[r]=n}function Lb(t,e){const n={...t};for(const[s,r]of Object.entries(e))s.includes(".")?Rb(n,s.split("."),r):(Qs(s),n[s]=r);return n}function Nb(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?Kl(e??{},n):n;case"update":return Lb(e??{},n);case"delete":return null}}const Mb="Paths are document-relative, from the first segment after /databases/<database>/documents, such as orders/o2.",uc=3;function Db(t){const e=t.split("/").filter(Boolean);return e.length>uc&&e[0]==="databases"&&e[2]==="documents"?e.slice(uc).join("/"):e.join("/")}const Di=t=>t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t),Ft=t=>({type:"literal",value:t,raw:JSON.stringify(t)});function Ys(t){return t.type==="memberAccess"?{object:t.object,property:t.property}:t.type==="bracketAccess"&&t.index.type==="literal"&&typeof t.index.value=="string"?{object:t.object,property:t.index.value}:null}function $b(t){const e=Ys(t);return!e||e.property!=="data"?!1:e.object.type==="identifier"&&e.object.name==="resource"}function Bt(t){const e=Ys(t);return!e||e.property.length===0||e.property.includes(".")||!$b(e.object)?null:e.property}function Zl(t){const e=Ys(t);if(!e||e.property!=="uid")return!1;const n=Ys(e.object);return!n||n.property!=="auth"?!1:n.object.type==="identifier"&&n.object.name==="request"}function No(t){const e=new Map;for(const n of t.where??[]){let s;if(n.op==="=="&&Di(n.value)?s=[n.value]:n.op==="in"&&Array.isArray(n.value)&&n.value.length>0&&n.value.length<=30&&n.value.every(Di)&&(s=Array.from(new Set(n.value))),s===void 0)continue;const r=e.get(n.field);r===void 0?e.set(n.field,[s]):r.push(s)}return e}function Mo(t){const e=new Map;for(const[n,s]of No(t)){let r=s[0];for(let i=1;i<s.length;i++){const o=s[i];r=r.filter(a=>o.includes(a))}e.set(n,r)}return e}function Pb(t,e,n=new Set){let s=500;const r=(i,o)=>{if(--s<0)return null;if(i.type==="functionCall"&&e.has(i.name)){if(o.has(i.name))return null;const a=e.get(i.name);if(a.parameters.length!==i.args.length)return null;const c=new Map;for(let l=0;l<a.parameters.length;l++){const d=r(i.args[l],o);if(!d)return null;c.set(a.parameters[l],d)}const u=new Set(o).add(i.name);for(const l of a.lets){const d=r(Kt(l.value,c),u);if(!d)return null;c.set(l.name,d)}return r(Kt(a.body,c),u)}switch(i.type){case"literal":case"identifier":return i;case"memberAccess":{const a=r(i.object,o);return a?{...i,object:a}:null}case"bracketAccess":{const a=r(i.object,o),c=r(i.index,o);return!a||!c?null:{...i,object:a,index:c}}case"binaryOp":{const a=r(i.left,o),c=r(i.right,o);return!a||!c?null:{...i,left:a,right:c}}default:return i}};return r(t,n)}function Ns(t,e,n){return{type:"binaryOp",op:n,left:t,right:e}}function wn(t){return{type:"unaryOp",op:"!",operand:t}}function Do(t,e){if(t.type==="literal"&&Di(t.value))return t.value;if(Zl(t))return e}function ei(t,e,n,s){const r=Do(e,s);return r===void 0?!1:(n.where??[]).some(i=>i.field===t&&i.op==="array-contains"&&i.value===r)}function jb(t,e,n,s){const r=(i,o)=>{const a=Bt(i);if(a===null)return!1;const c=n.get(a);if(!c)return!1;const u=Do(o,s);return u===void 0?!1:c.some(l=>l.length===1&&l[0]===u)};return r(t,e)||r(e,t)}function Fb(t,e,n,s){const r=Bt(t);if(r===null||e.type!=="listLiteral")return!1;const i=n.get(r);if(!i)return!1;const o=[];for(const a of e.elements){const c=Do(a,s);if(c===void 0)return!1;o.push(c)}return i.some(a=>a.every(c=>o.includes(c)))}function qb(t,e,n,s){let r=!1;const i=No(e),o=Mo(e),a=new Map;for(const[l,d]of o)d.length>0&&a.set(l,d);let c=[new Map];for(const[l,d]of a){if(c.length*d.length>30)return;c=c.flatMap(f=>d.map(p=>new Map([...f,[l,p]])))}const u=[];for(const l of c){let f=function(h,m=new Set){if(--d<0)throw new Error("proof expansion budget");const g=Bt(h);if(g!==null&&l.has(g))return Ft(l.get(g));if(h.type==="functionCall"&&n.has(h.name)){if(sn(h,n))return h;if(m.has(h.name))throw new Error("recursive proof helper");const y=n.get(h.name);if(y.parameters.length!==h.args.length)throw new Error("proof arity");const w=new Map(y.parameters.map((v,E)=>[v,h.args[E]]));for(const v of y.lets)w.set(v.name,Kt(v.value,w));return f(Kt(y.body,w),new Set([...m,h.name]))}if(h.type==="inExpr"){const y=f(h.element,m),w=f(h.collection,m),v=Bt(w);return v!==null&&ei(v,y,e,s)||Fb(y,w,i,s)?Ft(!0):{...h,element:y,collection:w}}const b=y=>f(y,m);switch(h.type){case"literal":case"identifier":return h;case"memberAccess":{const y={...h,object:b(h.object)},w=Bt(y);return w!==null&&l.has(w)?Ft(l.get(w)):y}case"bracketAccess":{const y={...h,object:b(h.object),index:b(h.index)},w=Bt(y);return w!==null&&l.has(w)?Ft(l.get(w)):y}case"sliceAccess":return{...h,object:b(h.object),start:b(h.start),end:b(h.end)};case"binaryOp":{const y=b(h.left),w=b(h.right);return h.op==="=="&&jb(y,w,i,s)?Ft(!0):{...h,left:y,right:w}}case"unaryOp":return{...h,operand:b(h.operand)};case"ternary":return{...h,condition:b(h.condition),consequent:b(h.consequent),alternate:b(h.alternate)};case"isExpr":return{...h,value:b(h.value)};case"methodCall":{const y=b(h.object),w=h.args.map(b),v=Bt(y);if(v!==null&&w.length===1&&w[0].type==="listLiteral"&&w[0].elements.every(E=>sn(E,n))){const E=w[0].elements;if(h.method==="hasAny"&&E.some(I=>ei(v,I,e,s))||h.method==="hasAll"&&E.length>0&&E.every(I=>ei(v,I,e,s)))return Ft(!0)}return{...h,object:y,args:w}}case"functionCall":return{...h,args:h.args.map(b)};case"listLiteral":return{...h,elements:h.elements.map(b)};case"mapLiteral":return{...h,entries:h.entries.map(y=>({key:b(y.key),value:b(y.value)}))};case"pathLiteral":return{...h,segments:h.segments.map(y=>typeof y=="string"?y:b(y))}}},p=function(h){if(sn(h,n))return h;if(h.type==="unaryOp"&&h.op==="!"){const b=h.operand;if(b.type==="binaryOp"&&b.op==="&&")return p(Ns(wn(b.left),wn(b.right),"||"));if(b.type==="binaryOp"&&b.op==="||")return p(Ns(wn(b.left),wn(b.right),"&&"));if(b.type==="unaryOp"&&b.op==="!"){const y=p(b.operand);return y?wn(wn(y)):void 0}return}if(h.type!=="binaryOp"||h.op!=="&&"&&h.op!=="||")return;const m=p(h.left),g=p(h.right);if(m&&g)return Ns(m,g,h.op);if(h.op==="||")return r=!0,m??g},d=2e3;try{const h=p(f(t));if(!h)return;u.push(h)}catch{return}}return{condition:u.reduce((l,d)=>Ns(l,d,"&&")),partial:r}}function Ub(t,e,n=new Map,s){const r=Bb(t,e,n,s);if(r.provable||r.kind==="constraints-not-satisfied")return r;const i=qb(t,e,n,s);return i?{provable:!0,reason:"query-guaranteed facts reduce every candidate alternative to a document-independent residual",residualCondition:i.condition,proofFailure:i.partial?r:void 0}:r}function Bb(t,e,n=new Map,s){if(sn(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const r=Wb(t,n,s);if(!r.ok||r.required.length===0){const f="list rule depends on per-document data through a predicate the query cannot discharge (unconstrained candidate fields or unsupported query facts remain after helper expansion)";return{provable:!1,kind:"unsupported-predicate",reason:`${f} — Pyric cannot establish whether Firebase would allow this query`,residual:{missing:[],mismatched:[],outOfScope:f,...r.ok?{}:{predicate:Ae(r.predicate),predicateLoc:r.predicateLoc}}}}const i=r.required,o=e.where??[],a=No(e),c=Mo(e),u=[],l=[];let d=!1;for(const f of i){const p=c.get(f.field),h=a.get(f.field),m=p!==void 0&&p.length===1&&ti(p[0],f.value),g=h!==void 0&&h.some(w=>w.length===1&&ti(w[0],f.value));if(m||g){(p?.length??0)===0&&(d=!0);continue}const y=o.find(w=>w.field===f.field&&w.op==="=="&&!ti(w.value,f.value));y?l.push({field:f.field,expectedValue:f.value,actualValue:y.value}):u.push({field:f.field,expectedValue:f.value,fromAuthUid:f.fromAuthUid})}if(u.length===0&&l.length===0){const f={provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"};return d&&(f.residualCondition=r.residual),f}return{provable:!1,kind:"constraints-not-satisfied",reason:zb(u,l),residual:{missing:u,mismatched:l}}}function zb(t,e){const n=[];if(t.length>0){const s=t.map(r=>`resource.data.${r.field} == ${r.fromAuthUid?"request.auth.uid":JSON.stringify(r.expectedValue)}`).join(", ");n.push(`the query has no matching where(...) equality for [${s}]`)}if(e.length>0){const s=e.map(r=>`resource.data.${r.field} == ${JSON.stringify(r.expectedValue)} but the query pins ${JSON.stringify(r.actualValue)}`).join(", ");n.push(`the query where(...) value does not match [${s}]`)}return`${n.join("; ")} — Pyric cannot prove the query safe ("rules are not filters")`}function sn(t,e=new Map,n=new Set){const s=r=>{switch(r.type){case"literal":return!0;case"identifier":return r.name!=="resource";case"memberAccess":return s(r.object);case"bracketAccess":return s(r.object)&&s(r.index);case"sliceAccess":return s(r.object)&&s(r.start)&&s(r.end);case"binaryOp":return s(r.left)&&s(r.right);case"unaryOp":return s(r.operand);case"ternary":return s(r.condition)&&s(r.consequent)&&s(r.alternate);case"inExpr":return s(r.element)&&s(r.collection);case"isExpr":return s(r.value);case"listLiteral":return r.elements.every(s);case"mapLiteral":return r.entries.every(i=>s(i.key)&&s(i.value));case"pathLiteral":return r.segments.every(i=>typeof i=="string"||s(i));case"methodCall":return s(r.object)&&r.args.every(s);case"functionCall":{if(!r.args.every(s))return!1;const i=e.get(r.name);if(!i)return!0;if(n.has(r.name))return!1;const o=new Set(n).add(r.name),a=new Map;i.parameters.forEach((c,u)=>{const l=r.args[u];l&&a.set(c,l)});for(const c of i.lets){const u=Kt(c.value,a);if(!sn(u,e,o))return!1;a.set(c.name,u)}return sn(Kt(i.body,a),e,o)}default:return!1}};return s(t)}function Wb(t,e,n){const s=[];let r=t,i=t.loc;const o=(c,u,l=t.loc)=>{if(c.type==="binaryOp"&&c.op==="&&"){const p=o(c.left,u,l);if(!p)return null;const h=o(c.right,u,l);return h?{type:"binaryOp",op:"&&",left:p,right:h}:null}if(c.type==="functionCall"&&e.has(c.name)&&!u.has(c.name)){const p=e.get(c.name),h=new Map;p.parameters.forEach((b,y)=>{const w=c.args[y];w&&h.set(b,w)});for(const b of p.lets)h.set(b.name,Kt(b.value,h));const m=Kt(p.body,h),g=new Set(u).add(c.name);return o(m,g,p.loc??l)}const d=Vb(c,e,n,u);return d?(s.push(d),{type:"literal",value:!0,raw:"true"}):sn(c,e)?c:(r=c,i=c.loc??l,null)},a=o(t,new Set);return a?{ok:!0,required:s,residual:a}:{ok:!1,predicate:r,predicateLoc:i}}function Vb(t,e,n,s){const r=Pb(t,e,s);if(!r||r.type!=="binaryOp"||r.op!=="==")return null;const i=(o,a)=>{const c=Bt(o);return c===null?null:a.type==="literal"?{field:c,value:a.value,fromAuthUid:!1}:n!==void 0&&Zl(a)?{field:c,value:n,fromAuthUid:!0}:null};return i(r.left,r.right)??i(r.right,r.left)}function Kt(t,e){const n=s=>{switch(s.type){case"identifier":return e.get(s.name)??s;case"literal":return s;case"memberAccess":return{...s,object:n(s.object)};case"methodCall":return{...s,object:n(s.object),args:s.args.map(n)};case"bracketAccess":return{...s,object:n(s.object),index:n(s.index)};case"sliceAccess":return{...s,object:n(s.object),start:n(s.start),end:n(s.end)};case"binaryOp":return{...s,left:n(s.left),right:n(s.right)};case"unaryOp":return{...s,operand:n(s.operand)};case"ternary":return{...s,condition:n(s.condition),consequent:n(s.consequent),alternate:n(s.alternate)};case"inExpr":return{...s,element:n(s.element),collection:n(s.collection)};case"isExpr":return{...s,value:n(s.value)};case"listLiteral":return{...s,elements:s.elements.map(n)};case"mapLiteral":return{...s,entries:s.entries.map(r=>({key:n(r.key),value:n(r.value)}))};case"pathLiteral":return{...s,segments:s.segments.map(r=>typeof r=="string"?r:n(r))};case"functionCall":return{...s,args:s.args.map(n)}}};return n(t)}function ti(t,e){return t===e}function Jl(t){const e=new Map,n=new Set;for(const s of t)e.has(s.name)&&n.add(s.name),e.set(s.name,s);return{functions:e,ambiguousNames:n}}function Ql(t,e,n,s=Gb){const r=new Set;return{pathInvariant:!Us(t,e,n,s,new Set,r),requiredFunctions:r}}function Us(t,e,n,s,r,i){const o=a=>Us(a,e,n,s,r,i);switch(t.type){case"literal":return!1;case"identifier":return e.has(t.name)||t.name==="request";case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!dc.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&dc.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(a=>o(a.key)||o(a.value));case"pathLiteral":return t.segments.some(a=>typeof a!="string"&&o(a));case"functionCall":{for(const l of t.args)if(!ni(l)&&o(l))return!0;if(s.has(t.name))return!0;const a=n.get(t.name);if(!a)return t.args.some(ni);if(t.args.length!==a.parameters.length||(i.add(a.name),r.has(a.name)))return!0;const c=new Set(r).add(a.name),u=new Map;for(let l=0;l<a.parameters.length;l++)u.set(a.parameters[l],t.args[l]);for(const l of a.lets){const d=lc(l.value,u);if(!ni(d)&&Us(d,e,n,s,c,i))return!0;u.set(l.name,d)}return Us(lc(a.body,u),e,n,s,c,i)}}}function ni(t){return t.type==="identifier"&&t.name==="request"}function lc(t,e){const n=s=>{switch(s.type){case"identifier":return e.get(s.name)??s;case"literal":return s;case"memberAccess":return{...s,object:n(s.object)};case"methodCall":return{...s,object:n(s.object),args:s.args.map(n)};case"bracketAccess":return{...s,object:n(s.object),index:n(s.index)};case"sliceAccess":return{...s,object:n(s.object),start:n(s.start),end:n(s.end)};case"binaryOp":return{...s,left:n(s.left),right:n(s.right)};case"unaryOp":return{...s,operand:n(s.operand)};case"ternary":return{...s,condition:n(s.condition),consequent:n(s.consequent),alternate:n(s.alternate)};case"inExpr":return{...s,element:n(s.element),collection:n(s.collection)};case"isExpr":return{...s,value:n(s.value)};case"listLiteral":return{...s,elements:s.elements.map(n)};case"mapLiteral":return{...s,entries:s.entries.map(r=>({key:n(r.key),value:n(r.value)}))};case"pathLiteral":return{...s,segments:s.segments.map(r=>typeof r=="string"?r:n(r))};case"functionCall":return{...s,args:s.args.map(n)}}};return n(t)}const dc=new Set(["auth","method","query","time"]),Gb=new Set;function Yl(t,e,n,s,r){if(t!==null===!1)return{kind:"no-rule"};const o=e.split("/").filter(m=>m.length>0),a=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const m of t.service.match.children)c.push(...ds(m,o,a));if(c.length===0)return{kind:"no-rule"};const l=[],d=new Map;let f=0;for(const m of c){const g=Jl(m.functions),b=g.functions;for(const y of m.block.allows){if(y.operations.some(V=>V==="list"?!0:V==="read")===!1)continue;if(f++,Ql(y.condition,new Set(m.candidateVariables),b,g.ambiguousNames).pathInvariant===!0===!1){l.push({kind:"unsupported-path",reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:fc(y,r)});continue}const I=Ub(y.condition,s,b,n?.uid);I.provable===!0&&d.set(y,I.residualCondition?{...y,condition:I.residualCondition}:y);const W=I.provable?I.proofFailure:I;W&&l.push({kind:W.kind,reason:W.reason,residual:W.residual,rule:fc(y,r),...W.residual.predicate?{predicate:Xl(W.residual.predicate,W.residual.predicateLoc??y.loc,r)}:{}})}}if(f===0)return{kind:"no-rule"};if(d.size===0){const m=l[0];return{kind:"unprovable",failures:l,reason:m.reason,residual:m.residual,...m.rule?{rule:{...m.rule,verdict:"deny"}}:{}}}return{kind:"provable",failures:l,evaluationAst:Hb(t,d),syntheticResource:Kb(s)}}function fc(t,e=""){return Xl(Ae(t.condition),t.loc,e)}function Xl(t,e,n=""){if(!e)return{expression:t};const{line:s,col:r,file:i}=e,o=Im(n,s,r,i,t);return o?{...o,column:o.col,expression:o.expression??t}:{line:s,col:r,column:r,file:i??"firestore.rules",citation:`${i??"firestore.rules"}:${s}:${r}`,expression:t}}function Hb(t,e){const n=s=>({...s,allows:s.allows.filter(r=>e.has(r)).map(r=>e.get(r)),children:s.children.map(n)});return{...t,service:{...t.service,match:n(t.service.match)}}}function Kb(t){const e={};for(const[n,s]of Mo(t))s.length===1&&(e[n]=s[0]);return e}function Zb(t){return t?{...t.where!==void 0?{where:t.where}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.offset!==void 0?{offset:t.offset}:{},...t.orderBy!==void 0?{orderBy:t.orderBy}:{}}:{}}function ed(t){const e=t.where!==void 0&&t.where.length>0;if(!(!e&&t.limit==null&&t.offset==null&&t.orderBy==null))return{...e?{where:t.where.map(n=>({field:n.field,op:n.op,value:Array.isArray(n.value)?[...n.value]:n.value}))}:{},...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}function $i(t){const e=[];for(const s of t.missing)s.fromAuthUid?e.push(` .where('${s.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(s.expectedValue)}`):e.push(` .where('${s.field}', '==', ${JSON.stringify(s.expectedValue)})`);for(const s of t.mismatched)e.push(` .where('${s.field}', '==', ${JSON.stringify(s.expectedValue)}) // the query pins ${JSON.stringify(s.actualValue)}, but the rule requires ${JSON.stringify(s.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
|
|
1707
1707
|
${e.join(`
|
|
1708
|
-
`)}`}function hc(t){return/^[A-Za-z0-9_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function
|
|
1709
|
-
`)}class Wb{attempts=[];push(e){this.attempts.push(e)}}function Vb(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Gb(t){return t instanceof Ol?{kind:"expressions",limit:os,message:t.message,...t.position===void 0?{}:{line:t.position.line,column:t.position.column}}:{kind:"document-lookups",limit:Mi,message:t.message}}function Hb(t,e,n,s){const r=Vb(e),i=[],o=[],a=[];for(let p=0;p<t.allows.length;p++){const h=t.allows[p];h.operations.some(g=>r.includes(g))&&a.push({rule:h,index:p})}if(a.length===0)return o.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:o};let u=!1;const l=n.trace,d=p=>{n.expressionBudget&&(p.evaluatedExpressions=n.expressionBudget.evaluated),i.push(p)};for(const{rule:p,index:h}of a){const m=Kb(p,h,s),g=new cy;n.trace=g;try{const b=fs(xe(p.condition,n),p.condition);if(m.expressionTrace=g.entries,b)return m.verdict="ALLOW",d(m),n.trace=l,{decision:"ALLOW",trace:i,notes:o};m.verdict="DENY",d(m)}catch(b){if(m.expressionTrace=g.entries,b instanceof cn){m.verdict="ERROR",m.message=b.message,d(m),n.trace=l;const v=Gb(b),E=v.line===void 0||v.column===void 0?void 0:{line:v.line,column:v.column},I=Sb(v.message,E);return o.push(`Request denied by a rules resource limit: ${I.endsWith(".")?I:`${I}.`} The limit is per request, so no other allow rule or match block was evaluated.`),{decision:"DENY",trace:i,notes:o,resourceLimit:v}}b instanceof Gt?(u=!0,m.verdict="UNSUPPORTED",m.message=b.message):(m.verdict="ERROR",b instanceof Error?m.message=b.message:m.message=String(b)),d(m)}}n.trace=l;let f="DENY";return u&&(f="UNSUPPORTED"),{decision:f,trace:i,notes:o}}function Kb(t,e,n){const s=Ae(t.condition),r={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:s};if(t.loc!==void 0){const o=t.loc;if(r.line=o.line,r.col=o.col,r.column=o.col,o.file!==void 0?(r.file=o.file,r.citation=`${o.file}:${o.line}:${o.col}`):(r.file="firestore.rules",r.citation=`firestore.rules:${o.line}:${o.col}`),n!==void 0){const u=Il(n,o.line,o.col,o.file,s);u!==void 0&&(r.line=u.line,r.col=u.col,r.column=u.col,r.file=u.file,r.citation=u.citation,u.expression!==void 0&&(r.conditionText=u.expression))}}return r}function Zb(t,e,n,s,r,i,o){const a=new Map;for(const I of e)a.set(I.name,I);const c=new Map,u=new Set,l=new Map;for(const I of t.functionMocks??[]){const j=Mn(I.path);I.function==="get"&&typeof I.result=="object"&&I.result!==null?(c.set(j,tt(I.result)),u.add(j)):I.function==="exists"&&l.set(j,I.result===!0)}const d=t.requestTime?ve.fromIsoString(t.requestTime):ve.fromMillis(Date.now()),p=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],h=new nt(p,n),m=tt(t.data??{}),g=t.resource===void 0||t.resource===null?null:tt(t.resource);let b,y;if(t.writeMode)b=_b(t.writeMode,g,m),y=b!==null;else switch(t.method){case"create":case"update":b=m,y=!0;break;case"delete":b=null,y=!1;break;case"get":case"list":default:b=g,y=g!==null;break}const w=b!==null?tt(Li(b,d)):null;let v;t.method==="create"||t.method==="update"?v={data:w??{}}:t.data!==void 0&&(v={data:tt(Li(t.data,d))});const E={auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,method:t.method,path:h,...Ja(t)?{query:Ja(t)}:{},time:d};return v!==void 0&&(E.resource=v),{request:E,resource:t.method==="create"||g===null?null:{data:tt(g)},mockDocuments:c,identitylessFunctionMocks:u,existsMocks:l,getDoc:s,pathVariables:n,functions:a,database:"(default)",afterStatePath:h,afterState:w,existsAfter:y,...r?{batchProjection:r}:{},lookupBudget:i,expressionBudget:o}}class Jb{simulate(e,n,s){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const r=pl(e);return r.ok?this.simulateParsed(r.ast,e,n,s):{success:!1,error:{code:"PARSE_FAILED",message:`Firestore ${r.rejection.message}`,recoverable:!0}}}simulateParsed(e,n,s,r){nb(e);const i=r?.sourceMap??_o(n),o=[];let a=0,c=0,u=0;const l={database:"(default)"};for(const d of e.service.match.path.segments)d.type==="wildcard"&&(l[d.name]="(default)");for(const d of s){const f=Cb(d.path),p=f.split("/").filter(Boolean),h=d.method==="list",m=p.length%2===1;let g,b=e,y=d;if(h&&!r?.skipQueryProof){const ce=p.length===0?"__listPlaceholder__":m?`${f}/__listPlaceholder__`:f,Y=Bb(d.query),X=Kl(e,ce,d.auth??null,Y,n);if(X.kind==="no-rule")g={verdict:"NO_RULE",provable:!1,kind:"no-rule",failures:[]};else if(X.kind==="unprovable"){const be=X.failures.find(jt=>jt.kind!=="constraints-not-satisfied")??X.failures[0],ie=$i(be.residual);g={verdict:"UNPROVABLE",provable:!1,kind:be.kind,failures:X.failures,reason:be.reason,residual:be.residual,...ie?{remediation:ie}:{},...be.rule?{rule:{...be.rule,verdict:"deny"}}:{}}}else{let be=!1;if(X.failures.length>0){const ie=this.simulateParsed(X.evaluationAst,n,[{...d,path:ce,resource:X.syntheticResource,expectation:"ALLOW"}],{...r,sourceMap:i,skipQueryProof:!0});ie.success&&ie.data.results[0]?.decision!=="ALLOW"&&(be=!0)}if(be){const ie=X.failures.find(Cs=>Cs.kind!=="constraints-not-satisfied")??X.failures[0],jt=$i(ie.residual);g={verdict:"UNPROVABLE",provable:!1,kind:ie.kind,failures:X.failures,reason:ie.reason,residual:ie.residual,...jt?{remediation:jt}:{},...ie.rule?{rule:{...ie.rule,verdict:"deny"}}:{}}}else g={verdict:"PROVABLE",provable:!0,kind:"provable",failures:X.failures};d.resource===void 0&&(d.query?.where?.length??0)>0&&(b=X.evaluationAst,y={...d,resource:X.syntheticResource})}}const w=[...b.functions??[],...b.service.functions??[],...b.service.match.functions];let v=[];const E=new Wb;for(const ce of b.service.match.children)v.push(...ds(ce,p,w,E));let I=!1;if(h&&(m||v.length===0)){const ce=[...p,"__hypothetical_doc__"],Y=[];for(const be of b.service.match.children)Y.push(...ds(be,ce,w,E));Y.length>0&&(v=Y,I=!0)}const W={requestPath:f,attempts:E.attempts};if(v.length===0){const ce=d.expectation==="DENY"?"PASSED":"FAILED";ce==="PASSED"?a++:c++,o.push({description:d.description,expectation:d.expectation,state:ce,decision:"DENY",evaluatedExpressions:0,trace:[],notes:[`No match block found for path '${f}', so the request is denied by default.`,xb],pathResolution:W,...g?{queryProof:g}:{}});continue}let T="DENY";const N=[],B=[];let G=!1,C,S,x=!1;const F=new ql,D=new Ab((ce,Y)=>new Ol(ce,Y));for(const ce of v){const Y={...l,...ce.pathVariables},X=Zb(y,ce.functions,Y,r?.getDoc,r?.batchProjection,F,D),be=zl(ce.block),ie=Hb(ce.block,d.method,X,i);for(const gn of ie.trace)gn.matchPath=be;if(N.push(...ie.trace),B.push(...ie.notes),ie.resourceLimit!==void 0){T="DENY",x=!0;const gn=N.slice(0,-1).find(Jo=>Jo.verdict==="ERROR");ie.resourceLimit.kind==="expressions"&&gn?B.push(`The request reached the limit (${ie.resourceLimit.message}) after an earlier allow rule raised an error; production reports that earlier error: ${gn.message??"evaluation error"}`):S=ie.resourceLimit;break}if(ie.decision==="ALLOW"){T="ALLOW",C=be;break}ie.decision==="UNSUPPORTED"&&(G=!0)}T!=="ALLOW"&&!x&&G&&(T="UNSUPPORTED"),T==="ALLOW"&&C!==void 0&&B.push(`Allowed by match block '${C}'`),I===!0&&B.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let Oe;T==="UNSUPPORTED"?(Oe="UNSUPPORTED",u++):T===d.expectation?(Oe="PASSED",a++):(Oe="FAILED",c++),o.push({description:d.description,expectation:d.expectation,state:Oe,decision:T,evaluatedExpressions:D.evaluated,...S?{resourceLimit:S}:{},...g?{queryProof:g}:{},trace:N,notes:B,pathResolution:W})}return{success:!0,data:{passed:a,failed:c,unsupported:u,results:o}}}}var Q;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(Q||(Q={}));var pc;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(pc||(pc={}));const R=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ut=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}},k=Q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Dt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let a=s,c=0;for(;c<o.path.length;){const u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return r(this),s}static assert(e){if(!(e instanceof Dt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}Dt.create=t=>new Dt(t);const Pi=(t,e)=>{let n;switch(t.code){case k.invalid_type:t.received===R.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Q.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:n=`Unrecognized key(s) in object: ${Q.joinValues(t.keys,", ")}`;break;case k.invalid_union:n="Invalid input";break;case k.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Q.joinValues(t.options)}`;break;case k.invalid_enum_value:n=`Invalid enum value. Expected ${Q.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:n="Invalid function arguments";break;case k.invalid_return_type:n="Invalid function return type";break;case k.invalid_date:n="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Q.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case k.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case k.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case k.custom:n="Invalid input";break;case k.invalid_intersection_types:n="Intersection results could not be merged";break;case k.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:n="Number must be finite";break;default:n=e.defaultError,Q.assertNever(t)}return{message:n}};let Qb=Pi;function Yb(){return Qb}const Xb=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const c=s.filter(u=>!!u).slice().reverse();for(const u of c)a=u(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function O(t,e){const n=Yb(),s=Xb({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Pi?void 0:Pi].filter(r=>!!r)});t.common.issues.push(s)}class Ue{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return $;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ue.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return $;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const $=Object.freeze({status:"aborted"}),Yn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),mc=t=>t.status==="aborted",gc=t=>t.status==="dirty",Tn=t=>t.status==="valid",Xs=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));class St{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const yc=(t,e)=>{if(Tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Dt(t.common.issues);return this._error=n,this._error}}};function z(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:r}}class Z{get description(){return this._def.description}_getType(e){return Ut(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ue,ctx:{common:e.parent.common,data:e.data,parsedType:Ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Xs(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)},r=this._parseSync({data:e,path:s.path,parent:s});return yc(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Tn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Tn(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Xs(r)?r:Promise.resolve(r));return yc(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:k.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new dn({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Nt.create(this,this._def)}nullable(){return fn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return or.create(this,this._def)}or(e){return nr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new dn({...z(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new ar({...z(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new td({typeName:P.ZodBranded,type:this,...z(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new cr({...z(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Po.create(this,e)}readonly(){return ur.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ev=/^c[^\s-]{8,}$/i,tv=/^[0-9a-z]+$/,nv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sv=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rv=/^[a-z0-9_-]{21}$/i,iv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ov=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,av=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let si;const uv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,fv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",mv=new RegExp(`^${Yl}$`);function Xl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function gv(t){return new RegExp(`^${Xl(t)}$`)}function yv(t){let e=`${Yl}T${Xl(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function bv(t,e){return!!((e==="v4"||!e)&&uv.test(t)||(e==="v6"||!e)&&dv.test(t))}function vv(t,e){if(!iv.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function wv(t,e){return!!((e==="v4"||!e)&&lv.test(t)||(e==="v6"||!e)&&fv.test(t))}class Ot extends Z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.string,received:i.parsedType}),$}const s=new Ue;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?O(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&O(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")av.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"email",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")si||(si=new RegExp(cv,"u")),si.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"emoji",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")sv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"uuid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")rv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"nanoid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")ev.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cuid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")tv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cuid2",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")nv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"ulid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),O(r,{validation:"url",code:k.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"regex",code:k.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?yv(i).test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?mv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?gv(i).test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ov.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"duration",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?bv(e.data,i.version)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"ip",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?vv(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"jwt",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?wv(e.data,i.version)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cidr",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?hv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"base64",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?pv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"base64url",code:k.invalid_string,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:k.invalid_string,...L.errToObj(s)})}_addCheck(e){return new Ot({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...L.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...L.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...L.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...L.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...L.errToObj(n)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Ot.create=t=>new Ot({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...z(t)});function Sv(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Rn extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.number,received:i.parsedType}),$}let s;const r=new Ue;for(const i of this._def.checks)i.kind==="int"?Q.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:k.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Sv(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_finite,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,s,r){return new Rn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:L.toString(r)}]})}_addCheck(e){return new Rn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Q.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Rn.create=t=>new Rn({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...z(t)});class hs extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let s;const r=new Ue;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return O(n,{code:k.invalid_type,expected:R.bigint,received:n.parsedType}),$}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,s,r){return new hs({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:L.toString(r)}]})}_addCheck(e){return new hs({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}hs.create=t=>new hs({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...z(t)});class ji extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.boolean,received:s.parsedType}),$}return st(e.data)}}ji.create=t=>new ji({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...z(t)});class er extends Z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.date,received:i.parsedType}),$}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_date}),$}const s=new Ue;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):Q.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new er({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}er.create=t=>new er({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...z(t)});class bc extends Z{_parse(e){if(this._getType(e)!==R.symbol){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.symbol,received:s.parsedType}),$}return st(e.data)}}bc.create=t=>new bc({typeName:P.ZodSymbol,...z(t)});class Fi extends Z{_parse(e){if(this._getType(e)!==R.undefined){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.undefined,received:s.parsedType}),$}return st(e.data)}}Fi.create=t=>new Fi({typeName:P.ZodUndefined,...z(t)});class tr extends Z{_parse(e){if(this._getType(e)!==R.null){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.null,received:s.parsedType}),$}return st(e.data)}}tr.create=t=>new tr({typeName:P.ZodNull,...z(t)});class vc extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}}vc.create=t=>new vc({typeName:P.ZodAny,...z(t)});class qi extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}}qi.create=t=>new qi({typeName:P.ZodUnknown,...z(t)});class Zt extends Z{_parse(e){const n=this._getOrReturnCtx(e);return O(n,{code:k.invalid_type,expected:R.never,received:n.parsedType}),$}}Zt.create=t=>new Zt({typeName:P.ZodNever,...z(t)});class wc extends Z{_parse(e){if(this._getType(e)!==R.undefined){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.void,received:s.parsedType}),$}return st(e.data)}}wc.create=t=>new wc({typeName:P.ZodVoid,...z(t)});class gt extends Z{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==R.array)return O(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),$;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(O(n,{code:o?k.too_big:k.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(O(n,{code:k.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(O(n,{code:k.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new St(n,o,n.path,a)))).then(o=>Ue.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new St(n,o,n.path,a)));return Ue.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new gt({...this._def,minLength:{value:e,message:L.toString(n)}})}max(e,n){return new gt({...this._def,maxLength:{value:e,message:L.toString(n)}})}length(e,n){return new gt({...this._def,exactLength:{value:e,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}}gt.create=(t,e)=>new gt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...z(e)});function kn(t){if(t instanceof Se){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=Nt.create(kn(s))}return new Se({...t._def,shape:()=>e})}else return t instanceof gt?new gt({...t._def,type:kn(t.element)}):t instanceof Nt?Nt.create(kn(t.unwrap())):t instanceof fn?fn.create(kn(t.unwrap())):t instanceof un?un.create(t.items.map(e=>kn(e))):t}class Se extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Q.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==R.object){const u=this._getOrReturnCtx(e);return O(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),$}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Zt&&this._def.unknownKeys==="strip"))for(const u in r.data)o.includes(u)||a.push(u);const c=[];for(const u of o){const l=i[u],d=r.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new St(r,d,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Zt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:r.data[l]}});else if(u==="strict")a.length>0&&(O(r,{code:k.unrecognized_keys,keys:a}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of a){const d=r.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new St(r,d,r.path,l)),alwaysSet:l in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Ue.mergeObjectSync(s,u)):Ue.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new Se({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:L.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new Se({...this._def,unknownKeys:"strip"})}passthrough(){return new Se({...this._def,unknownKeys:"passthrough"})}extend(e){return new Se({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Se({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Se({...this._def,catchall:e})}pick(e){const n={};for(const s of Q.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new Se({...this._def,shape:()=>n})}omit(e){const n={};for(const s of Q.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new Se({...this._def,shape:()=>n})}deepPartial(){return kn(this)}partial(e){const n={};for(const s of Q.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new Se({...this._def,shape:()=>n})}required(e){const n={};for(const s of Q.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Nt;)i=i._def.innerType;n[s]=i}return new Se({...this._def,shape:()=>n})}keyof(){return ed(Q.objectKeys(this.shape))}}Se.create=(t,e)=>new Se({shape:()=>t,unknownKeys:"strip",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});Se.strictCreate=(t,e)=>new Se({shape:()=>t,unknownKeys:"strict",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});Se.lazycreate=(t,e)=>new Se({shape:t,unknownKeys:"strip",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});class nr extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Dt(a.ctx.common.issues));return O(n,{code:k.invalid_union,unionErrors:o}),$}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const c of s){const u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new Dt(c));return O(n,{code:k.invalid_union,unionErrors:a}),$}}get options(){return this._def.options}}nr.create=(t,e)=>new nr({options:t,typeName:P.ZodUnion,...z(e)});const _t=t=>t instanceof Bi?_t(t.schema):t instanceof dn?_t(t.innerType()):t instanceof ir?[t.value]:t instanceof ln?t.options:t instanceof zi?Q.objectValues(t.enum):t instanceof ar?_t(t._def.innerType):t instanceof Fi?[void 0]:t instanceof tr?[null]:t instanceof Nt?[void 0,..._t(t.unwrap())]:t instanceof fn?[null,..._t(t.unwrap())]:t instanceof td||t instanceof ur?_t(t.unwrap()):t instanceof cr?_t(t._def.innerType):[];class $o extends Z{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return O(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),$;const s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(O(n,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),$)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,s){const r=new Map;for(const i of n){const o=_t(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new $o({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:r,...z(s)})}}function Ui(t,e){const n=Ut(t),s=Ut(e);if(t===e)return{valid:!0,data:t};if(n===R.object&&s===R.object){const r=Q.objectKeys(e),i=Q.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const c=Ui(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(n===R.array&&s===R.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],c=Ui(o,a);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return n===R.date&&s===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class sr extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(mc(i)||mc(o))return $;const a=Ui(i.value,o.value);return a.valid?((gc(i)||gc(o))&&n.dirty(),{status:n.value,value:a.data}):(O(s,{code:k.invalid_intersection_types}),$)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}sr.create=(t,e,n)=>new sr({left:t,right:e,typeName:P.ZodIntersection,...z(n)});class un extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.array)return O(s,{code:k.invalid_type,expected:R.array,received:s.parsedType}),$;if(s.data.length<this._def.items.length)return O(s,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$;!this._def.rest&&s.data.length>this._def.items.length&&(O(s,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new St(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ue.mergeArray(n,o)):Ue.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new un({...this._def,rest:e})}}un.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new un({items:t,typeName:P.ZodTuple,rest:null,...z(e)})};class rr extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.object)return O(s,{code:k.invalid_type,expected:R.object,received:s.parsedType}),$;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new St(s,a,s.path,a)),value:o._parse(new St(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ue.mergeObjectAsync(n,r):Ue.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof Z?new rr({keyType:e,valueType:n,typeName:P.ZodRecord,...z(s)}):new rr({keyType:Ot.create(),valueType:e,typeName:P.ZodRecord,...z(n)})}}class Sc extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.map)return O(s,{code:k.invalid_type,expected:R.map,received:s.parsedType}),$;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],u)=>({key:r._parse(new St(s,a,s.path,[u,"key"])),value:i._parse(new St(s,c,s.path,[u,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return $;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of o){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return $;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}}Sc.create=(t,e,n)=>new Sc({valueType:e,keyType:t,typeName:P.ZodMap,...z(n)});class ps extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.set)return O(s,{code:k.invalid_type,expected:R.set,received:s.parsedType}),$;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(O(s,{code:k.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(O(s,{code:k.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(c){const u=new Set;for(const l of c){if(l.status==="aborted")return $;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const a=[...s.data.values()].map((c,u)=>i._parse(new St(s,c,s.path,u)));return s.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,n){return new ps({...this._def,minSize:{value:e,message:L.toString(n)}})}max(e,n){return new ps({...this._def,maxSize:{value:e,message:L.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}ps.create=(t,e)=>new ps({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...z(e)});class Bi extends Z{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bi.create=(t,e)=>new Bi({getter:t,typeName:P.ZodLazy,...z(e)});class ir extends Z{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return O(n,{received:n.data,code:k.invalid_literal,expected:this._def.value}),$}return{status:"valid",value:e.data}}get value(){return this._def.value}}ir.create=(t,e)=>new ir({value:t,typeName:P.ZodLiteral,...z(e)});function ed(t,e){return new ln({values:t,typeName:P.ZodEnum,...z(e)})}class ln extends Z{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return O(n,{expected:Q.joinValues(s),received:n.parsedType,code:k.invalid_type}),$}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return O(n,{received:n.data,code:k.invalid_enum_value,options:s}),$}return st(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return ln.create(e,{...this._def,...n})}exclude(e,n=this._def){return ln.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}ln.create=ed;class zi extends Z{_parse(e){const n=Q.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==R.string&&s.parsedType!==R.number){const r=Q.objectValues(n);return O(s,{expected:Q.joinValues(r),received:s.parsedType,code:k.invalid_type}),$}if(this._cache||(this._cache=new Set(Q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=Q.objectValues(n);return O(s,{received:s.data,code:k.invalid_enum_value,options:r}),$}return st(e.data)}get enum(){return this._def.values}}zi.create=(t,e)=>new zi({values:t,typeName:P.ZodNativeEnum,...z(e)});class or extends Z{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==R.promise&&n.common.async===!1)return O(n,{code:k.invalid_type,expected:R.promise,received:n.parsedType}),$;const s=n.parsedType===R.promise?n.data:Promise.resolve(n.data);return st(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}or.create=(t,e)=>new or({type:t,typeName:P.ZodPromise,...z(e)});class dn extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{O(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return $;const c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?$:c.status==="dirty"||n.value==="dirty"?Yn(c.value):c});{if(n.value==="aborted")return $;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?$:a.status==="dirty"||n.value==="dirty"?Yn(a.value):a}}if(r.type==="refinement"){const o=a=>{const c=r.refinement(a,i);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?$:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?$:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Tn(o))return $;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Tn(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):$);Q.assertNever(r)}}dn.create=(t,e,n)=>new dn({schema:t,typeName:P.ZodEffects,effect:e,...z(n)});dn.createWithPreprocess=(t,e,n)=>new dn({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...z(n)});class Nt extends Z{_parse(e){return this._getType(e)===R.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Nt.create=(t,e)=>new Nt({innerType:t,typeName:P.ZodOptional,...z(e)});class fn extends Z{_parse(e){return this._getType(e)===R.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fn.create=(t,e)=>new fn({innerType:t,typeName:P.ZodNullable,...z(e)});class ar extends Z{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===R.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}ar.create=(t,e)=>new ar({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...z(e)});class cr extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Xs(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Dt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Dt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}cr.create=(t,e)=>new cr({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...z(e)});class Ac extends Z{_parse(e){if(this._getType(e)!==R.nan){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.nan,received:s.parsedType}),$}return{status:"valid",value:e.data}}}Ac.create=t=>new Ac({typeName:P.ZodNaN,...z(t)});class td extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Po extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?$:i.status==="dirty"?(n.dirty(),Yn(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?$:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Po({in:e,out:n,typeName:P.ZodPipeline})}}class ur extends Z{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Tn(r)&&(r.value=Object.freeze(r.value)),r);return Xs(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}ur.create=(t,e)=>new ur({innerType:t,typeName:P.ZodReadonly,...z(e)});var P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));const yt=Ot.create,Wi=Rn.create,Rr=ji.create,nd=tr.create,ms=qi.create;Zt.create;const jo=gt.create,pt=Se.create,_s=nr.create,Av=$o.create;sr.create;un.create;const gs=rr.create,Ms=ir.create,lr=ln.create;or.create;Nt.create;fn.create;const kv=["get","list","create","update","delete"],Ev=pt({uid:yt(),token:gs(ms()).optional()}),Iv=pt({function:lr(["get","exists"]).describe("Firestore function to mock"),path:yt().describe('Document path, e.g. "users/alice"'),result:_s([gs(ms()),Rr()]).describe("Document data for get, boolean for exists")}),_v=Av("kind",[pt({kind:Ms("create")}),pt({kind:Ms("set"),merge:Rr()}),pt({kind:Ms("update")}),pt({kind:Ms("delete")})]),kc=_s([yt(),Wi(),Rr(),nd()]),xv=pt({field:yt(),op:yt(),value:_s([kc,jo(kc)])}),Cv=pt({where:jo(xv).optional(),limit:Wi().optional(),offset:Wi().optional(),orderBy:yt().optional()});pt({description:yt().describe("Human-readable description of what this test verifies"),expectation:lr(["ALLOW","DENY"]).describe("Expected outcome"),method:lr(kv).describe("Firestore method to test"),path:yt().describe('Document path, e.g. "users/alice"'),auth:_s([Ev,nd()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:gs(ms()).optional().describe("request.resource.data for write operations"),resource:gs(ms()).optional().describe("Existing document data (resource.data)"),functionMocks:jo(Iv).optional().describe("Mock get()/exists() calls in rules"),query:Cv.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:yt().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:_v.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Jt(t){if(t.decision==="UNSUPPORTED")return;const n=t.decision==="ALLOW";let s="deny",r;if(n)s="allow",r=t.trace.find(b=>b.verdict==="ALLOW");else if(t.resourceLimit!==void 0&&t.trace.length>0)s="deny",r=t.trace[t.trace.length-1];else if(s="deny",r=t.trace.find(y=>y.verdict==="DENY"?!0:y.verdict==="ERROR"),r===void 0){const y=t.trace.length;y>0&&(r=t.trace[y-1])}if(r===void 0)return;const o={verdict:s};r.line!==void 0&&(o.line=r.line),r.col!==void 0&&(o.col=r.col,o.column=r.col),r.column!==void 0&&(o.col=r.column,o.column=r.column),r.file!==void 0&&(o.file=r.file),r.citation!==void 0&&(o.citation=r.citation),r.conditionText!==void 0&&(o.expression=r.conditionText),r.expressionTrace!==void 0&&(o.expressionTrace=r.expressionTrace);const h=o.line!==void 0,m=o.expression!==void 0,g=o.expressionTrace!==void 0;if(h||m||g)return o}function Ee(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const s=n.operations.join(","),r=`Rule #${n.ruleIndex} (${s})`;n.verdict==="ALLOW"?e.push(`${r} → ALLOW`):n.verdict==="DENY"?e.push(`${r} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${r} → unsupported: ${n.message??""}`):e.push(`${r} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}pt({function:lr(["get","exists"]).describe("Cross-service Firestore function to mock"),path:yt().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:_s([gs(ms()),Rr()]).describe("Document fields for get, boolean for exists")});const Ov=new TextEncoder;function Bs(t){try{const e=JSON.stringify(t);return typeof Buffer=="function"?Buffer.byteLength(e):Ov.encode(e).byteLength}catch{return 1/0}}class Tv{entries=new Set;record(e){const n=e.event;if(!(n.kind==="request"&&n.rulesEvidence!==void 0)||(this.entries.add(e),this.entries.size<=64))return;const o=this.entries.values().next().value;return o!==void 0&&this.entries.delete(o),o}forget(e){this.entries.delete(e)}clear(){this.entries.clear()}}class Rv{limits;entries=[];bytes=0;liveCount=0;liveBytes=0;activeRequests=new Map;completedRequests=new Set;activeListeners=new Map;retainedIds=new Set;rulesEvidence=new Tv;sourceGapCount=0;gap;constructor(e){this.limits=e}get length(){return this.snapshot().length}append(e){const n=e.kind==="operation"?e.observation:void 0,s=this.limits!==void 0,r=s?Bs(e)+1:0;if(n?.status==="pending"){if(this.completedRequests.has(n.id))return;const u=this.activeRequests.get(n.id);u&&this.releaseLive(u);const l={event:e,bytes:r};this.activeRequests.set(n.id,l),this.reserveLive(l),this.prune();return}if(n){const u=this.activeRequests.get(n.id);u&&this.releaseLive(u),this.activeRequests.delete(n.id),this.completedRequests.add(n.id)}if(this.trackListener(e,r),this.retainedIds.has(e.id))return;this.retainedIds.add(e.id);const i="listenerId"in e?this.activeListeners.get(e.listenerId):void 0;i?.event.id===e.id&&this.releaseLive(i);const a=s&&e.kind==="observation_gap"&&e.reason==="history-limit";if(a||!Number.isFinite(r))if(this.forgetId(e),a){const u=Math.max(0,e.omittedCount-this.sourceGapCount);this.sourceGapCount=Math.max(this.sourceGapCount,e.omittedCount),u&&this.omit({...e,omittedCount:u})}else this.omit(e);else{const u={event:e,bytes:r};this.entries.push(u),this.bytes+=r;const l=this.rulesEvidence.record(u);l!==void 0&&this.expireRulesEvidence(l)}this.prune()}snapshot(){const e=[...this.entries.map(r=>r.event),...[...this.activeRequests.values()].map(r=>r.event),...[...this.activeListeners.values()].map(r=>r.event).filter(r=>!this.retainedIds.has(r.id))],n=this.gap;return n!==void 0?[{...n},...e]:e}clear(){this.entries=[],this.activeRequests.clear(),this.activeListeners.clear(),this.completedRequests.clear(),this.retainedIds.clear(),this.rulesEvidence.clear(),this.bytes=0,this.liveCount=0,this.liveBytes=0,this.gap=void 0,this.sourceGapCount=0}forgetId(e){this.retainedIds.delete(e.id);const n="listenerId"in e?this.activeListeners.get(e.listenerId):void 0;n?.event.id===e.id&&this.reserveLive(n);const r=e.kind==="operation"?e.observation:void 0;r&&this.completedRequests.delete(r.id)}trackListener(e,n){if(!("listenerId"in e))return;const s=e.kind==="listener_attach"||e.kind==="listener"&&e.phase==="attach",r=e.kind==="listener_detach"||e.kind==="listener_errored"||e.kind==="listener"&&(e.phase==="detach"||e.phase==="errored");if(!(s||r))return;const o=this.activeListeners.get(e.listenerId),a=o!==void 0&&!this.retainedIds.has(o.event.id);if(a&&this.releaseLive(o),s){const c={event:e,bytes:n};this.activeListeners.set(e.listenerId,c),!this.retainedIds.has(e.id)&&this.reserveLive(c)}else this.activeListeners.delete(e.listenerId);a&&this.omit(o.event)}expireRulesEvidence(e){const n=e.event;if(n.kind!=="request")return;const{rulesEvidence:r,...i}=n;e.event={...i,rulesEvidenceExpired:!0};const a=this.limits!==void 0?Bs(e.event)+1:0;this.bytes+=a-e.bytes,e.bytes=a}reserveLive(e){this.liveCount++,this.liveBytes+=e.bytes}releaseLive(e){this.liveCount--,this.liveBytes-=e.bytes}prune(){let e=this.exceedsLimits();for(;e;){const n=this.entries.shift();if(n===void 0)break;this.forgetId(n.event),this.rulesEvidence.forget(n),this.bytes-=n.bytes,this.omit(n.event),e=this.exceedsLimits()}}exceedsLimits(){const e=this.limits;if(e===void 0)return!1;const r=this.gap===void 0?0:Bs(this.gap)+1,i=Math.min(this.liveCount,Math.floor(e.maxEvents/2)),o=Math.min(this.liveBytes,Math.floor(e.maxBytes/2)),c=this.entries.length+i>e.maxEvents,u=this.bytes+o+r+2>e.maxBytes;return c||u}omit(e){if(("listenerId"in e?this.activeListeners.get(e.listenerId):void 0)?.event.id===e.id)return;const r=e.kind==="observation_gap",i=r?e.omittedCount:1,o=r?e.firstEventId:e.id,a=r?e.lastEventId:e.id;this.gap={kind:"observation_gap",reason:"history-limit",id:"history-gap",at:this.gap?.at??e.at,firstEventId:this.gap?.firstEventId??o,lastEventId:a,omittedCount:(this.gap?.omittedCount??0)+i}}}function Lv(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const Nv={name:"date-to-timestamp",convert(t){return t instanceof Date?ve.fromMillis(t.getTime()):Ye}},Mv={name:"server-timestamp-sentinel",convert(t,e){return Lv(t)?e.serverTime instanceof ve?e.serverTime:ve.fromMillis(Date.now()):Ye}};function Dv(t){if(t===null||typeof t!="object"||t instanceof ve)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const $v={name:"user-timestamp-to-rules-timestamp",convert(t){if(t instanceof ve){const s=Math.floor(t.nanos/1e3)*1e3;return s===t.nanos?Ye:new ve(t.seconds,s)}if(Dv(t)){const s=Math.floor(t.nanoseconds/1e3)*1e3;return new ve(t.seconds,s)}return Ye}};function Ec(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Vi(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ic(t){if(typeof t!="object"||t===null||Vi(t))return;const e=t;if(typeof e.seconds=="number"){const n=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof n=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:n}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function ft(t,e){if(Object.is(t,e))return!0;const n=Ic(t),s=Ic(e);if(n!==void 0||s!==void 0){if(n===void 0||s===void 0||n.kind!==s.kind)return!1;switch(n.kind){case"timestamp":return s.kind==="timestamp"&&n.seconds===s.seconds&&n.nanoseconds===s.nanoseconds;case"bytes":return s.kind==="bytes"&&n.values.length===s.values.length&&n.values.every((o,a)=>o===s.values[a]);case"vector":return s.kind==="vector"&&n.values.length===s.values.length&&n.values.every((o,a)=>o===s.values[a]);case"geo-point":return s.kind==="geo-point"&&n.latitude===s.latitude&&n.longitude===s.longitude;case"reference":return s.kind==="reference"&&n.path===s.path}}if(Ec(t))return t.isEqual(e);if(Ec(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,a)=>ft(o,e[a]));if(!Vi(t)||!Vi(e))return!1;const r=Object.keys(t),i=Object.keys(e);return r.length!==i.length?!1:r.every(o=>o in e&&ft(t[o],e[o]))}function Pv(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function jv(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function Fv(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function qv(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Fo(t){if(t.prior===null)return;let e=t.prior;for(const n of t.fieldSegments){if(typeof n=="number"){if(!Array.isArray(e))return;e=e[n];continue}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,n))return;e=e[n]}return e}const Uv={name:"increment-sentinel",convert(t,e){if(!Pv(t))return Ye;const n=Fo(e);return(typeof n=="number"?n:0)+t.value}},Bv={name:"array-union-sentinel",convert(t,e){if(!jv(t))return Ye;const n=Fo(e),s=Array.isArray(n)?n.slice():[];for(const r of t.values)s.some(o=>ft(o,r))||s.push(r);return s}},zv={name:"array-remove-sentinel",convert(t,e){if(!Fv(t))return Ye;const n=Fo(e);return Array.isArray(n)?n.filter(s=>!t.values.some(r=>ft(s,r))):[]}},Wv={name:"delete-field-sentinel",convert(t){return qv(t)?bt:Ye}},_c=Symbol.for("pyric.firestore.query-value-registry"),xc=globalThis,ys=xc[_c]??(xc[_c]=new WeakMap),Cc=Symbol.for("pyric.firestore.query-value-execution-registry"),Oc=globalThis,dr=Oc[Cc]??(Oc[Cc]=new WeakMap),Tc=Symbol.for("pyric.firestore.query-value-owner-registry"),Rc=globalThis,fr=Rc[Tc]??(Rc[Tc]=new WeakMap);function Dn(t,e,n=()=>t){ys.set(t,e),dr.set(t,n)}function Vv(t){return ys.get(t)}function z0(t){return fr.get(t)}function W0(t){return dr.get(t)?.()??t}function V0(t,e){const n=ys.get(t),s=dr.get(t);n!==void 0&&ys.set(e,n),s!==void 0&&dr.set(e,s);const r=fr.get(t);r!==void 0&&fr.set(e,r)}const Gi=Symbol.for("pyric.firestore.reference-query-value");class Gv{path;[Gi]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Gi in e&&e.path===this.path}}function qo(t){const e=ys.get(t);if(typeof e!="object"||e===null||!(Gi in e))return;const n=e.path;return typeof n=="string"?n:void 0}function Hv(t,e,n,s=t){Dn(t,new Gv(e),()=>s),n!==void 0&&fr.set(t,n)}function Kv(t){if(t===null||typeof t!="object"||t instanceof wt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const Zv={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=qo(t);if(e!==void 0)return new wt(e)}return Kv(t)?new wt(t.path):Ye}};function Jv(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Qv(t){if(t===null||typeof t!="object"||t instanceof Ht)return null;const e=t;return Jv(e._values)&&typeof e.toArray=="function"?e._values:null}const Yv={name:"vector-value",convert(t){const e=Qv(t);return e===null?Ye:new Ht(e)}};function Xv(t){if(t===null||typeof t!="object"||t instanceof He)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function ew(t){if(t===null||typeof t!="object"||t instanceof ut)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const tw={name:"fb-bytes-to-rules-bytes",convert(t){return Xv(t)?new He(t.toUint8Array()):Ye}},nw={name:"fb-geopoint-to-rules-latlng",convert(t){return ew(t)?new ut(t.latitude,t.longitude):Ye}};function rt(t){if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}class At extends Error{code;customData;name="FirebaseError";constructor(e,n,s){super(n),this.code=e,this.customData=s,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(At,"name",{value:"FirebaseError"});function sw(t){return t.length===0||/[.`\\]/.test(t)}function sd(t){return t.map(e=>sw(e)?`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``:e).join(".")}function Lr(t){if(!t.includes("`"))return t.split(".");const e=[];let n="",s=!1;for(let r=0;r<t.length;r++){const i=t[r];if(s){i==="\\"&&r+1<t.length?n+=t[++r]:i==="`"?s=!1:n+=i;continue}i==="`"?s=!0:i==="."?(e.push(n),n=""):n+=i}return e.push(n),e}function G0(t){const e={};for(const n of t)e[sd(n.path)]=n.value;return e}function Lc(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}function rw(t){const e={};for(const[n,s]of Object.entries(t)){const r=Lr(n);let i=e;for(const o of r.slice(0,-1)){const a=Object.hasOwn(i,o)?i[o]:void 0;rt(a)||Lc(i,o,{}),i=i[o]}Lc(i,r[r.length-1],s)}return e}function iw(t){return Object.keys(t).map(Lr)}function ow(t){return t.method==="update"&&(t.merge===void 0||t.merge===!1)}function Xn(t,e){return ow(t)?{resourceData:rw(e),updateMask:iw(e)}:{resourceData:e}}function Uo(t){if(typeof t!="object"||t===null)return;const n=t._internalPath?.segments;if(Array.isArray(n)&&n.every(r=>typeof r=="string"))return[...n]}function rd(t){return typeof t=="string"||Uo(t)!==void 0}const aw=/[~*/[\]]/,cw=/^[_a-zA-Z][_a-zA-Z0-9]*$/;function id(t){return t.map(e=>{const n=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`");return cw.test(n)?n:`\`${n}\``}).join(".")}function hr(t,e,n,s){if(n===void 0){const r=s!==void 0&&s.length>0?` in field ${id(s)}`:"";throw new At("invalid-argument",`Function ${t}() called with invalid data. Unsupported field value: undefined (found${r} in document ${e})`)}if(Array.isArray(n)){for(const r of n)hr(t,e,r,void 0);return}if(rt(n))for(const[r,i]of Object.entries(n))hr(t,e,i,s===void 0?void 0:[...s,r])}function pr(t,e,n){const s=n===void 0?"":` (found in document ${n})`;return new At("invalid-argument",`Function ${t}() called with invalid data. ${e}${s}`)}function od(t,e,n){if(aw.test(e))throw pr(t,`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n);const s=e.split(".");if(s.some(r=>r.length===0))throw pr(t,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n);return s}function Nc(t,e,n){const s=Uo(e);if(s!==void 0)return s;if(typeof e=="string")return od(t,e);throw pr(t,"Field path arguments must be of type string or ",n)}function H0(t,e,n,s){if(!rd(n)){if(!rt(n))throw pr(t,"Data must be an object, but it was: "+uw(n),e);return Object.entries(n).map(([c,u])=>{const l=od(t,c,e);return hr(t,e,u,l),{path:l,value:u}})}const[r,...i]=s,o=[{path:Nc(t,n,e),value:r}];if(i.length%2!==0)throw new At("invalid-argument",`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let c=0;c<i.length;c+=2)o.push({path:Nc(t,i[c]),value:i[c+1]});const a=[];for(let c=o.length-1;c>=0;c--){const u=sd(o[c].path);a.includes(u)||(a.push(u),hr(t,e,o[c].value,o[c].path))}return o}function uw(t){return t===void 0?"undefined":t===null?"null":typeof t=="string"?`"${t.length>20?`${t.substring(0,20)}...`:t}"`:typeof t=="object"?Array.isArray(t)?"an array":"a custom object":typeof t=="function"?"a function":String(t)}const Ye=Symbol("value-resolver:KEEP"),bt=Symbol("value-resolver:DELETE_MARKER"),Hi=[];function it(t){Hi.some(e=>e.name===t.name)||Hi.push(t)}function ht(t,e){const n={},s=e.method==="update";for(const[r,i]of Object.entries(t)){const o=s?Lr(r):[r];n[r]=Ki(i,{...e,fieldPath:r,fieldSegments:o})}return n}function Ki(t,e){for(const n of Hi){const s=n.convert(t,e);if(s!==Ye)return s}if(Array.isArray(t))return t.map((n,s)=>Ki(n,{...e,fieldPath:`${e.fieldPath}[${s}]`,fieldSegments:[...e.fieldSegments,s]}));if(rt(t)){const n={};for(const[s,r]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${s}`:s;n[s]=Ki(r,{...e,fieldPath:i,fieldSegments:[...e.fieldSegments,s]})}return n}return t}function rn(t){const e={},n=[];for(const[s,r]of Object.entries(t)){if(r===bt){n.push(s);continue}e[s]=mr(r)}return{writes:e,deletedKeys:n}}function mr(t){if(t!==bt){if(Array.isArray(t))return t.filter(e=>e!==bt).map(mr);if(rt(t)){const e={};for(const[n,s]of Object.entries(t))s!==bt&&(e[n]=mr(s));return e}return t}}function lw(){it(Nv),it(Mv),it($v),it(Uv),it(Bv),it(zv),it(Wv),it(Zv),it(Yv),it(tw),it(nw)}const Mc=Symbol.for("pyric.firestore.activity-value-registry"),Dc=globalThis,ad=Dc[Mc]??(Dc[Mc]=new WeakMap);function cd(){let t=2166136261,e=2654435769,n=2246822507,s=3266489909;const r=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),n=Math.imul(n^i,3266489909),s=Math.imul(s^i,668265263)};return{update:i=>{if(typeof i=="string")for(let o=0;o<i.length;o+=1){const a=i.charCodeAt(o);r(a&255),r(a>>>8)}else for(const o of i)r(o)},finish:()=>[t,e,n,s].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Bo(...t){const e=cd();for(const n of t)e.update(n);return e.finish()}function dw(t){return{type:"string-digest",length:t.length,digest:Bo("string\0",t)}}function gr(t,...e){return{type:`${t}-digest`,digest:Bo(`${t}\0`,...e)}}function fw(t){return{type:"bytes-digest",length:t.byteLength,digest:Bo("bytes\0",t)}}function $c(t){const e=cd(),n=(...r)=>{for(const i of r)e.update(i)},s=r=>{if(r===null){n("null;");return}switch(typeof r){case"string":n(`s${r.length}:`,r,";");return;case"number":n(`n${Object.is(r,-0)?"-0":String(r)};`);return;case"boolean":n(r?"b1;":"b0;");return;case"undefined":n("u;");return;case"bigint":n(`i${r.toString()};`);return;case"object":break;default:n(`x${typeof r};`);return}if(Array.isArray(r)){n(`a${r.length}[`);for(const a of r)s(a);n("];");return}const i=r,o=Object.keys(i).sort();n(`o${o.length}{`);for(const a of o)n(`k${a.length}:`,a,"="),s(i[a]);n("};")};return s(t),{type:"wire-value-digest",digest:e.finish()}}function bs(t,e){ad.set(t,e)}function hw(t){return ad.get(t)}const Pc=-62135596800,pw=253402300800;class mt{seconds;nanoseconds;constructor(e,n){if(this.seconds=e,this.nanoseconds=n,n<0||n>=1e9)throw new At("invalid-argument",`Timestamp nanoseconds out of range: ${n}`);if(e<Pc||e>=pw)throw new At("invalid-argument",`Timestamp seconds out of range: ${e}`);bs(this,gr("timestamp",String(e),"\0",String(n))),Dn(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:n}),()=>new mt(e,n))}static now(){return mt.fromMillis(Date.now())}static fromDate(e){return mt.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),s=Math.floor((e-n*1e3)*1e6);return new mt(n,s)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds-Pc,n=String(e).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function vs(t){const e={};for(const[n,s]of Object.entries(t))e[n]=ud(s);return e}function ud(t){return t instanceof Date?mt.fromDate(t).toDate():Array.isArray(t)?t.map(ud):rt(t)?qo(t)!==void 0?t:vs(t):t}function mw(t){return t.split(".")}const gw=new Set(["__proto__","prototype","constructor"]);function jc(t){if(gw.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function ld(t,e,n){let s=t;for(let i=0;i<e.length-1;i++){const o=e[i];jc(o);const a=Object.hasOwn(s,o)?s[o]:void 0;rt(a)||(s[o]={}),s=s[o]}const r=e[e.length-1];jc(r),n===bt?delete s[r]:s[r]=mr(n)}function Nr(t,e){const n=vs(t);for(const[s,r]of Object.entries(e)){if(r!==bt&&yr(r))throw new dd;ld(n,Lr(s),r)}return n}class dd extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function yr(t){return t===bt?!0:Array.isArray(t)?t.some(yr):rt(t)?Object.values(t).some(yr):!1}function yw(t){for(const e of Object.values(t))if(e!==bt&&yr(e))throw new dd}function Mr(t,e,n){const s=vs(t),r=[];if(n!==void 0)for(const o of n){const a=mw(o),c=bw(e,a);if(c===fd)throw new At("invalid-argument",`Field '${o}' is specified in your field mask but missing from your input data.`);r.push({segments:a,value:c})}else hd(e,[],r);for(const{segments:o,value:a}of r)ld(s,o,a);return s}const fd=Symbol("field-merge:ABSENT");function bw(t,e){let n=t;for(const s of e){if(!rt(n)||!Object.hasOwn(n,s))return fd;n=n[s]}return n}function hd(t,e,n){const s=Object.keys(t);if(s.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const r of s){const i=t[r],o=[...e,r];rt(i)&&i!==bt?hd(i,o,n):n.push({segments:o,value:i})}}function vw(t,e,n){const s=[],r=new Map;for(const[a,c]of e.entries()){const u=r.get(c.path)??t.has(c.path);switch(c.method){case"create":u&&s.push({index:a,error:`Document '${c.path}' already exists`}),r.set(c.path,!0);break;case"update":{!u&&s.push({index:a,error:`Document '${c.path}' does not exist`});break}case"delete":r.set(c.path,!1);break;case"set":r.set(c.path,!0);break}}if(s.length>0)return{success:!1,errors:s};const o=new Map;for(const a of e)if(!o.has(a.path)){const u=t.has(a.path);let l=null;u&&(l={...t.get(a.path)}),o.set(a.path,l)}for(const a of e){switch(a.method){case"create":{const c=ht({...a.data},{path:a.path,method:"create",prior:null}),{writes:u}=rn(c);t.set(a.path,u);break}case"update":{const c=t.get(a.path);if(c===void 0)throw new Error(`Validated document '${a.path}' disappeared during atomic application`);const l=ht({...a.data},{path:a.path,method:"update",prior:c});t.set(a.path,Nr(c,l));break}case"set":{const c=o.get(a.path)??null,u=ht({...a.data},{path:a.path,method:"set",prior:c}),{writes:l}=rn(u);t.set(a.path,l);break}case"delete":t.delete(a.path);break}n(a.path)}return{success:!0,priorStates:o}}function ww(t,e){if(e===void 0)throw new TypeError("Projection fields are not iterable");const s={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=t[r]);return s}class ri{onChange;documents;versions=new Map;nextVersion=1;constructor(e={},n,s){this.onChange=s,this.documents=n??new Map;for(const[r,i]of Object.entries(e)){const o=ht({...i},{path:r,method:"seed",prior:null}),{writes:a}=rn(o);this.documents.set(r,a),this.bumpVersion(r)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,n={}){const r=e===""||e.endsWith("/")?e:e+"/",i=!!n.projection;let o=d=>d;i&&(o=d=>ww(d,n.projection));const a=[],c=new Set,u=[];for(const[d,f]of this.documents){if(r!==""&&!d.startsWith(r))continue;if(!n.directOnly){a.push({path:d,data:o(f)});continue}const m=d.slice(r.length),g=m.indexOf("/");if(g===-1){a.push({path:d,data:o(f)}),c.add(m);continue}if(!!n.phantoms){const w=m.slice(0,g);w.length>0&&!u.includes(w)&&u.push(w)}}if(!!(n.directOnly&&n.phantoms))for(const d of u)c.has(d)||a.push({path:r+d,data:{},phantom:!0});return a}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const s of this.documents.keys()){const r=s.split("/",1)[0]??"";if(r.length===0)continue;!e.has(r)&&(e.add(r),n.push(r))}return n}listSubcollections(e){const s=e.endsWith("/")?e:e+"/",r=new Set,i=[];for(const o of this.documents.keys()){if(!o.startsWith(s))continue;const u=o.slice(s.length).split("/",1)[0]??"";if(u.length===0)continue;!r.has(u)&&(r.add(u),i.push(u))}return i}snapshot(){const e={};for(const[n,s]of this.documents)e[n]={...s};return e}size(){return this.documents.size}create(e,n){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let r;try{const i=ht({...n},{path:e,method:"create",prior:null});r=rn(i).writes}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,r),this.bumpVersion(e),{success:!0}}update(e,n){const s=this.documents.get(e);if(!s)return{success:!1,error:`Document '${e}' does not exist`};let i;try{const o=ht({...n},{path:e,method:"update",prior:s});i=Nr(s,o)}catch(o){return{success:!1,error:o.message}}return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:{...s}}}setMerge(e,n,s){const r=this.documents.has(e);let i=null;r&&(i={...this.documents.get(e)});const o=ht({...n},{path:e,method:"set",prior:i}),a=Mr(i??{},o,s);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:i,created:i===null}}set(e,n){const s=this.documents.has(e);let r=null;s&&(r={...this.documents.get(e)});const i=ht({...n},{path:e,method:"set",prior:r}),{writes:o}=rn(i);return this.documents.set(e,o),this.bumpVersion(e),{success:!0,priorData:r,created:r===null}}delete(e){const n=this.documents.get(e);return n?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...n}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){return vw(this.documents,e,n=>this.bumpVersion(n))}restore(e){const n=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[s,r]of Object.entries(e))this.documents.set(s,{...r});for(const s of n)this.bumpVersion(s)}restorePaths(e){for(const[n,s]of Object.entries(e))s===null?this.documents.delete(n):this.documents.set(n,{...s}),this.bumpVersion(n)}bumpVersion(e){this.versions.set(e,this.nextVersion++),this.onChange?.(e)}}class Sw{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let n=this.baseCache.get(e);return n===void 0&&(n=structuredClone(this.base[e]),this.baseCache.set(e,n)),n}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,n){this.overlay.set(e,n),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const n=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),n}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const n of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const n of Object.keys(this.base))this.tombstones.has(n)||(e.add(n),yield[n,this.overlay.has(n)?this.overlay.get(n):this.baseDoc(n)]);for(const[n,s]of this.overlay)e.has(n)||(yield[n,s])}}const Aw={maxEvents:1e4,maxBytes:8*1024*1024};class ct extends Error{code;denialContext;remediation;constructor(e,n,s){const r=typeof e=="object",i=r?e.code:e,o=r?e.message:n,a=r?e.denialContext:s,c=r?e.remediation:void 0,u=c!==void 0?`${o}
|
|
1708
|
+
`)}`}function hc(t){return/^[A-Za-z0-9_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function td(t){const e=ed(t.constraints),n=t.auth?{uid:t.auth.uid,...t.auth.token&&Object.keys(t.auth.token).length>0?{token:t.auth.token}:{}}:null,s={description:`list ${t.path}`,expectation:"ALLOW",method:"list",path:t.path,auth:n,...e?{query:e}:{}};return{command:["pyric rules simulate --service firestore --operation list",`--path ${hc(t.path)}`,...n?[`--uid ${hc(n.uid)}`]:[],...e?[`--query '${JSON.stringify(e).replace(/'/g,"'\\''")}'`]:[]].join(" "),testCase:s}}function Jb(t){const e=td(t);return["Reproduce with:",` ${e.command}`,` Fixture case: ${JSON.stringify(e.testCase)}`].join(`
|
|
1709
|
+
`)}class Qb{attempts=[];push(e){this.attempts.push(e)}}function Yb(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Xb(t){return t instanceof Ol?{kind:"expressions",limit:os,message:t.message,...t.position===void 0?{}:{line:t.position.line,column:t.position.column}}:{kind:"document-lookups",limit:Mi,message:t.message}}function ev(t,e,n,s){const r=Yb(e),i=[],o=[],a=[];for(let p=0;p<t.allows.length;p++){const h=t.allows[p];h.operations.some(g=>r.includes(g))&&a.push({rule:h,index:p})}if(a.length===0)return o.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:o};let u=!1;const l=n.trace,d=p=>{n.expressionBudget&&(p.evaluatedExpressions=n.expressionBudget.evaluated),i.push(p)};for(const{rule:p,index:h}of a){const m=tv(p,h,s),g=new my;n.trace=g;try{const b=fs(xe(p.condition,n),p.condition);if(m.expressionTrace=g.entries,b)return m.verdict="ALLOW",d(m),n.trace=l,{decision:"ALLOW",trace:i,notes:o};m.verdict="DENY",d(m)}catch(b){if(m.expressionTrace=g.entries,b instanceof cn){m.verdict="ERROR",m.message=b.message,d(m),n.trace=l;const v=Xb(b),E=v.line===void 0||v.column===void 0?void 0:{line:v.line,column:v.column},I=Cb(v.message,E);return o.push(`Request denied by a rules resource limit: ${I.endsWith(".")?I:`${I}.`} The limit is per request, so no other allow rule or match block was evaluated.`),{decision:"DENY",trace:i,notes:o,resourceLimit:v}}b instanceof Gt?(u=!0,m.verdict="UNSUPPORTED",m.message=b.message):(m.verdict="ERROR",b instanceof Error?m.message=b.message:m.message=String(b)),d(m)}}n.trace=l;let f="DENY";return u&&(f="UNSUPPORTED"),{decision:f,trace:i,notes:o}}function tv(t,e,n){const s=Ae(t.condition),r={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:s};if(t.loc!==void 0){const o=t.loc;if(r.line=o.line,r.col=o.col,r.column=o.col,o.file!==void 0?(r.file=o.file,r.citation=`${o.file}:${o.line}:${o.col}`):(r.file="firestore.rules",r.citation=`firestore.rules:${o.line}:${o.col}`),n!==void 0){const u=Il(n,o.line,o.col,o.file,s);u!==void 0&&(r.line=u.line,r.col=u.col,r.column=u.col,r.file=u.file,r.citation=u.citation,u.expression!==void 0&&(r.conditionText=u.expression))}}return r}function nv(t,e,n,s,r,i,o){const a=new Map;for(const I of e)a.set(I.name,I);const c=new Map,u=new Set,l=new Map;for(const I of t.functionMocks??[]){const j=Mn(I.path);I.function==="get"&&typeof I.result=="object"&&I.result!==null?(c.set(j,tt(I.result)),u.add(j)):I.function==="exists"&&l.set(j,I.result===!0)}const d=t.requestTime?ve.fromIsoString(t.requestTime):ve.fromMillis(Date.now()),p=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],h=new nt(p,n),m=tt(t.data??{}),g=t.resource===void 0||t.resource===null?null:tt(t.resource);let b,y;if(t.writeMode)b=Nb(t.writeMode,g,m),y=b!==null;else switch(t.method){case"create":case"update":b=m,y=!0;break;case"delete":b=null,y=!1;break;case"get":case"list":default:b=g,y=g!==null;break}const w=b!==null?tt(Li(b,d)):null;let v;t.method==="create"||t.method==="update"?v={data:w??{}}:t.data!==void 0&&(v={data:tt(Li(t.data,d))});const E={auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,method:t.method,path:h,...Ja(t)?{query:Ja(t)}:{},time:d};return v!==void 0&&(E.resource=v),{request:E,resource:t.method==="create"||g===null?null:{data:tt(g)},mockDocuments:c,identitylessFunctionMocks:u,existsMocks:l,getDoc:s,pathVariables:n,functions:a,database:"(default)",afterStatePath:h,afterState:w,existsAfter:y,...r?{batchProjection:r}:{},lookupBudget:i,expressionBudget:o}}class sv{simulate(e,n,s){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const r=pl(e);return r.ok?this.simulateParsed(r.ast,e,n,s):{success:!1,error:{code:"PARSE_FAILED",message:`Firestore ${r.rejection.message}`,recoverable:!0}}}simulateParsed(e,n,s,r){ub(e);const i=r?.sourceMap??_o(n),o=[];let a=0,c=0,u=0;const l={database:"(default)"};for(const d of e.service.match.path.segments)d.type==="wildcard"&&(l[d.name]="(default)");for(const d of s){const f=Db(d.path),p=f.split("/").filter(Boolean),h=d.method==="list",m=p.length%2===1;let g,b=e,y=d;if(h&&!r?.skipQueryProof){const ce=p.length===0?"__listPlaceholder__":m?`${f}/__listPlaceholder__`:f,Y=Zb(d.query),X=Yl(e,ce,d.auth??null,Y,n);if(X.kind==="no-rule")g={verdict:"NO_RULE",provable:!1,kind:"no-rule",failures:[]};else if(X.kind==="unprovable"){const be=X.failures.find(jt=>jt.kind!=="constraints-not-satisfied")??X.failures[0],ie=$i(be.residual);g={verdict:"UNPROVABLE",provable:!1,kind:be.kind,failures:X.failures,reason:be.reason,residual:be.residual,...ie?{remediation:ie}:{},...be.rule?{rule:{...be.rule,verdict:"deny"}}:{}}}else{let be=!1;if(X.failures.length>0){const ie=this.simulateParsed(X.evaluationAst,n,[{...d,path:ce,resource:X.syntheticResource,expectation:"ALLOW"}],{...r,sourceMap:i,skipQueryProof:!0});ie.success&&ie.data.results[0]?.decision!=="ALLOW"&&(be=!0)}if(be){const ie=X.failures.find(Cs=>Cs.kind!=="constraints-not-satisfied")??X.failures[0],jt=$i(ie.residual);g={verdict:"UNPROVABLE",provable:!1,kind:ie.kind,failures:X.failures,reason:ie.reason,residual:ie.residual,...jt?{remediation:jt}:{},...ie.rule?{rule:{...ie.rule,verdict:"deny"}}:{}}}else g={verdict:"PROVABLE",provable:!0,kind:"provable",failures:X.failures};d.resource===void 0&&(d.query?.where?.length??0)>0&&(b=X.evaluationAst,y={...d,resource:X.syntheticResource})}}const w=[...b.functions??[],...b.service.functions??[],...b.service.match.functions];let v=[];const E=new Qb;for(const ce of b.service.match.children)v.push(...ds(ce,p,w,E));let I=!1;if(h&&(m||v.length===0)){const ce=[...p,"__hypothetical_doc__"],Y=[];for(const be of b.service.match.children)Y.push(...ds(be,ce,w,E));Y.length>0&&(v=Y,I=!0)}const W={requestPath:f,attempts:E.attempts};if(v.length===0){const ce=d.expectation==="DENY"?"PASSED":"FAILED";ce==="PASSED"?a++:c++,o.push({description:d.description,expectation:d.expectation,state:ce,decision:"DENY",evaluatedExpressions:0,trace:[],notes:[`No match block found for path '${f}', so the request is denied by default.`,Mb],pathResolution:W,...g?{queryProof:g}:{}});continue}let T="DENY";const N=[],B=[];let G=!1,C,S,x=!1;const F=new Wl,D=new Ob((ce,Y)=>new Ol(ce,Y));for(const ce of v){const Y={...l,...ce.pathVariables},X=nv(y,ce.functions,Y,r?.getDoc,r?.batchProjection,F,D),be=Hl(ce.block),ie=ev(ce.block,d.method,X,i);for(const gn of ie.trace)gn.matchPath=be;if(N.push(...ie.trace),B.push(...ie.notes),ie.resourceLimit!==void 0){T="DENY",x=!0;const gn=N.slice(0,-1).find(Jo=>Jo.verdict==="ERROR");ie.resourceLimit.kind==="expressions"&&gn?B.push(`The request reached the limit (${ie.resourceLimit.message}) after an earlier allow rule raised an error; production reports that earlier error: ${gn.message??"evaluation error"}`):S=ie.resourceLimit;break}if(ie.decision==="ALLOW"){T="ALLOW",C=be;break}ie.decision==="UNSUPPORTED"&&(G=!0)}T!=="ALLOW"&&!x&&G&&(T="UNSUPPORTED"),T==="ALLOW"&&C!==void 0&&B.push(`Allowed by match block '${C}'`),I===!0&&B.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let Oe;T==="UNSUPPORTED"?(Oe="UNSUPPORTED",u++):T===d.expectation?(Oe="PASSED",a++):(Oe="FAILED",c++),o.push({description:d.description,expectation:d.expectation,state:Oe,decision:T,evaluatedExpressions:D.evaluated,...S?{resourceLimit:S}:{},...g?{queryProof:g}:{},trace:N,notes:B,pathResolution:W})}return{success:!0,data:{passed:a,failed:c,unsupported:u,results:o}}}}var Q;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(Q||(Q={}));var pc;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(pc||(pc={}));const R=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ut=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}},k=Q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Dt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let a=s,c=0;for(;c<o.path.length;){const u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return r(this),s}static assert(e){if(!(e instanceof Dt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}Dt.create=t=>new Dt(t);const Pi=(t,e)=>{let n;switch(t.code){case k.invalid_type:t.received===R.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Q.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:n=`Unrecognized key(s) in object: ${Q.joinValues(t.keys,", ")}`;break;case k.invalid_union:n="Invalid input";break;case k.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Q.joinValues(t.options)}`;break;case k.invalid_enum_value:n=`Invalid enum value. Expected ${Q.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:n="Invalid function arguments";break;case k.invalid_return_type:n="Invalid function return type";break;case k.invalid_date:n="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Q.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case k.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case k.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case k.custom:n="Invalid input";break;case k.invalid_intersection_types:n="Intersection results could not be merged";break;case k.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:n="Number must be finite";break;default:n=e.defaultError,Q.assertNever(t)}return{message:n}};let rv=Pi;function iv(){return rv}const ov=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const c=s.filter(u=>!!u).slice().reverse();for(const u of c)a=u(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function O(t,e){const n=iv(),s=ov({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Pi?void 0:Pi].filter(r=>!!r)});t.common.issues.push(s)}class Ue{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return $;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ue.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return $;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const $=Object.freeze({status:"aborted"}),Yn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),mc=t=>t.status==="aborted",gc=t=>t.status==="dirty",Tn=t=>t.status==="valid",Xs=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));class St{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const yc=(t,e)=>{if(Tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Dt(t.common.issues);return this._error=n,this._error}}};function z(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:r}}class Z{get description(){return this._def.description}_getType(e){return Ut(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ue,ctx:{common:e.parent.common,data:e.data,parsedType:Ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Xs(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)},r=this._parseSync({data:e,path:s.path,parent:s});return yc(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Tn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Tn(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ut(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Xs(r)?r:Promise.resolve(r));return yc(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:k.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new dn({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Nt.create(this,this._def)}nullable(){return fn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return or.create(this,this._def)}or(e){return nr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new dn({...z(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new ar({...z(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new id({typeName:P.ZodBranded,type:this,...z(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new cr({...z(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Po.create(this,e)}readonly(){return ur.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const av=/^c[^\s-]{8,}$/i,cv=/^[0-9a-z]+$/,uv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lv=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dv=/^[a-z0-9_-]{21}$/i,fv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hv=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,pv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let si;const gv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,vv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Av=new RegExp(`^${nd}$`);function sd(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function kv(t){return new RegExp(`^${sd(t)}$`)}function Ev(t){let e=`${nd}T${sd(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Iv(t,e){return!!((e==="v4"||!e)&&gv.test(t)||(e==="v6"||!e)&&bv.test(t))}function _v(t,e){if(!fv.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function xv(t,e){return!!((e==="v4"||!e)&&yv.test(t)||(e==="v6"||!e)&&vv.test(t))}class Ot extends Z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.string,received:i.parsedType}),$}const s=new Ue;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?O(r,{code:k.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&O(r,{code:k.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")pv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"email",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")si||(si=new RegExp(mv,"u")),si.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"emoji",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")lv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"uuid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")dv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"nanoid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")av.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cuid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")cv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cuid2",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")uv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"ulid",code:k.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),O(r,{validation:"url",code:k.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"regex",code:k.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Ev(i).test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Av.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?kv(i).test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:k.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?hv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"duration",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Iv(e.data,i.version)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"ip",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?_v(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"jwt",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?xv(e.data,i.version)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"cidr",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?wv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"base64",code:k.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Sv.test(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{validation:"base64url",code:k.invalid_string,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:k.invalid_string,...L.errToObj(s)})}_addCheck(e){return new Ot({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...L.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...L.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...L.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...L.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...L.errToObj(n)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Ot.create=t=>new Ot({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...z(t)});function Cv(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Rn extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.number,received:i.parsedType}),$}let s;const r=new Ue;for(const i of this._def.checks)i.kind==="int"?Q.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:k.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Cv(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_finite,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,s,r){return new Rn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:L.toString(r)}]})}_addCheck(e){return new Rn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Q.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Rn.create=t=>new Rn({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...z(t)});class hs extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let s;const r=new Ue;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),O(s,{code:k.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return O(n,{code:k.invalid_type,expected:R.bigint,received:n.parsedType}),$}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,s,r){return new hs({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:L.toString(r)}]})}_addCheck(e){return new hs({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}hs.create=t=>new hs({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...z(t)});class ji extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.boolean,received:s.parsedType}),$}return st(e.data)}}ji.create=t=>new ji({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...z(t)});class er extends Z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_type,expected:R.date,received:i.parsedType}),$}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return O(i,{code:k.invalid_date}),$}const s=new Ue;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),O(r,{code:k.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):Q.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new er({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}er.create=t=>new er({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...z(t)});class bc extends Z{_parse(e){if(this._getType(e)!==R.symbol){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.symbol,received:s.parsedType}),$}return st(e.data)}}bc.create=t=>new bc({typeName:P.ZodSymbol,...z(t)});class Fi extends Z{_parse(e){if(this._getType(e)!==R.undefined){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.undefined,received:s.parsedType}),$}return st(e.data)}}Fi.create=t=>new Fi({typeName:P.ZodUndefined,...z(t)});class tr extends Z{_parse(e){if(this._getType(e)!==R.null){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.null,received:s.parsedType}),$}return st(e.data)}}tr.create=t=>new tr({typeName:P.ZodNull,...z(t)});class vc extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}}vc.create=t=>new vc({typeName:P.ZodAny,...z(t)});class qi extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}}qi.create=t=>new qi({typeName:P.ZodUnknown,...z(t)});class Zt extends Z{_parse(e){const n=this._getOrReturnCtx(e);return O(n,{code:k.invalid_type,expected:R.never,received:n.parsedType}),$}}Zt.create=t=>new Zt({typeName:P.ZodNever,...z(t)});class wc extends Z{_parse(e){if(this._getType(e)!==R.undefined){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.void,received:s.parsedType}),$}return st(e.data)}}wc.create=t=>new wc({typeName:P.ZodVoid,...z(t)});class gt extends Z{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==R.array)return O(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),$;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(O(n,{code:o?k.too_big:k.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(O(n,{code:k.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(O(n,{code:k.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new St(n,o,n.path,a)))).then(o=>Ue.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new St(n,o,n.path,a)));return Ue.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new gt({...this._def,minLength:{value:e,message:L.toString(n)}})}max(e,n){return new gt({...this._def,maxLength:{value:e,message:L.toString(n)}})}length(e,n){return new gt({...this._def,exactLength:{value:e,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}}gt.create=(t,e)=>new gt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...z(e)});function kn(t){if(t instanceof Se){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=Nt.create(kn(s))}return new Se({...t._def,shape:()=>e})}else return t instanceof gt?new gt({...t._def,type:kn(t.element)}):t instanceof Nt?Nt.create(kn(t.unwrap())):t instanceof fn?fn.create(kn(t.unwrap())):t instanceof un?un.create(t.items.map(e=>kn(e))):t}class Se extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Q.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==R.object){const u=this._getOrReturnCtx(e);return O(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),$}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Zt&&this._def.unknownKeys==="strip"))for(const u in r.data)o.includes(u)||a.push(u);const c=[];for(const u of o){const l=i[u],d=r.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new St(r,d,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Zt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:r.data[l]}});else if(u==="strict")a.length>0&&(O(r,{code:k.unrecognized_keys,keys:a}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of a){const d=r.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new St(r,d,r.path,l)),alwaysSet:l in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Ue.mergeObjectSync(s,u)):Ue.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new Se({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:L.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new Se({...this._def,unknownKeys:"strip"})}passthrough(){return new Se({...this._def,unknownKeys:"passthrough"})}extend(e){return new Se({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Se({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Se({...this._def,catchall:e})}pick(e){const n={};for(const s of Q.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new Se({...this._def,shape:()=>n})}omit(e){const n={};for(const s of Q.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new Se({...this._def,shape:()=>n})}deepPartial(){return kn(this)}partial(e){const n={};for(const s of Q.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new Se({...this._def,shape:()=>n})}required(e){const n={};for(const s of Q.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Nt;)i=i._def.innerType;n[s]=i}return new Se({...this._def,shape:()=>n})}keyof(){return rd(Q.objectKeys(this.shape))}}Se.create=(t,e)=>new Se({shape:()=>t,unknownKeys:"strip",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});Se.strictCreate=(t,e)=>new Se({shape:()=>t,unknownKeys:"strict",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});Se.lazycreate=(t,e)=>new Se({shape:t,unknownKeys:"strip",catchall:Zt.create(),typeName:P.ZodObject,...z(e)});class nr extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Dt(a.ctx.common.issues));return O(n,{code:k.invalid_union,unionErrors:o}),$}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const c of s){const u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new Dt(c));return O(n,{code:k.invalid_union,unionErrors:a}),$}}get options(){return this._def.options}}nr.create=(t,e)=>new nr({options:t,typeName:P.ZodUnion,...z(e)});const _t=t=>t instanceof Bi?_t(t.schema):t instanceof dn?_t(t.innerType()):t instanceof ir?[t.value]:t instanceof ln?t.options:t instanceof zi?Q.objectValues(t.enum):t instanceof ar?_t(t._def.innerType):t instanceof Fi?[void 0]:t instanceof tr?[null]:t instanceof Nt?[void 0,..._t(t.unwrap())]:t instanceof fn?[null,..._t(t.unwrap())]:t instanceof id||t instanceof ur?_t(t.unwrap()):t instanceof cr?_t(t._def.innerType):[];class $o extends Z{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return O(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),$;const s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(O(n,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),$)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,s){const r=new Map;for(const i of n){const o=_t(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new $o({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:r,...z(s)})}}function Ui(t,e){const n=Ut(t),s=Ut(e);if(t===e)return{valid:!0,data:t};if(n===R.object&&s===R.object){const r=Q.objectKeys(e),i=Q.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const c=Ui(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(n===R.array&&s===R.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],c=Ui(o,a);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return n===R.date&&s===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class sr extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(mc(i)||mc(o))return $;const a=Ui(i.value,o.value);return a.valid?((gc(i)||gc(o))&&n.dirty(),{status:n.value,value:a.data}):(O(s,{code:k.invalid_intersection_types}),$)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}sr.create=(t,e,n)=>new sr({left:t,right:e,typeName:P.ZodIntersection,...z(n)});class un extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.array)return O(s,{code:k.invalid_type,expected:R.array,received:s.parsedType}),$;if(s.data.length<this._def.items.length)return O(s,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$;!this._def.rest&&s.data.length>this._def.items.length&&(O(s,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new St(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ue.mergeArray(n,o)):Ue.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new un({...this._def,rest:e})}}un.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new un({items:t,typeName:P.ZodTuple,rest:null,...z(e)})};class rr extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.object)return O(s,{code:k.invalid_type,expected:R.object,received:s.parsedType}),$;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new St(s,a,s.path,a)),value:o._parse(new St(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ue.mergeObjectAsync(n,r):Ue.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof Z?new rr({keyType:e,valueType:n,typeName:P.ZodRecord,...z(s)}):new rr({keyType:Ot.create(),valueType:e,typeName:P.ZodRecord,...z(n)})}}class Sc extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.map)return O(s,{code:k.invalid_type,expected:R.map,received:s.parsedType}),$;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],u)=>({key:r._parse(new St(s,a,s.path,[u,"key"])),value:i._parse(new St(s,c,s.path,[u,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return $;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of o){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return $;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}}Sc.create=(t,e,n)=>new Sc({valueType:e,keyType:t,typeName:P.ZodMap,...z(n)});class ps extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==R.set)return O(s,{code:k.invalid_type,expected:R.set,received:s.parsedType}),$;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(O(s,{code:k.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(O(s,{code:k.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(c){const u=new Set;for(const l of c){if(l.status==="aborted")return $;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const a=[...s.data.values()].map((c,u)=>i._parse(new St(s,c,s.path,u)));return s.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,n){return new ps({...this._def,minSize:{value:e,message:L.toString(n)}})}max(e,n){return new ps({...this._def,maxSize:{value:e,message:L.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}ps.create=(t,e)=>new ps({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...z(e)});class Bi extends Z{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bi.create=(t,e)=>new Bi({getter:t,typeName:P.ZodLazy,...z(e)});class ir extends Z{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return O(n,{received:n.data,code:k.invalid_literal,expected:this._def.value}),$}return{status:"valid",value:e.data}}get value(){return this._def.value}}ir.create=(t,e)=>new ir({value:t,typeName:P.ZodLiteral,...z(e)});function rd(t,e){return new ln({values:t,typeName:P.ZodEnum,...z(e)})}class ln extends Z{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return O(n,{expected:Q.joinValues(s),received:n.parsedType,code:k.invalid_type}),$}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return O(n,{received:n.data,code:k.invalid_enum_value,options:s}),$}return st(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return ln.create(e,{...this._def,...n})}exclude(e,n=this._def){return ln.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}ln.create=rd;class zi extends Z{_parse(e){const n=Q.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==R.string&&s.parsedType!==R.number){const r=Q.objectValues(n);return O(s,{expected:Q.joinValues(r),received:s.parsedType,code:k.invalid_type}),$}if(this._cache||(this._cache=new Set(Q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=Q.objectValues(n);return O(s,{received:s.data,code:k.invalid_enum_value,options:r}),$}return st(e.data)}get enum(){return this._def.values}}zi.create=(t,e)=>new zi({values:t,typeName:P.ZodNativeEnum,...z(e)});class or extends Z{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==R.promise&&n.common.async===!1)return O(n,{code:k.invalid_type,expected:R.promise,received:n.parsedType}),$;const s=n.parsedType===R.promise?n.data:Promise.resolve(n.data);return st(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}or.create=(t,e)=>new or({type:t,typeName:P.ZodPromise,...z(e)});class dn extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{O(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return $;const c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?$:c.status==="dirty"||n.value==="dirty"?Yn(c.value):c});{if(n.value==="aborted")return $;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?$:a.status==="dirty"||n.value==="dirty"?Yn(a.value):a}}if(r.type==="refinement"){const o=a=>{const c=r.refinement(a,i);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?$:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?$:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Tn(o))return $;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Tn(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):$);Q.assertNever(r)}}dn.create=(t,e,n)=>new dn({schema:t,typeName:P.ZodEffects,effect:e,...z(n)});dn.createWithPreprocess=(t,e,n)=>new dn({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...z(n)});class Nt extends Z{_parse(e){return this._getType(e)===R.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Nt.create=(t,e)=>new Nt({innerType:t,typeName:P.ZodOptional,...z(e)});class fn extends Z{_parse(e){return this._getType(e)===R.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fn.create=(t,e)=>new fn({innerType:t,typeName:P.ZodNullable,...z(e)});class ar extends Z{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===R.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}ar.create=(t,e)=>new ar({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...z(e)});class cr extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Xs(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Dt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Dt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}cr.create=(t,e)=>new cr({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...z(e)});class Ac extends Z{_parse(e){if(this._getType(e)!==R.nan){const s=this._getOrReturnCtx(e);return O(s,{code:k.invalid_type,expected:R.nan,received:s.parsedType}),$}return{status:"valid",value:e.data}}}Ac.create=t=>new Ac({typeName:P.ZodNaN,...z(t)});class id extends Z{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Po extends Z{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?$:i.status==="dirty"?(n.dirty(),Yn(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?$:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Po({in:e,out:n,typeName:P.ZodPipeline})}}class ur extends Z{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Tn(r)&&(r.value=Object.freeze(r.value)),r);return Xs(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}ur.create=(t,e)=>new ur({innerType:t,typeName:P.ZodReadonly,...z(e)});var P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));const yt=Ot.create,Wi=Rn.create,Rr=ji.create,od=tr.create,ms=qi.create;Zt.create;const jo=gt.create,pt=Se.create,_s=nr.create,Ov=$o.create;sr.create;un.create;const gs=rr.create,Ms=ir.create,lr=ln.create;or.create;Nt.create;fn.create;const Tv=["get","list","create","update","delete"],Rv=pt({uid:yt(),token:gs(ms()).optional()}),Lv=pt({function:lr(["get","exists"]).describe("Firestore function to mock"),path:yt().describe('Document path, e.g. "users/alice"'),result:_s([gs(ms()),Rr()]).describe("Document data for get, boolean for exists")}),Nv=Ov("kind",[pt({kind:Ms("create")}),pt({kind:Ms("set"),merge:Rr()}),pt({kind:Ms("update")}),pt({kind:Ms("delete")})]),kc=_s([yt(),Wi(),Rr(),od()]),Mv=pt({field:yt(),op:yt(),value:_s([kc,jo(kc)])}),Dv=pt({where:jo(Mv).optional(),limit:Wi().optional(),offset:Wi().optional(),orderBy:yt().optional()});pt({description:yt().describe("Human-readable description of what this test verifies"),expectation:lr(["ALLOW","DENY"]).describe("Expected outcome"),method:lr(Tv).describe("Firestore method to test"),path:yt().describe('Document path, e.g. "users/alice"'),auth:_s([Rv,od()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:gs(ms()).optional().describe("request.resource.data for write operations"),resource:gs(ms()).optional().describe("Existing document data (resource.data)"),functionMocks:jo(Lv).optional().describe("Mock get()/exists() calls in rules"),query:Dv.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:yt().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:Nv.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Jt(t){if(t.decision==="UNSUPPORTED")return;const n=t.decision==="ALLOW";let s="deny",r;if(n)s="allow",r=t.trace.find(b=>b.verdict==="ALLOW");else if(t.resourceLimit!==void 0&&t.trace.length>0)s="deny",r=t.trace[t.trace.length-1];else if(s="deny",r=t.trace.find(y=>y.verdict==="DENY"?!0:y.verdict==="ERROR"),r===void 0){const y=t.trace.length;y>0&&(r=t.trace[y-1])}if(r===void 0)return;const o={verdict:s};r.line!==void 0&&(o.line=r.line),r.col!==void 0&&(o.col=r.col,o.column=r.col),r.column!==void 0&&(o.col=r.column,o.column=r.column),r.file!==void 0&&(o.file=r.file),r.citation!==void 0&&(o.citation=r.citation),r.conditionText!==void 0&&(o.expression=r.conditionText),r.expressionTrace!==void 0&&(o.expressionTrace=r.expressionTrace);const h=o.line!==void 0,m=o.expression!==void 0,g=o.expressionTrace!==void 0;if(h||m||g)return o}function Ee(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const s=n.operations.join(","),r=`Rule #${n.ruleIndex} (${s})`;n.verdict==="ALLOW"?e.push(`${r} → ALLOW`):n.verdict==="DENY"?e.push(`${r} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${r} → unsupported: ${n.message??""}`):e.push(`${r} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}pt({function:lr(["get","exists"]).describe("Cross-service Firestore function to mock"),path:yt().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:_s([gs(ms()),Rr()]).describe("Document fields for get, boolean for exists")});const $v=new TextEncoder;function Bs(t){try{const e=JSON.stringify(t);return typeof Buffer=="function"?Buffer.byteLength(e):$v.encode(e).byteLength}catch{return 1/0}}class Pv{entries=new Set;record(e){const n=e.event;if(!(n.kind==="request"&&n.rulesEvidence!==void 0)||(this.entries.add(e),this.entries.size<=64))return;const o=this.entries.values().next().value;return o!==void 0&&this.entries.delete(o),o}forget(e){this.entries.delete(e)}clear(){this.entries.clear()}}class jv{limits;entries=[];bytes=0;liveCount=0;liveBytes=0;activeRequests=new Map;completedRequests=new Set;activeListeners=new Map;retainedIds=new Set;rulesEvidence=new Pv;sourceGapCount=0;gap;constructor(e){this.limits=e}get length(){return this.snapshot().length}append(e){const n=e.kind==="operation"?e.observation:void 0,s=this.limits!==void 0,r=s?Bs(e)+1:0;if(n?.status==="pending"){if(this.completedRequests.has(n.id))return;const u=this.activeRequests.get(n.id);u&&this.releaseLive(u);const l={event:e,bytes:r};this.activeRequests.set(n.id,l),this.reserveLive(l),this.prune();return}if(n){const u=this.activeRequests.get(n.id);u&&this.releaseLive(u),this.activeRequests.delete(n.id),this.completedRequests.add(n.id)}if(this.trackListener(e,r),this.retainedIds.has(e.id))return;this.retainedIds.add(e.id);const i="listenerId"in e?this.activeListeners.get(e.listenerId):void 0;i?.event.id===e.id&&this.releaseLive(i);const a=s&&e.kind==="observation_gap"&&e.reason==="history-limit";if(a||!Number.isFinite(r))if(this.forgetId(e),a){const u=Math.max(0,e.omittedCount-this.sourceGapCount);this.sourceGapCount=Math.max(this.sourceGapCount,e.omittedCount),u&&this.omit({...e,omittedCount:u})}else this.omit(e);else{const u={event:e,bytes:r};this.entries.push(u),this.bytes+=r;const l=this.rulesEvidence.record(u);l!==void 0&&this.expireRulesEvidence(l)}this.prune()}snapshot(){const e=[...this.entries.map(r=>r.event),...[...this.activeRequests.values()].map(r=>r.event),...[...this.activeListeners.values()].map(r=>r.event).filter(r=>!this.retainedIds.has(r.id))],n=this.gap;return n!==void 0?[{...n},...e]:e}clear(){this.entries=[],this.activeRequests.clear(),this.activeListeners.clear(),this.completedRequests.clear(),this.retainedIds.clear(),this.rulesEvidence.clear(),this.bytes=0,this.liveCount=0,this.liveBytes=0,this.gap=void 0,this.sourceGapCount=0}forgetId(e){this.retainedIds.delete(e.id);const n="listenerId"in e?this.activeListeners.get(e.listenerId):void 0;n?.event.id===e.id&&this.reserveLive(n);const r=e.kind==="operation"?e.observation:void 0;r&&this.completedRequests.delete(r.id)}trackListener(e,n){if(!("listenerId"in e))return;const s=e.kind==="listener_attach"||e.kind==="listener"&&e.phase==="attach",r=e.kind==="listener_detach"||e.kind==="listener_errored"||e.kind==="listener"&&(e.phase==="detach"||e.phase==="errored");if(!(s||r))return;const o=this.activeListeners.get(e.listenerId),a=o!==void 0&&!this.retainedIds.has(o.event.id);if(a&&this.releaseLive(o),s){const c={event:e,bytes:n};this.activeListeners.set(e.listenerId,c),!this.retainedIds.has(e.id)&&this.reserveLive(c)}else this.activeListeners.delete(e.listenerId);a&&this.omit(o.event)}expireRulesEvidence(e){const n=e.event;if(n.kind!=="request")return;const{rulesEvidence:r,...i}=n;e.event={...i,rulesEvidenceExpired:!0};const a=this.limits!==void 0?Bs(e.event)+1:0;this.bytes+=a-e.bytes,e.bytes=a}reserveLive(e){this.liveCount++,this.liveBytes+=e.bytes}releaseLive(e){this.liveCount--,this.liveBytes-=e.bytes}prune(){let e=this.exceedsLimits();for(;e;){const n=this.entries.shift();if(n===void 0)break;this.forgetId(n.event),this.rulesEvidence.forget(n),this.bytes-=n.bytes,this.omit(n.event),e=this.exceedsLimits()}}exceedsLimits(){const e=this.limits;if(e===void 0)return!1;const r=this.gap===void 0?0:Bs(this.gap)+1,i=Math.min(this.liveCount,Math.floor(e.maxEvents/2)),o=Math.min(this.liveBytes,Math.floor(e.maxBytes/2)),c=this.entries.length+i>e.maxEvents,u=this.bytes+o+r+2>e.maxBytes;return c||u}omit(e){if(("listenerId"in e?this.activeListeners.get(e.listenerId):void 0)?.event.id===e.id)return;const r=e.kind==="observation_gap",i=r?e.omittedCount:1,o=r?e.firstEventId:e.id,a=r?e.lastEventId:e.id;this.gap={kind:"observation_gap",reason:"history-limit",id:"history-gap",at:this.gap?.at??e.at,firstEventId:this.gap?.firstEventId??o,lastEventId:a,omittedCount:(this.gap?.omittedCount??0)+i}}}function Fv(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const qv={name:"date-to-timestamp",convert(t){return t instanceof Date?ve.fromMillis(t.getTime()):Ye}},Uv={name:"server-timestamp-sentinel",convert(t,e){return Fv(t)?e.serverTime instanceof ve?e.serverTime:ve.fromMillis(Date.now()):Ye}};function Bv(t){if(t===null||typeof t!="object"||t instanceof ve)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const zv={name:"user-timestamp-to-rules-timestamp",convert(t){if(t instanceof ve){const s=Math.floor(t.nanos/1e3)*1e3;return s===t.nanos?Ye:new ve(t.seconds,s)}if(Bv(t)){const s=Math.floor(t.nanoseconds/1e3)*1e3;return new ve(t.seconds,s)}return Ye}};function Ec(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Vi(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ic(t){if(typeof t!="object"||t===null||Vi(t))return;const e=t;if(typeof e.seconds=="number"){const n=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof n=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:n}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function ft(t,e){if(Object.is(t,e))return!0;const n=Ic(t),s=Ic(e);if(n!==void 0||s!==void 0){if(n===void 0||s===void 0||n.kind!==s.kind)return!1;switch(n.kind){case"timestamp":return s.kind==="timestamp"&&n.seconds===s.seconds&&n.nanoseconds===s.nanoseconds;case"bytes":return s.kind==="bytes"&&n.values.length===s.values.length&&n.values.every((o,a)=>o===s.values[a]);case"vector":return s.kind==="vector"&&n.values.length===s.values.length&&n.values.every((o,a)=>o===s.values[a]);case"geo-point":return s.kind==="geo-point"&&n.latitude===s.latitude&&n.longitude===s.longitude;case"reference":return s.kind==="reference"&&n.path===s.path}}if(Ec(t))return t.isEqual(e);if(Ec(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,a)=>ft(o,e[a]));if(!Vi(t)||!Vi(e))return!1;const r=Object.keys(t),i=Object.keys(e);return r.length!==i.length?!1:r.every(o=>o in e&&ft(t[o],e[o]))}function Wv(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function Vv(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function Gv(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function Hv(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Fo(t){if(t.prior===null)return;let e=t.prior;for(const n of t.fieldSegments){if(typeof n=="number"){if(!Array.isArray(e))return;e=e[n];continue}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,n))return;e=e[n]}return e}const Kv={name:"increment-sentinel",convert(t,e){if(!Wv(t))return Ye;const n=Fo(e);return(typeof n=="number"?n:0)+t.value}},Zv={name:"array-union-sentinel",convert(t,e){if(!Vv(t))return Ye;const n=Fo(e),s=Array.isArray(n)?n.slice():[];for(const r of t.values)s.some(o=>ft(o,r))||s.push(r);return s}},Jv={name:"array-remove-sentinel",convert(t,e){if(!Gv(t))return Ye;const n=Fo(e);return Array.isArray(n)?n.filter(s=>!t.values.some(r=>ft(s,r))):[]}},Qv={name:"delete-field-sentinel",convert(t){return Hv(t)?bt:Ye}},_c=Symbol.for("pyric.firestore.query-value-registry"),xc=globalThis,ys=xc[_c]??(xc[_c]=new WeakMap),Cc=Symbol.for("pyric.firestore.query-value-execution-registry"),Oc=globalThis,dr=Oc[Cc]??(Oc[Cc]=new WeakMap),Tc=Symbol.for("pyric.firestore.query-value-owner-registry"),Rc=globalThis,fr=Rc[Tc]??(Rc[Tc]=new WeakMap);function Dn(t,e,n=()=>t){ys.set(t,e),dr.set(t,n)}function Yv(t){return ys.get(t)}function Q0(t){return fr.get(t)}function Y0(t){return dr.get(t)?.()??t}function X0(t,e){const n=ys.get(t),s=dr.get(t);n!==void 0&&ys.set(e,n),s!==void 0&&dr.set(e,s);const r=fr.get(t);r!==void 0&&fr.set(e,r)}const Gi=Symbol.for("pyric.firestore.reference-query-value");class Xv{path;[Gi]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Gi in e&&e.path===this.path}}function qo(t){const e=ys.get(t);if(typeof e!="object"||e===null||!(Gi in e))return;const n=e.path;return typeof n=="string"?n:void 0}function ew(t,e,n,s=t){Dn(t,new Xv(e),()=>s),n!==void 0&&fr.set(t,n)}function tw(t){if(t===null||typeof t!="object"||t instanceof wt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const nw={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=qo(t);if(e!==void 0)return new wt(e)}return tw(t)?new wt(t.path):Ye}};function sw(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function rw(t){if(t===null||typeof t!="object"||t instanceof Ht)return null;const e=t;return sw(e._values)&&typeof e.toArray=="function"?e._values:null}const iw={name:"vector-value",convert(t){const e=rw(t);return e===null?Ye:new Ht(e)}};function ow(t){if(t===null||typeof t!="object"||t instanceof He)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function aw(t){if(t===null||typeof t!="object"||t instanceof ut)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const cw={name:"fb-bytes-to-rules-bytes",convert(t){return ow(t)?new He(t.toUint8Array()):Ye}},uw={name:"fb-geopoint-to-rules-latlng",convert(t){return aw(t)?new ut(t.latitude,t.longitude):Ye}};function rt(t){if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}class At extends Error{code;customData;name="FirebaseError";constructor(e,n,s){super(n),this.code=e,this.customData=s,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(At,"name",{value:"FirebaseError"});function lw(t){return t.length===0||/[.`\\]/.test(t)}function ad(t){return t.map(e=>lw(e)?`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``:e).join(".")}function Lr(t){if(!t.includes("`"))return t.split(".");const e=[];let n="",s=!1;for(let r=0;r<t.length;r++){const i=t[r];if(s){i==="\\"&&r+1<t.length?n+=t[++r]:i==="`"?s=!1:n+=i;continue}i==="`"?s=!0:i==="."?(e.push(n),n=""):n+=i}return e.push(n),e}function eA(t){const e={};for(const n of t)e[ad(n.path)]=n.value;return e}function Lc(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}function dw(t){const e={};for(const[n,s]of Object.entries(t)){const r=Lr(n);let i=e;for(const o of r.slice(0,-1)){const a=Object.hasOwn(i,o)?i[o]:void 0;rt(a)||Lc(i,o,{}),i=i[o]}Lc(i,r[r.length-1],s)}return e}function fw(t){return Object.keys(t).map(Lr)}function hw(t){return t.method==="update"&&(t.merge===void 0||t.merge===!1)}function Xn(t,e){return hw(t)?{resourceData:dw(e),updateMask:fw(e)}:{resourceData:e}}function Uo(t){if(typeof t!="object"||t===null)return;const n=t._internalPath?.segments;if(Array.isArray(n)&&n.every(r=>typeof r=="string"))return[...n]}function cd(t){return typeof t=="string"||Uo(t)!==void 0}const pw=/[~*/[\]]/,mw=/^[_a-zA-Z][_a-zA-Z0-9]*$/;function ud(t){return t.map(e=>{const n=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`");return mw.test(n)?n:`\`${n}\``}).join(".")}function hr(t,e,n,s){if(n===void 0){const r=s!==void 0&&s.length>0?` in field ${ud(s)}`:"";throw new At("invalid-argument",`Function ${t}() called with invalid data. Unsupported field value: undefined (found${r} in document ${e})`)}if(Array.isArray(n)){for(const r of n)hr(t,e,r,void 0);return}if(rt(n))for(const[r,i]of Object.entries(n))hr(t,e,i,s===void 0?void 0:[...s,r])}function pr(t,e,n){const s=n===void 0?"":` (found in document ${n})`;return new At("invalid-argument",`Function ${t}() called with invalid data. ${e}${s}`)}function ld(t,e,n){if(pw.test(e))throw pr(t,`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n);const s=e.split(".");if(s.some(r=>r.length===0))throw pr(t,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n);return s}function Nc(t,e,n){const s=Uo(e);if(s!==void 0)return s;if(typeof e=="string")return ld(t,e);throw pr(t,"Field path arguments must be of type string or ",n)}function tA(t,e,n,s){if(!cd(n)){if(!rt(n))throw pr(t,"Data must be an object, but it was: "+gw(n),e);return Object.entries(n).map(([c,u])=>{const l=ld(t,c,e);return hr(t,e,u,l),{path:l,value:u}})}const[r,...i]=s,o=[{path:Nc(t,n,e),value:r}];if(i.length%2!==0)throw new At("invalid-argument",`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let c=0;c<i.length;c+=2)o.push({path:Nc(t,i[c]),value:i[c+1]});const a=[];for(let c=o.length-1;c>=0;c--){const u=ad(o[c].path);a.includes(u)||(a.push(u),hr(t,e,o[c].value,o[c].path))}return o}function gw(t){return t===void 0?"undefined":t===null?"null":typeof t=="string"?`"${t.length>20?`${t.substring(0,20)}...`:t}"`:typeof t=="object"?Array.isArray(t)?"an array":"a custom object":typeof t=="function"?"a function":String(t)}const Ye=Symbol("value-resolver:KEEP"),bt=Symbol("value-resolver:DELETE_MARKER"),Hi=[];function it(t){Hi.some(e=>e.name===t.name)||Hi.push(t)}function ht(t,e){const n={},s=e.method==="update";for(const[r,i]of Object.entries(t)){const o=s?Lr(r):[r];n[r]=Ki(i,{...e,fieldPath:r,fieldSegments:o})}return n}function Ki(t,e){for(const n of Hi){const s=n.convert(t,e);if(s!==Ye)return s}if(Array.isArray(t))return t.map((n,s)=>Ki(n,{...e,fieldPath:`${e.fieldPath}[${s}]`,fieldSegments:[...e.fieldSegments,s]}));if(rt(t)){const n={};for(const[s,r]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${s}`:s;n[s]=Ki(r,{...e,fieldPath:i,fieldSegments:[...e.fieldSegments,s]})}return n}return t}function rn(t){const e={},n=[];for(const[s,r]of Object.entries(t)){if(r===bt){n.push(s);continue}e[s]=mr(r)}return{writes:e,deletedKeys:n}}function mr(t){if(t!==bt){if(Array.isArray(t))return t.filter(e=>e!==bt).map(mr);if(rt(t)){const e={};for(const[n,s]of Object.entries(t))s!==bt&&(e[n]=mr(s));return e}return t}}function yw(){it(qv),it(Uv),it(zv),it(Kv),it(Zv),it(Jv),it(Qv),it(nw),it(iw),it(cw),it(uw)}const Mc=Symbol.for("pyric.firestore.activity-value-registry"),Dc=globalThis,dd=Dc[Mc]??(Dc[Mc]=new WeakMap);function fd(){let t=2166136261,e=2654435769,n=2246822507,s=3266489909;const r=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),n=Math.imul(n^i,3266489909),s=Math.imul(s^i,668265263)};return{update:i=>{if(typeof i=="string")for(let o=0;o<i.length;o+=1){const a=i.charCodeAt(o);r(a&255),r(a>>>8)}else for(const o of i)r(o)},finish:()=>[t,e,n,s].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Bo(...t){const e=fd();for(const n of t)e.update(n);return e.finish()}function bw(t){return{type:"string-digest",length:t.length,digest:Bo("string\0",t)}}function gr(t,...e){return{type:`${t}-digest`,digest:Bo(`${t}\0`,...e)}}function vw(t){return{type:"bytes-digest",length:t.byteLength,digest:Bo("bytes\0",t)}}function $c(t){const e=fd(),n=(...r)=>{for(const i of r)e.update(i)},s=r=>{if(r===null){n("null;");return}switch(typeof r){case"string":n(`s${r.length}:`,r,";");return;case"number":n(`n${Object.is(r,-0)?"-0":String(r)};`);return;case"boolean":n(r?"b1;":"b0;");return;case"undefined":n("u;");return;case"bigint":n(`i${r.toString()};`);return;case"object":break;default:n(`x${typeof r};`);return}if(Array.isArray(r)){n(`a${r.length}[`);for(const a of r)s(a);n("];");return}const i=r,o=Object.keys(i).sort();n(`o${o.length}{`);for(const a of o)n(`k${a.length}:`,a,"="),s(i[a]);n("};")};return s(t),{type:"wire-value-digest",digest:e.finish()}}function bs(t,e){dd.set(t,e)}function ww(t){return dd.get(t)}const Pc=-62135596800,Sw=253402300800;class mt{seconds;nanoseconds;constructor(e,n){if(this.seconds=e,this.nanoseconds=n,n<0||n>=1e9)throw new At("invalid-argument",`Timestamp nanoseconds out of range: ${n}`);if(e<Pc||e>=Sw)throw new At("invalid-argument",`Timestamp seconds out of range: ${e}`);bs(this,gr("timestamp",String(e),"\0",String(n))),Dn(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:n}),()=>new mt(e,n))}static now(){return mt.fromMillis(Date.now())}static fromDate(e){return mt.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),s=Math.floor((e-n*1e3)*1e6);return new mt(n,s)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds-Pc,n=String(e).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function vs(t){const e={};for(const[n,s]of Object.entries(t))e[n]=hd(s);return e}function hd(t){return t instanceof Date?mt.fromDate(t).toDate():Array.isArray(t)?t.map(hd):rt(t)?qo(t)!==void 0?t:vs(t):t}function Aw(t){return t.split(".")}const kw=new Set(["__proto__","prototype","constructor"]);function jc(t){if(kw.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function pd(t,e,n){let s=t;for(let i=0;i<e.length-1;i++){const o=e[i];jc(o);const a=Object.hasOwn(s,o)?s[o]:void 0;rt(a)||(s[o]={}),s=s[o]}const r=e[e.length-1];jc(r),n===bt?delete s[r]:s[r]=mr(n)}function Nr(t,e){const n=vs(t);for(const[s,r]of Object.entries(e)){if(r!==bt&&yr(r))throw new md;pd(n,Lr(s),r)}return n}class md extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function yr(t){return t===bt?!0:Array.isArray(t)?t.some(yr):rt(t)?Object.values(t).some(yr):!1}function Ew(t){for(const e of Object.values(t))if(e!==bt&&yr(e))throw new md}function Mr(t,e,n){const s=vs(t),r=[];if(n!==void 0)for(const o of n){const a=Aw(o),c=Iw(e,a);if(c===gd)throw new At("invalid-argument",`Field '${o}' is specified in your field mask but missing from your input data.`);r.push({segments:a,value:c})}else yd(e,[],r);for(const{segments:o,value:a}of r)pd(s,o,a);return s}const gd=Symbol("field-merge:ABSENT");function Iw(t,e){let n=t;for(const s of e){if(!rt(n)||!Object.hasOwn(n,s))return gd;n=n[s]}return n}function yd(t,e,n){const s=Object.keys(t);if(s.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const r of s){const i=t[r],o=[...e,r];rt(i)&&i!==bt?yd(i,o,n):n.push({segments:o,value:i})}}function _w(t,e,n){const s=[],r=new Map;for(const[a,c]of e.entries()){const u=r.get(c.path)??t.has(c.path);switch(c.method){case"create":u&&s.push({index:a,error:`Document '${c.path}' already exists`}),r.set(c.path,!0);break;case"update":{!u&&s.push({index:a,error:`Document '${c.path}' does not exist`});break}case"delete":r.set(c.path,!1);break;case"set":r.set(c.path,!0);break}}if(s.length>0)return{success:!1,errors:s};const o=new Map;for(const a of e)if(!o.has(a.path)){const u=t.has(a.path);let l=null;u&&(l={...t.get(a.path)}),o.set(a.path,l)}for(const a of e){switch(a.method){case"create":{const c=ht({...a.data},{path:a.path,method:"create",prior:null}),{writes:u}=rn(c);t.set(a.path,u);break}case"update":{const c=t.get(a.path);if(c===void 0)throw new Error(`Validated document '${a.path}' disappeared during atomic application`);const l=ht({...a.data},{path:a.path,method:"update",prior:c});t.set(a.path,Nr(c,l));break}case"set":{const c=o.get(a.path)??null,u=ht({...a.data},{path:a.path,method:"set",prior:c}),{writes:l}=rn(u);t.set(a.path,l);break}case"delete":t.delete(a.path);break}n(a.path)}return{success:!0,priorStates:o}}function xw(t,e){if(e===void 0)throw new TypeError("Projection fields are not iterable");const s={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=t[r]);return s}class ri{onChange;documents;versions=new Map;nextVersion=1;constructor(e={},n,s){this.onChange=s,this.documents=n??new Map;for(const[r,i]of Object.entries(e)){const o=ht({...i},{path:r,method:"seed",prior:null}),{writes:a}=rn(o);this.documents.set(r,a),this.bumpVersion(r)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,n={}){const r=e===""||e.endsWith("/")?e:e+"/",i=!!n.projection;let o=d=>d;i&&(o=d=>xw(d,n.projection));const a=[],c=new Set,u=[];for(const[d,f]of this.documents){if(r!==""&&!d.startsWith(r))continue;if(!n.directOnly){a.push({path:d,data:o(f)});continue}const m=d.slice(r.length),g=m.indexOf("/");if(g===-1){a.push({path:d,data:o(f)}),c.add(m);continue}if(!!n.phantoms){const w=m.slice(0,g);w.length>0&&!u.includes(w)&&u.push(w)}}if(!!(n.directOnly&&n.phantoms))for(const d of u)c.has(d)||a.push({path:r+d,data:{},phantom:!0});return a}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const s of this.documents.keys()){const r=s.split("/",1)[0]??"";if(r.length===0)continue;!e.has(r)&&(e.add(r),n.push(r))}return n}listSubcollections(e){const s=e.endsWith("/")?e:e+"/",r=new Set,i=[];for(const o of this.documents.keys()){if(!o.startsWith(s))continue;const u=o.slice(s.length).split("/",1)[0]??"";if(u.length===0)continue;!r.has(u)&&(r.add(u),i.push(u))}return i}snapshot(){const e={};for(const[n,s]of this.documents)e[n]={...s};return e}size(){return this.documents.size}create(e,n){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let r;try{const i=ht({...n},{path:e,method:"create",prior:null});r=rn(i).writes}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,r),this.bumpVersion(e),{success:!0}}update(e,n){const s=this.documents.get(e);if(!s)return{success:!1,error:`Document '${e}' does not exist`};let i;try{const o=ht({...n},{path:e,method:"update",prior:s});i=Nr(s,o)}catch(o){return{success:!1,error:o.message}}return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:{...s}}}setMerge(e,n,s){const r=this.documents.has(e);let i=null;r&&(i={...this.documents.get(e)});const o=ht({...n},{path:e,method:"set",prior:i}),a=Mr(i??{},o,s);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:i,created:i===null}}set(e,n){const s=this.documents.has(e);let r=null;s&&(r={...this.documents.get(e)});const i=ht({...n},{path:e,method:"set",prior:r}),{writes:o}=rn(i);return this.documents.set(e,o),this.bumpVersion(e),{success:!0,priorData:r,created:r===null}}delete(e){const n=this.documents.get(e);return n?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...n}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){return _w(this.documents,e,n=>this.bumpVersion(n))}restore(e){const n=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[s,r]of Object.entries(e))this.documents.set(s,{...r});for(const s of n)this.bumpVersion(s)}restorePaths(e){for(const[n,s]of Object.entries(e))s===null?this.documents.delete(n):this.documents.set(n,{...s}),this.bumpVersion(n)}bumpVersion(e){this.versions.set(e,this.nextVersion++),this.onChange?.(e)}}class Cw{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let n=this.baseCache.get(e);return n===void 0&&(n=structuredClone(this.base[e]),this.baseCache.set(e,n)),n}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,n){this.overlay.set(e,n),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const n=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),n}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const n of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const n of Object.keys(this.base))this.tombstones.has(n)||(e.add(n),yield[n,this.overlay.has(n)?this.overlay.get(n):this.baseDoc(n)]);for(const[n,s]of this.overlay)e.has(n)||(yield[n,s])}}const Ow={maxEvents:1e4,maxBytes:8*1024*1024};class ct extends Error{code;denialContext;remediation;constructor(e,n,s){const r=typeof e=="object",i=r?e.code:e,o=r?e.message:n,a=r?e.denialContext:s,c=r?e.remediation:void 0,u=c!==void 0?`${o}
|
|
1710
1710
|
|
|
1711
1711
|
Remediation:
|
|
1712
|
-
${c}`:o;super(u),this.name="SandboxError",this.code=i,a!==void 0&&(this.denialContext=a),c!==void 0&&(this.remediation=c)}}const
|
|
1712
|
+
${c}`:o;super(u),this.name="SandboxError",this.code=i,a!==void 0&&(this.denialContext=a),c!==void 0&&(this.remediation=c)}}const bd=Symbol.for("pyric.sandbox.clock");function Fc(t){const e=t[bd];if(e===void 0)throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return e}function qc(t,e){if(!Number.isFinite(t))throw new RangeError(`${e} must be a finite number of milliseconds; received ${String(t)}.`)}class Pt{currentMode="wall";fixedAt=0;offsetMs=0;listeners=new Set;onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}announce(){const e=this.capture();for(const n of[...this.listeners])n(e)}get mode(){return this.currentMode}now(){return this.currentMode==="fixed"?this.fixedAt:this.currentMode==="offset"?Date.now()+this.offsetMs:Date.now()}date(){return new Date(this.now())}set(e){qc(e,"A clock instant"),this.currentMode="fixed",this.fixedAt=e,this.offsetMs=0,this.announce()}advance(e){if(qc(e,"A clock advance"),this.currentMode==="fixed"){this.fixedAt+=e,this.announce();return}this.currentMode="offset",this.offsetMs+=e,this.announce()}reset(){this.currentMode="wall",this.fixedAt=0,this.offsetMs=0,this.announce()}capture(){return{mode:this.currentMode,fixedAt:this.fixedAt,offsetMs:this.offsetMs}}restore(e){this.currentMode=e.mode,this.fixedAt=e.fixedAt,this.offsetMs=e.offsetMs,this.announce()}}class Tw{clock;limits;events=[];nextId=1;undoneEvents=[];eventBytes=new Map;retainedBytes=0;omittedCount=0;constructor(e=new Pt,n=Ow){this.clock=e,this.limits=n}append(e,n=!1){const s={...e,id:this.nextId++,timestamp:new Date(this.clock.now()).toISOString()};if(!n){for(const i of this.undoneEvents)this.release(i);this.undoneEvents=[]}this.events.push(s);const r=Bs(s)+1;return this.eventBytes.set(s.id,r),this.retainedBytes+=r,this.prune(),s}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const n=this.events[e];if(!n.aborted&&n.allowed&&n.method!=="get"&&n.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(n),n}return null}popLastUndo(){const e=this.undoneEvents.pop();return e?(this.release(e),e):null}getRetention(){return{retainedEvents:this.eventBytes.size,retainedBytes:this.retainedBytes,omittedCount:this.omittedCount}}release(e){this.retainedBytes-=this.eventBytes.get(e.id)??0,this.eventBytes.delete(e.id),this.eventBytes.size===0&&(this.retainedBytes=0)}prune(){const e=()=>this.eventBytes.size>this.limits.maxEvents||this.retainedBytes>this.limits.maxBytes;for(;e();){const n=this.eventBytes.keys().next().value,s=this.events[0]?.id!==n,r=s?this.undoneEvents:this.events,i=s?r.findIndex(a=>a.id===n):0,[o]=r.splice(i,1);if(!o)break;this.release(o),this.omittedCount++}}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1,this.eventBytes.clear(),this.retainedBytes=0,this.omittedCount=0}}function Rw(t){return new Date(t.toMillis()).toISOString()}class $n extends Error{method;path;debugMessages;constructor(e,n,s,r){super(e),this.method=n,this.path=s,this.debugMessages=r,this.name="SimulatorUnsupportedError"}}function Pn(t,e,n){const s=n.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),r=s?` Reason(s): ${s}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${r} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function Lw(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const Nw=`rules_version = '2';
|
|
1713
1713
|
service cloud.firestore {
|
|
1714
1714
|
match /databases/{database}/documents {
|
|
1715
1715
|
match /{document=**} {
|
|
@@ -1717,9 +1717,9 @@ service cloud.firestore {
|
|
|
1717
1717
|
}
|
|
1718
1718
|
}
|
|
1719
1719
|
}
|
|
1720
|
-
`;class en{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const n of this.subscribers)try{const s=n(...e);this.swallowAsyncRejections&&s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class
|
|
1721
|
-
"*~/[]".`);return e.split(".")}function
|
|
1722
|
-
`)){const c=nS(a);if(c?.kind!=="frame"||Yw(c.file))continue;const{kind:u,...l}=c;if(r===void 0&&!n(c.file)&&(r=s.length),s.push(l),r!==void 0&&s.length-r>=e)break}if(s.length===0)return;const i=r===void 0?s.slice(0,e):s,o={kind:"frame",...i[r??0]};return i.length>1&&(o.stack=i),o}function rS(){if(!vd())return;const t=Ww();if(t!==void 0)return sS(t)}function iS(t){if(t!==void 0){if(typeof t=="string")return t.length===0?void 0:{kind:"tag",name:t};if(Kw(t))return Zw(t);if(vr(t))return{kind:"tag",name:$r(t),element:wd(t)}}}function oS(t,e){if(e!==void 0&&e.length>0)return[...e];const n=[],s=rS();s!==void 0&&n.push(s);const r=iS(t);if(r!==void 0&&n.push(r),n.length!==0)return n}const aS={childList:!0,attributes:!0,characterData:!0,subtree:!0};function cS(){const t=globalThis,e=t.MutationObserver,n=t.document;if(typeof e=="function"&&n!=null)return{Observer:e,document:n}}function uS(t){if(vr(t))return t;if(t===null||typeof t!="object")return;const e=t.parentElement;if(vr(e))return e}function lS(t){if(!vd()){t();return}const e=cS();if(e===void 0){t();return}const n=new e.Observer(()=>{});let s=[];try{n.observe(e.document,aS),t()}finally{s=n.takeRecords(),n.disconnect()}return dS(s)}function dS(t){const e=[],n=new Set,s=r=>{const i=uS(r);if(i===void 0)return;const o=Hw(i);o.length!==0&&(n.has(o)||(n.add(o),e.push(o)))};for(const r of t){s(r.target);const i=r.addedNodes;if(i)for(let o=0;o<i.length;o+=1)s(i[o])}if(e.length!==0)return{kind:"regions",selectors:e}}function Gn(t,e=!1){return{kind:"query",collection:t.collection,...t.collectionGroup?{collectionGroup:!0}:{},...e&&t.constraints?.activityQuery?{query:t.constraints.activityQuery}:{}}}const An=Symbol.for("pyric.firestore.lookupCollector");class fS{events;triggerScope;host;clock;snapshotListeners=new Map;nextListenerId=0;listenerLookupDeps=new Map;deliveryQueue=[];deliveryScheduled=!1;deliveryOwners=new Map;constructor(e,n,s,r=new Pt){this.events=e,this.triggerScope=n,this.host=s,this.clock=r}instrumentCallback(e,n){return s=>{this.deliveryOwners.delete(e);const r=lS(()=>n(s));r!==void 0&&this.deliveryOwners.set(e,[r])}}takeDeliveryOwners(e){const n=this.deliveryOwners.get(e);return this.deliveryOwners.delete(e),n}emitSnapshotDelivery(e){const n=this.takeDeliveryOwners(e.listenerId);if(!this.events.delivery.hasSubscribers)return;const s={kind:"snapshot_delivery",id:ns().replace(/^req-/,"snd-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};n!==void 0&&(s.owners=n),this.events.delivery.emit(s)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const n={kind:"snapshot_suppressed",id:ns().replace(/^req-/,"sup-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(n)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const n={kind:e.phase,id:ns().replace(/^req-/,"lc-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};e.owners!==void 0&&(n.owners=e.owners),this.events.lifecycle.emit(n)}emitSnapshotError(e,n,s){this.events.snapshotError.emit(e,n,s)}addSnapshotListener(e,n,s={},r=null,i,o=!1,a=!1,c){const u=String(this.nextListenerId++),l=oS(s.owner,s.owners),d={id:u,target:e,callback:this.instrumentCallback(u,n),auth:r,bypassRules:a,followsCurrentUser:o,...c?{authScope:c}:{},options:s,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,d),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:Gn(e,!0),auth:r,owners:l}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(d)}),()=>{const f=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),this.deliveryOwners.delete(u),this.listenerLookupDeps.delete(u),f&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:Gn(e,!0),auth:r})}}readDocWithLookupDeps(e,n){const s=new Set,r=globalThis,i=r[An];r[An]=s;try{return this.host.silentReadDoc(n,e.auth,e.bypassRules)}finally{r[An]=i,this.listenerLookupDeps.set(e.id,s)}}readCollectionWithLookupDeps(e,n,s){const r=new Set,i=globalThis,o=i[An];i[An]=r;try{return this.host.silentReadCollection(n,e.auth,s,e.bypassRules)}finally{i[An]=o,this.listenerLookupDeps.set(e.id,r)}}touchesLookupDependency(e,n){const s=this.listenerLookupDeps.get(e);if(s===void 0||s.size===0)return!1;for(const i of n)if(s.has(i))return!0;return!1}fireInitialSnapshot(e){if(e.target.kind==="doc"){const r=this.readDocWithLookupDeps(e,e.target.path);if(!r.allowed){this.markErrored(e,r.error);return}const i=Wn(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:r.data!==null?1:0,modifiedCount:0,removedCount:0,size:r.data!==null?1:0,sample:{docs:[{path:e.target.path,data:r.data}]}});return}const n=this.readCollectionWithLookupDeps(e,Ds(e.target),e.target.constraints);if(!n.allowed){this.markErrored(e,n.error);return}const s=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:Gn(e.target),auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(r=>({path:r.path,data:r.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,n){this.scheduleDelivery(()=>this.triggerScope.run(e,n))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e,n){if(e.size===0||this.snapshotListeners.size===0)return;const s=this.triggerScope.current(),r=Array.from(this.snapshotListeners.values());for(const i of r){const o=n?this.attributeToOp(i,n)??s:s;this.scheduleTriggeredDelivery(o,()=>{this.snapshotListeners.has(i.id)&&(i.errored||(i.target.kind==="doc"?this.notifyDocListener(i,e):this.notifyQueryListener(i,e)))})}}attributeToOp(e,n){const s=e.target;for(const r of n.paths)if(s.kind==="doc"?s.path===r:Vc(new Set([r]),Ds(s)))return{method:n.method,path:r}}notifyDocListener(e,n){if(e.target.kind!=="doc")return;const s=n.has(e.target.path),r=this.touchesLookupDependency(e.id,n);if(!s&&!r)return;const i=this.readDocWithLookupDeps(e,e.target.path);if(!i.allowed){this.markErrored(e,i.error);return}if(!s)return;const o=e.currentDocData??null;if(Wc(o,i.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const a=e.target.path,c=Wn(a,i.data,Bc);e.currentSnapshot=c,e.currentDocData=i.data;const u=o!==null,l=i.data!==null,d=!u&&l?1:0,f=u&&!l?1:0,p=u&&l?1:0;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:a},auth:e.auth,addedCount:d,modifiedCount:p,removedCount:f,size:l?1:0,sample:{docs:[{path:a,data:i.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,a,i.data)}scheduleDocMetadataAck(e,n,s){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const r=Wn(n,s,Ss);e.currentSnapshot=r;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:s!==null?1:0,sample:{docs:[{path:n,data:s}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query")return;const s=Ds(e.target),r=Vc(n,s),i=this.touchesLookupDependency(e.id,n);if(!r&&!i)return;const o=this.readCollectionWithLookupDeps(e,s,e.target.constraints);if(!o.allowed){this.markErrored(e,o.error);return}if(!r)return;const a=e.target.collection,c=Gn(e.target),u=e.currentDocs??[],l=Vn({path:a},o.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},u,Bc),d=l.docChanges();if(d.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=l,e.currentDocs=o.docs;try{e.callback(l)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:c,auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:o.docs.length,sample:{docs:o.docs.map(m=>({path:m.path,data:m.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,e.target,o.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:c,auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=l,e.currentDocs=o.docs;let f=0,p=0,h=0;for(const m of d)m.type==="added"?f++:m.type==="modified"?p++:m.type==="removed"&&h++;try{e.callback(l)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:c,auth:e.auth,addedCount:f,modifiedCount:p,removedCount:h,size:o.docs.length,sample:{docs:o.docs.map(m=>({path:m.path,data:m.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,e.target,o.docs)}scheduleQueryMetadataAck(e,n,s){if(!e.options.includeMetadataChanges)return;const r=Gn(n);this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const i=Vn({path:n.collection},s,{excludesMetadataChanges:!1},s,Ss);e.currentSnapshot=i;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:r,auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:s.length,sample:{docs:s.map(o=>({path:o.path,data:o.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,n){if(e.errored=!0,this.emitSnapshotError(n,e.target,e.id),!!e.errorCallback)try{e.errorCallback(n)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const n of e)this.snapshotListeners.has(n.id)&&(n.target.kind==="doc"?this.reEvaluateDocListener(n):this.reEvaluateQueryListener(n))}reevaluateLiveListeners(e,n){if(this.snapshotListeners.size===0)return;const s=Array.from(this.snapshotListeners.values());for(const r of s)r.followsCurrentUser&&r.authScope===n&&this.snapshotListeners.has(r.id)&&(r.errored||(r.auth=e,r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r)))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.readDocWithLookupDeps(e,e.target.path);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const i=Wn(e.target.path,n.data);e.currentSnapshot=i,e.currentDocData=n.data;try{e.callback(i)}catch{}return}const s=e.currentDocData??null;if(Wc(s,n.data))return;const r=Wn(e.target.path,n.data);e.currentSnapshot=r,e.currentDocData=n.data;try{e.callback(r)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.readCollectionWithLookupDeps(e,Ds(e.target),e.target.constraints);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const o=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=o,e.currentDocs=n.docs;try{e.callback(o)}catch{}return}const s=e.currentDocs??[],r=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},s);if(r.docChanges().length!==0){e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryOwners.clear(),this.listenerLookupDeps.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class hS{eventLog;host;constructor(e,n){this.eventLog=e,this.host=n}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const n=e.type==="batch"&&e.operations?e.operations.map(a=>a.path):e.path?[e.path]:[],s=!!e.snapshot,r=s?void 0:this.host.capturePriors(n),i=s?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const a of e.operations)a.allowed&&this.host.applyWrite(a.method,a.path,a.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const o=this.eventLog.append({...e,snapshot:i,priorDocs:r},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:o}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class Ad{truncated=!1;remainingChecks=128;text(e){return e.length<=256?e:(this.truncated=!0,`${e.slice(0,256)}…`)}take(e,n){return e.length>n&&(this.truncated=!0),e.slice(0,n)}}function pS(t,e){const n={expression:e.text(t.source),parent:t.parent,operator:t.operator,kind:t.kind,helper:t.inlinedFrom?.name,binding:t.letBinding?.name};if(n.helper!==void 0&&(n.helper=e.text(n.helper)),n.binding!==void 0&&(n.binding=e.text(n.binding)),t.skipped)return{...n,state:"skipped"};if(t.error!==void 0)return{...n,state:"error",error:e.text(t.error)};const s=t.value;return s===null||typeof s=="boolean"||typeof s=="number"?{...n,state:"value",value:s}:typeof s=="string"?{...n,state:"value",value:e.text(s)}:{...n,state:"unavailable"}}function mS(t,e){const n=t.expressionTrace??[],s=e.take(n,e.remainingChecks);e.remainingChecks-=s.length;const r=t.conditionText??"",i={expression:e.text(r),verdict:t.verdict,checks:s.map(o=>pS(o,e))};return t.line!==void 0&&(i.line=t.line),t.matchPath!==void 0&&(i.path=e.text(t.matchPath)),t.message!==void 0&&(i.error=e.text(t.message)),i}function gS(t,e,n="request"){const s=new Ad,r=s.take(t.trace,32).map(a=>mS(a,s)),i=t.pathResolution?.attempts??[],o=s.take(i,32).map(a=>({path:s.text(a.blockPath),matched:a.matched,line:a.line}));return{version:e,scope:n,decision:t.decision,rules:r,paths:o,truncated:s.truncated}}function yS(t,e,n){const s=new Ad,r=s.take(t.failures,32).map(c=>{const u={reason:s.text(c.reason)};return c.rule?.expression!==void 0&&(u.expression=s.text(c.rule.expression)),c.rule?.line!==void 0&&(u.line=c.rule.line),u});let i="DENY";(t.kind==="unsupported-path"||t.kind==="unsupported-predicate")&&(i="UNSUPPORTED");const a=n??{version:e,scope:"query-residual",decision:i,truncated:!1,rules:[],paths:[]};return{...a,queryProof:{kind:t.kind,failures:r},truncated:a.truncated||s.truncated}}function Kc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`rules-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class bS{version=Kc();captureEvidence(e,n="request"){return gS(e,this.version,n)}captureQueryEvidence(e,n){return yS(e,this.version,n)}currentSource;parsedCache=null;sourceMapCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource!==e&&(this.version=Kc()),this.currentSource=e}ast(){if(this.parsedCache?.source!==this.currentSource){const e=vo(this.currentSource);this.parsedCache={source:this.currentSource,ast:e&&mo(e).length===0?e:null}}return this.parsedCache.ast}sourceMap(){return this.sourceMapCache?.source!==this.currentSource&&(this.sourceMapCache={source:this.currentSource,sourceMap:_o(this.currentSource)}),this.sourceMapCache.sourceMap}}const Z0=["permission-denied","not-found","already-exists","failed-precondition","aborted","invalid-argument","unauthenticated","unimplemented"];function me(t,e,n){const s={code:t,message:e};return n!==void 0&&(n.queryProof!==void 0&&(s.queryProof=n.queryProof),n.request!==void 0&&(s.request=n.request),n.resource!==void 0&&(s.resource=n.resource),n.remediation!==void 0&&(s.remediation=n.remediation),n.query!==void 0&&(s.query=n.query),n.rule!==void 0&&(s.rule=n.rule),n.repro!==void 0&&(s.repro=n.repro)),s}function vS(t,e){const{method:n,data:s,merge:r}=t;if(n==="get"||n==="list")return;if(!s)return s;if(r!==void 0&&r!==!1&&(n==="create"||n==="update")){const o=r===!0?void 0:r.mergeFields;return Mr(e??{},s,o)}return n==="update"?Nr(e??{},s):rn(s).writes}function Pr(t,e,n){const s=t.get(e.path),r=e.method==="set"?s!==null?"update":"create":e.method;return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:r,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:vS(e,s),resource:s??void 0,...n?{requestTime:Ew(n)}:{}}}function kd(t,e,n,s){const r=t.ast();return r?e.simulateParsed(r,t.source,n,{...s,sourceMap:t.sourceMap()}):e.simulate(t.source,n,s)}function Ed(t,e,n,s,r,i){if(r){const o=s.map(a=>Iw(a.description));return{success:!0,data:{passed:o.length,failed:0,unsupported:0,results:o}}}return kd(e,n,s,{getDoc:o=>t.get(o),...i?{batchProjection:i}:{}})}class wS{events;rules;simulator;host;eventLog;clock;constructor(e,n,s,r,i,o=new Pt){this.events=e,this.rules=n,this.simulator=s,this.host=r,this.eventLog=i,this.clock=o}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:n,path:s,auth:r,bypassRules:i}=e;let o;i===!0&&(o={admin:!0});const c=ve.fromMillis(this.clock.now()),u=Pr(this.state,e,c),l=this.clock.now(),d=performance.now(),f=Ed(this.state,this.rules,this.simulator,[u],i),p=performance.now()-d;let h=null;if(r!==void 0&&r!==null&&(h={uid:r.uid}),f.success===!0===!1){const C=this.eventLog.append({type:"single",method:n,path:s,auth:h,allowed:!1,debugMessages:[`Simulation error: ${f.error.message}`]}),S={at:l,evalMs:p,method:n,path:s,auth:r,result:"deny",debugMessages:[`Simulation error: ${f.error.message}`],origin:"user"};return o!==void 0&&(S.detail=o),this.emitRequest(S),{allowed:!1,debugMessages:[f.error.message],event:C}}const y=f.data.results[0],w=this.rules.captureEvidence(y);if(y.state==="UNSUPPORTED"){const C={at:l,evalMs:p,method:n,path:s,auth:r,result:"unsupported",rulesEvidence:w,debugMessages:Ee(y),origin:"user"};throw o!==void 0&&(C.detail=o),this.emitRequest(C),new $n(Pn(n,s,Ee(y)),n,s,Ee(y))}const E=y.state==="PASSED";let I;E&&(n==="get"?I=this.state.get(s):I=this.state.list(s));const j=this.eventLog.append({type:"single",method:n,path:s,auth:h,allowed:E,debugMessages:Ee(y)}),W={allowed:E,debugMessages:Ee(y),event:j};E&&(W.data=I);const V=Jt(y);if(E===!1){const S={request:{method:n,path:s,auth:r}};if(n==="get"){const D=this.state.get(s),H=D!==null;S.resource={data:D,exists:H}}V!==void 0&&(S.rule=V),W.error=me("permission-denied",`${n} ${s} denied by rules`,S),this.emitDenial(W.error)}let T="deny";E&&(T="allow");const N={at:l,evalMs:p,method:n,path:s,auth:r,result:T,debugMessages:Ee(y),evaluatedRule:V,rulesEvidence:w,origin:"user"};if(n==="get"){const C=this.state.get(s),S=C!==null;N.resourceBefore={data:C,exists:S}}return o!==void 0&&(N.detail=o),this.emitRequest(N),W}}const Zc=new WeakMap;let SS=1;function Jc(t){let e=Zc.get(t);return e===void 0&&(e=SS++,Zc.set(t,e)),e}function ai(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return dw(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return gr("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return gr("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=hw(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:Jc(t)}}catch{}return{type:"opaque-object",id:Jc(t)}}function AS(t,e,n){if(e<=0)return[];const s=[];for(const r of t)s.length<e?Qc(s,r,n):n(r,s[s.length-1])<0&&(s.pop(),Qc(s,r,n));return s}function Qc(t,e,n){let s=0,r=t.length;for(;s<r;){const i=s+r>>1;n(e,t[i])<0?r=i:s=i+1}t.splice(s,0,e)}function kS(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function ES(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function IS(t){return t.data instanceof Uint8Array}function _S(t){return typeof t.path=="string"}function wr(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return kS(n)?3:IS(n)?5:ES(n)?7:_S(n)?6:9}return 9}function Yc(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function xS(t,e){const n=Number.isNaN(t),s=Number.isNaN(e);return n&&s?0:n?-1:s?1:t<e?-1:t>e?1:0}function Xc(t,e){return t<e?-1:t>e?1:0}function Qt(t,e){const n=wr(t),s=wr(e);if(n!==s)return n<s?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return xS(Number(t),Number(e));case 3:{const[r,i]=Yc(t),[o,a]=Yc(e);return r!==o?r<o?-1:1:i<a?-1:i>a?1:0}case 4:return Xc(t,e);case 5:{const r=t.data,i=e.data,o=Math.min(r.length,i.length);for(let a=0;a<o;a++)if(r[a]!==i[a])return r[a]<i[a]?-1:1;return r.length<i.length?-1:r.length>i.length?1:0}case 6:return Xc(t.path,e.path);case 7:{const r=t,i=e;return r.latitude!==i.latitude?r.latitude<i.latitude?-1:1:r.longitude<i.longitude?-1:r.longitude>i.longitude?1:0}case 8:{const r=t,i=e,o=Math.min(r.length,i.length);for(let a=0;a<o;a++){const c=Qt(r[a],i[a]);if(c!==0)return c}return r.length<i.length?-1:r.length>i.length?1:0}case 9:{const r=t,i=e,o=Object.keys(r).sort(),a=Object.keys(i).sort(),c=Math.min(o.length,a.length);for(let u=0;u<c;u++){if(o[u]!==a[u])return o[u]<a[u]?-1:1;const l=Qt(r[o[u]],i[a[u]]);if(l!==0)return l}return o.length<a.length?-1:o.length>a.length?1:0}default:return 0}}function eu(t){const e=t.kind;if(e==="collection"){const n=t.path;return Object.freeze({kind:e,path:n})}if(e==="collection-group"){const n=t.collectionId;return Object.freeze({kind:e,collectionId:n})}throw new ws({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function tu(t){const e=u=>{const l=u.kind;if(l==="where"){const f=u.field,p=u.op,h=u.value;return Object.freeze({kind:l,field:f,op:p,value:h})}if(l!=="and"&&l!=="or")throw new ws({code:"invalid-argument",message:`Unknown query filter kind: ${String(l)}`});const d=u.filters;return Object.freeze({kind:l,filters:Object.freeze(Array.from(d,e))})},n=u=>{if(u===void 0)return;const l=u.values,d=u.inclusive,f=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(l)),inclusive:d,fromSnapshot:f})},s=t.filters,r=t.orders,i=t.limitCount,o=t.limitFromEnd,a=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(s,e)),orders:Object.freeze(Array.from(r,u=>{const l=u.field,d=u.direction;return Object.freeze({field:l,direction:d})})),limitCount:i,limitFromEnd:o,start:n(a),end:n(c)})}function nu(t){const e=[],n=s=>{if(s.kind==="where"){if(s.field===Vt)return;const r=s.value;(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"||s.op==="in"&&Array.isArray(r)&&r.length>0&&r.length<=30&&r.every(i=>i===null||typeof i=="string"||typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)))&&e.push(Object.freeze({field:s.field,op:s.op,value:Array.isArray(r)?Object.freeze([...r]):r}));return}s.kind==="and"&&s.filters.forEach(n)};return t.filters.forEach(n),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function CS(t){const e=n=>n.kind==="where"?{kind:n.kind,field:n.field,op:n.op,value:ai(n.value)}:{kind:n.kind,filters:n.filters.map(e)};return{filters:t.filters.map(e),orders:t.orders,limitCount:t.limitCount,limitFromEnd:t.limitFromEnd,...t.start?{start:{...t.start,values:t.start.values.map(ai)}}:{},...t.end?{end:{...t.end,values:t.end.values.map(ai)}}:{}}}function su(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const n=[];for(const[s,r]of Object.entries(t.snapshot())){const i=s.split("/").filter(o=>o.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&n.push({path:s,data:r})}return n}const Vt="__name__";function Wo(t,e){let n=t;for(const s of e.split(".")){if(!rt(n)||!Object.hasOwn(n,s))return;n=n[s]}return n}const OS=new Set(["<","<=",">",">=","!=","not-in"]);function Yi(t,e){return e===Vt?{path:t.path}:Wo(t.data,e)}function Id(t){return t.kind==="where"?OS.has(t.op)?[t.field]:[]:t.filters.flatMap(Id)}function jr(t,e){return wr(t)===wr(e)}function TS(t,e){return jr(t,e)&&Qt(t,e)<0}function RS(t,e){return jr(t,e)&&Qt(t,e)<=0}function LS(t,e){return jr(t,e)&&Qt(t,e)>0}function NS(t,e){return jr(t,e)&&Qt(t,e)>=0}function MS(t,e,n){const s=t!==void 0;switch(e){case"==":return s&&ft(t,n);case"!=":return s&&t!==null&&!ft(t,n);case"<":return s&&TS(t,n);case"<=":return s&&RS(t,n);case">":return s&&LS(t,n);case">=":return s&&NS(t,n);case"in":return s&&Array.isArray(n)&&n.some(r=>ft(t,r));case"not-in":return!Array.isArray(n)||n.some(r=>r===null)?!1:s&&t!==null&&!n.some(r=>ft(t,r));case"array-contains":return Array.isArray(t)&&t.some(r=>ft(r,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(r=>t.some(i=>ft(i,r)))}}function DS(t,e){if(e===Vt){const n=t.path.split("/");return n[n.length-1]??t.path}return Wo(t.data,e)}function _d(t){if(Array.isArray(t))return t.map(_d);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function Xi(t,e){if(e.kind==="where"){const n=DS(t,e.field),s=e.field===Vt?_d(e.value):e.value;return MS(n,e.op,s)}return e.kind==="and"?e.filters.every(n=>Xi(t,n)):e.filters.some(n=>Xi(t,n))}function $S(t,e){return t.filter(n=>e.every(s=>Xi(n,s)))}function ru(t,e,n){for(let s=0;s<e.length;s++){const r=Qt(Yi(t,n[s].field),e[s]);if(r!==0)return n[s].direction==="desc"?-r:r}return 0}function PS(t,e,n,s){return t.filter(r=>{if(n){const i=ru(r,n.values,e);if(n.inclusive?i<0:i<=0)return!1}if(s){const i=ru(r,s.values,e);if(s.inclusive?i>0:i>=0)return!1}return!0})}function xd(t,e){return t.filter(n=>e.every(s=>s.field===Vt||Wo(n.data,s.field)!==void 0))}function Cd(t){return(e,n)=>{for(const s of t){const r=Qt(Yi(e,s.field),Yi(n,s.field));if(r!==0)return s.direction==="desc"?-r:r}return 0}}function jS(t,e){return e.length===0?t:xd(t,e).sort(Cd(e))}function FS(t){const e=[...t.orders],n=new Set(e.map(r=>r.field)),s=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const r of t.filters)for(const i of Id(r))i!==Vt&&!n.has(i)&&(n.add(i),e.push({field:i,direction:s}));return n.has(Vt)||e.push({field:Vt,direction:s}),e}function iu(t,e){let n=$S(t,[...e.filters]);const s=FS(e),r=e.limitCount;if(r!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return AS(xd(n,s),r,Cd(s));if(n=jS(n,s),!!(e.start||e.end)){for(const u of[e.start,e.end])if(!!(u&&!u.fromSnapshot&&u.values.length>e.orders.length))throw new ws({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=PS(n,s,e.start,e.end)}const a=e.limitCount;if(a!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ws({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});n=a===0?[]:n.slice(-a)}else n=n.slice(0,a);return n}function qS(t,e){if(!t)return null;const n=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],s=new Set,r=t.service.match.children.flatMap(o=>{const a=BS(o,e,n,s);return a?[a]:[]});if(r.length===0)return null;const i=o=>o?.filter(a=>s.has(a.name));return{...t,functions:i(t.functions),service:{...t.service,functions:i(t.service.functions),match:{...t.service.match,functions:i(t.service.match.functions)??[],children:r}}}}function US(t,e){const[n,s,r,...i]=t.path.segments;return n?.type!=="recursive"?null:s?s.type==="literal"&&s.value===e&&r?.type==="wildcard"&&i.length===0?new Set([n.name,r.name]):null:new Set([n.name])}function BS(t,e,n,s){const r=US(t,e);if(!r)return null;const i=Gl([...n,...t.functions]),o=t.allows.filter(a=>{if(!a.operations.some(u=>u==="list"||u==="read"))return!1;const c=Hl(a.condition,r,i.functions,i.ambiguousNames);if(c.pathInvariant)for(const u of c.requiredFunctions)s.add(u);return c.pathInvariant});return o.length===0?null:{...t,functions:t.functions.filter(a=>s.has(a.name)),allows:o,children:[]}}function zS(t){return Jl(t)}class WS{events;rules;simulator;host;clock;constructor(e,n,s,r,i=new Pt){this.events=e,this.rules=n,this.simulator=s,this.host=r,this.clock=i}authorize(e){const{path:n,auth:s,constraints:r,origin:i,triggeredBy:o}=e,a=zS(r),c={...e.bypassRules?{admin:!0}:{},...a?{query:a}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,l=e.timing?.requestTime??(e.bypassRules?void 0:ve.fromMillis(this.clock.now())),d=e.timing?.at??this.clock.now();if(e.bypassRules)return this.emitRequest({at:d,evalMs:0,method:"list",path:n,auth:s,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!0};const f=this.rules.ast(),p=e.collectionGroup?qS(f,n):f;if(e.collectionGroup&&!p){const N=`list ${n} denied: no rule governs every '${n}' collection. A collection-group query needs a list or read rule at match /{path=**}/${n}/{id} or match /{document=**} whose condition reads no path binding`;this.emitRequest({at:d,evalMs:0,method:"list",path:n,auth:s,result:"deny",debugMessages:[N],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}});const B=me("permission-denied",N,{request:{method:"list",path:n,auth:s},query:r});return this.emitUserDenial(i,B),{allowed:!1,error:B}}const h=`${n}/__listPlaceholder__`,m=performance.now(),g=Kl(p,h,s,r,this.rules.source);if(g.kind==="unprovable")return this.denyQuery(e,g,d,performance.now()-m,u);const y=g.kind==="provable"?g.evaluationAst:p,w=Pr(this.host.state,{method:"list",path:h,auth:s},l);this.applyProof(w,g,r);const v=N=>this.host.state.get(N),E=y?this.simulator.simulateParsed(y,this.rules.source,[w],{getDoc:v,sourceMap:this.rules.sourceMap(),skipQueryProof:!0}):this.simulator.simulate(this.rules.source,[w],{getDoc:v}),I=performance.now()-m;if(!E.success)return this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${E.error.message}`],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!1,error:me("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:s}})};const j=E.data.results[0],W=this.rules.captureEvidence(j,"query-residual"),V=Ee(j);if(j.state==="UNSUPPORTED")throw this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"unsupported",rulesEvidence:W,debugMessages:V,origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),new $n(Pn("list",n,V),"list",n,V);return j.state!=="PASSED"?this.denyQuery(e,g,d,I,u,{reasons:V,rule:Jt(j),evidence:W}):(this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"allow",debugMessages:V,evaluatedRule:Jt(j),rulesEvidence:W,origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!0})}denyQuery(e,n,s,r,i,o={reasons:[]}){const{reasons:a,rule:c}=o,u=n.kind==="no-rule"?[]:n.failures,l=u.find(v=>v.kind!=="constraints-not-satisfied")??u[0],d={kind:l?.kind??(n.kind==="no-rule"?"no-rule":"residual-denied"),failures:u,query:e.activityQuery??(e.execution?CS(e.execution):void 0)},f=l?`list ${e.path} denied: Pyric found the query statically unprovable — ${l.reason}`:`list ${e.path} denied by rules`,p=l?[f,...a.filter(v=>!v.startsWith("No allow rules found"))]:a,h=l?$i(l.residual):void 0,m={path:e.path,auth:e.auth,constraints:e.constraints},g=l?Ql(m):void 0,b=l?zb(m):void 0,y=h&&b?`${h}
|
|
1720
|
+
`;class en{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const n of this.subscribers)try{const s=n(...e);this.swallowAsyncRejections&&s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Mw{denial=new en;request=new en(!0);write=new en(!0);delivery=new en;suppressed=new en;lifecycle=new en;snapshotError=new en;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class Dw{currentTrigger;run(e,n){const s=this.currentTrigger;this.currentTrigger=e;try{return n()}finally{this.currentTrigger=s}}current(){return this.currentTrigger}}class ws extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}function Zi(t){return t instanceof ve?new mt(t.seconds,t.nanos):t instanceof wt?(ew(t,t.path),t):t instanceof He||t instanceof ut||t instanceof Ht?t:Array.isArray(t)?t.map(Zi):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([o,a])=>[o,Zi(a)])):t}function vd(t){return Zi(t)}function $w(t){return(e,n)=>{for(const s of t)e.call(n,s)}}const Pw=/[*~/[\]]/;class Ji{_internalPath;constructor(...e){if(Array.isArray(e[0]))throw new Error("The FieldPath constructor no longer supports an array as its first argument. Please unpack your array and call FieldPath() with individual arguments.");if(e.length===0)throw new Error('Function "FieldPath()" requires at least 1 argument.');e.forEach((n,s)=>{if(typeof n!="string")throw new Error(`Element at index ${s} is not a valid string.`);if(n.length===0)throw new Error(`Element at index ${s} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new Ji("__name__");static documentId(){return Ji.DOCUMENT_ID}isEqual(e){const n=wd(e),s=this._internalPath.segments;return s.length===n.length&&s.every((r,i)=>r===n[i])}toString(){return ud(this._internalPath.segments)}}function Qi(t,e){const n=Uo(e);if(n!==void 0)return n;const r=`${typeof t=="string"?`Value for argument "${t}"`:`Element at index ${t}`} is not a valid field path.`;if(e===void 0)throw new Error(`${r} The path cannot be omitted.`);if(typeof e!="string")throw new Error(`${r} Paths can only be specified as strings or via a FieldPath object.`);if(e.includes(".."))throw new Error(`${r} Paths must not contain ".." in them.`);if(e.startsWith(".")||e.endsWith("."))throw new Error(`${r} Paths must not start or end with ".".`);if(e.length===0||Pw.test(e))throw new Error(`${r} Paths can't be empty and must not contain
|
|
1721
|
+
"*~/[]".`);return e.split(".")}function wd(t){return Qi("field",t)}function jw(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}const Uc="Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition.";function nA(t,e){const n=[];let s;if(cd(t)){const r=[t,...e];try{for(let i=0;i<r.length;i+=2)if(i===r.length-1){const a=r[i];if(typeof a!="object"||a===null)throw new Error("Input is not an object.");s=a}else n.push({path:Qi(i+1,r[i]),value:r[i+1]})}catch(i){throw new Error(`${Uc} ${i.message}`)}}else{try{if(!(typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new Error('Value for argument "dataOrField" is not a valid Firestore document. Input is not a plain JavaScript object.');for(const[i,o]of Object.entries(t))n.push({path:Qi(i,i),value:o})}catch(r){throw new Error(`${Uc} ${r.message}`)}s=e[0]}return{fields:n,options:s}}function Sd(t,e){const n=wd(e);let s=t;for(const r of n){if(!jw(s))return;s=Object.prototype.hasOwnProperty.call(s,r)?s[r]:void 0}return s}function Ds(t){return t.collectionGroup?{kind:"collection-group",collectionId:t.collection}:{kind:"collection",path:t.collection}}const Ss=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Bc=Object.freeze({hasPendingWrites:!0,fromCache:!1});function Ad(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Wn(t,e,n=Ss){const s={id:Ad(t),path:t},r=e!==null,i=r?vd(e):void 0;return{id:s.id,ref:s,metadata:n,exists:()=>r,data:()=>i,get:o=>Sd(i,o)}}function zc(t,e,n=Ss){const s={id:Ad(t),path:t},r=vd(e);return{id:s.id,ref:s,metadata:n,exists:()=>!0,data:()=>r,get:i=>Sd(r,i)}}function Vn(t,e,n,s,r=Ss){const i=e.map(a=>zc(a.path,a.data,r)),o=Uw(s,e,i,(a,c)=>JSON.stringify(a.data)===JSON.stringify(c.data),a=>zc(a.path,a.data,r));return{query:t,metadata:r,size:i.length,empty:i.length===0,docs:i,forEach:$w(i),docChanges:qw(o,n.excludesMetadataChanges)}}const Fw="To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().";function qw(t,e){let n=null,s=null;return r=>{const i=r?.includeMetadataChanges===!0;if(i&&e)throw new Error(Fw);return i?(s??=t.slice(),s):(n??=t.slice(),n)}}function Uw(t,e,n,s,r){if(t===void 0)return n.map((c,u)=>({type:"added",doc:c,oldIndex:-1,newIndex:u}));const i=new Map;t.forEach((c,u)=>i.set(c.path,u));const o=new Set(e.map(c=>c.path)),a=[];for(let c=0;c<t.length;c++){const u=t[c];o.has(u.path)||a.push({type:"removed",doc:r(u),oldIndex:c,newIndex:-1})}for(let c=0;c<e.length;c++){const u=e[c],l=i.get(u.path);l===void 0?a.push({type:"added",doc:n[c],oldIndex:-1,newIndex:c}):s(t[l],u)||a.push({type:"modified",doc:n[c],oldIndex:l,newIndex:c})}return a}function Wc(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function Vc(t,e){for(const n of t){if(e.kind==="collection-group"){const i=n.split("/");if(i.length%2===0&&i[i.length-2]===e.collectionId)return!0;continue}const s=`${e.path}/`;if(!n.startsWith(s))continue;const r=n.slice(s.length);if(r.length>0&&!r.includes("/"))return!0}return!1}let ii=0;function ns(){return ii=ii+1>>>0,`req-${ii.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function Bw(t,e){const n=e==="allow";let s;for(const r of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(r);if(!i)continue;const o={ruleIndex:Number(i[1]),operations:i[2].split(",").map(a=>a.trim())};if(n&&i[3]==="ALLOW")return o;s=o}return s}function Dr(t){const e={kind:"request",id:ns(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData},t.updateMask!==void 0&&(e.request.updateMask=t.updateMask)),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter),t.rulesEvidence!==void 0&&(e.rulesEvidence=t.rulesEvidence),t.queryProof!==void 0&&(e.queryProof=t.queryProof);const n=Bw(t.debugMessages,t.result);return n&&(e.matchedRule=n),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}const zw={ASSETS_PREFIX:void 0,BASE_URL:"/__pyric/ui/",DEV:!1,MODE:"production",PROD:!0,SITE:void 0,SSR:!1,STUDIO_STATIC:!1},Ww="production";function Vw(){try{return zw?.PROD===!0}catch{return!1}}function Gw(){const t=globalThis.process;return t===void 0?!1:t.env?.NODE_ENV===Ww}function kd(){return!(Vw()||Gw())}const Hw=3,Kw=()=>!1;let Zw={frames:Hw,skips:Kw};function Jw(){return Zw}function Qw(){const t=Error,e=t.stackTraceLimit,n=typeof e=="number"&&e<Gc;n&&(t.stackTraceLimit=Gc);try{const s=new Error().stack;return typeof s=="string"?s:void 0}finally{n&&(t.stackTraceLimit=e)}}const Gc=50,br="data-pyric-owner";let Hc=0;function vr(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.getAttribute!="function"?!1:typeof e.tagName=="string"}function $r(t){const e=t.tagName;return typeof e!="string"||e.length===0?"element":e.toLowerCase()}function zo(t){const e=t.id;if(typeof e=="string"&&e.length>0)return`#${e}`;const n=t.getAttribute(br);if(typeof n=="string"&&n.length>0)return`[${br}="${n}"]`}function Yw(t){const e=t.parentElement;if(!e)return 1;const n=e.children;if(!n)return 1;for(let s=0;s<n.length;s+=1)if(n[s]===t)return s+1;return 1}function Xw(t){const e=[];let n=t,s=0;for(;n&&s<8;){const r=zo(n);if(r!==void 0)return e.unshift(r),e.join(" > ");e.unshift(`${$r(n)}:nth-child(${Yw(n)})`),n=n.parentElement,s+=1}return e.join(" > ")}function Ed(t){const e=zo(t);if(e!==void 0)return e;Hc+=1;const n=`${$r(t)}-${Hc.toString(36)}`;return t.setAttribute(br,n),`[${br}="${n}"]`}function eS(t){const e=zo(t);return e!==void 0?e:Xw(t)}function tS(t){return t===null||typeof t!="object"?!1:"kind"in t&&typeof t.kind=="string"}function nS(t){if(t.kind!=="component")return t;const e={kind:"component",name:t.name};t.path!==void 0&&t.path.length>0&&(e.path=t.path);const n=t.element;return typeof n=="string"?e.element=n:n!==void 0&&vr(n)&&(e.element=Ed(n),e.tag=$r(n)),e}const Sn=sS();function sS(){const t=rS();if(t===void 0)return"";const e=t.slice(0,t.lastIndexOf("/")),n=e.slice(0,e.lastIndexOf("/")),s=n.slice(0,n.lastIndexOf("/"));return Id(s)}function rS(){try{const t=import.meta.url;return typeof t!="string"?void 0:t}catch{return}}function Id(t){return t.startsWith("file://")?t.slice(7):t}function iS(t){if(t.includes("/node_modules/")||t==="native"||t.startsWith("node:")||Sn.length>0&&t.startsWith(`${Sn}/`))return!0;const e=Sn.endsWith("/src")?`${Sn.slice(0,-4)}/dist`:Sn.endsWith("/dist")?`${Sn.slice(0,-5)}/src`:"";return!!(e&&t.startsWith(`${e}/`))}const oS=/^\s*at\s+(.+?)\s+\((.+):(\d+):(\d+)\)\s*$/,aS=/^\s*at\s+(.+):(\d+):(\d+)\s*$/,cS=/^\s*(.*?)@(.+):(\d+):(\d+)\s*$/;function uS(t){const e=oS.exec(t);if(e)return oi(e[2],e[3],e[4],e[1]);const n=aS.exec(t);if(n)return oi(n[1],n[2],n[3],"");const s=cS.exec(t);if(s)return oi(s[2],s[3],s[4],s[1])}function oi(t,e,n,s){const r={kind:"frame",file:Id(t),line:Number(e),column:Number(n)};return s.length>0&&(r.function=s),r}function lS(t){const{frames:e,skips:n}=Jw(),s=[];let r;for(const a of t.split(`
|
|
1722
|
+
`)){const c=uS(a);if(c?.kind!=="frame"||iS(c.file))continue;const{kind:u,...l}=c;if(r===void 0&&!n(c.file)&&(r=s.length),s.push(l),r!==void 0&&s.length-r>=e)break}if(s.length===0)return;const i=r===void 0?s.slice(0,e):s,o={kind:"frame",...i[r??0]};return i.length>1&&(o.stack=i),o}function dS(){if(!kd())return;const t=Qw();if(t!==void 0)return lS(t)}function fS(t){if(t!==void 0){if(typeof t=="string")return t.length===0?void 0:{kind:"tag",name:t};if(tS(t))return nS(t);if(vr(t))return{kind:"tag",name:$r(t),element:Ed(t)}}}function hS(t,e){if(e!==void 0&&e.length>0)return[...e];const n=[],s=dS();s!==void 0&&n.push(s);const r=fS(t);if(r!==void 0&&n.push(r),n.length!==0)return n}const pS={childList:!0,attributes:!0,characterData:!0,subtree:!0};function mS(){const t=globalThis,e=t.MutationObserver,n=t.document;if(typeof e=="function"&&n!=null)return{Observer:e,document:n}}function gS(t){if(vr(t))return t;if(t===null||typeof t!="object")return;const e=t.parentElement;if(vr(e))return e}function yS(t){if(!kd()){t();return}const e=mS();if(e===void 0){t();return}const n=new e.Observer(()=>{});let s=[];try{n.observe(e.document,pS),t()}finally{s=n.takeRecords(),n.disconnect()}return bS(s)}function bS(t){const e=[],n=new Set,s=r=>{const i=gS(r);if(i===void 0)return;const o=eS(i);o.length!==0&&(n.has(o)||(n.add(o),e.push(o)))};for(const r of t){s(r.target);const i=r.addedNodes;if(i)for(let o=0;o<i.length;o+=1)s(i[o])}if(e.length!==0)return{kind:"regions",selectors:e}}function Gn(t,e=!1){return{kind:"query",collection:t.collection,...t.collectionGroup?{collectionGroup:!0}:{},...e&&t.constraints?.activityQuery?{query:t.constraints.activityQuery}:{}}}const An=Symbol.for("pyric.firestore.lookupCollector");class vS{events;triggerScope;host;clock;snapshotListeners=new Map;nextListenerId=0;listenerLookupDeps=new Map;deliveryQueue=[];deliveryScheduled=!1;deliveryOwners=new Map;constructor(e,n,s,r=new Pt){this.events=e,this.triggerScope=n,this.host=s,this.clock=r}instrumentCallback(e,n){return s=>{this.deliveryOwners.delete(e);const r=yS(()=>n(s));r!==void 0&&this.deliveryOwners.set(e,[r])}}takeDeliveryOwners(e){const n=this.deliveryOwners.get(e);return this.deliveryOwners.delete(e),n}emitSnapshotDelivery(e){const n=this.takeDeliveryOwners(e.listenerId);if(!this.events.delivery.hasSubscribers)return;const s={kind:"snapshot_delivery",id:ns().replace(/^req-/,"snd-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};n!==void 0&&(s.owners=n),this.events.delivery.emit(s)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const n={kind:"snapshot_suppressed",id:ns().replace(/^req-/,"sup-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(n)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const n={kind:e.phase,id:ns().replace(/^req-/,"lc-"),at:this.clock.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};e.owners!==void 0&&(n.owners=e.owners),this.events.lifecycle.emit(n)}emitSnapshotError(e,n,s){this.events.snapshotError.emit(e,n,s)}addSnapshotListener(e,n,s={},r=null,i,o=!1,a=!1,c){const u=String(this.nextListenerId++),l=hS(s.owner,s.owners),d={id:u,target:e,callback:this.instrumentCallback(u,n),auth:r,bypassRules:a,followsCurrentUser:o,...c?{authScope:c}:{},options:s,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,d),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:Gn(e,!0),auth:r,owners:l}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(d)}),()=>{const f=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),this.deliveryOwners.delete(u),this.listenerLookupDeps.delete(u),f&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:Gn(e,!0),auth:r})}}readDocWithLookupDeps(e,n){const s=new Set,r=globalThis,i=r[An];r[An]=s;try{return this.host.silentReadDoc(n,e.auth,e.bypassRules)}finally{r[An]=i,this.listenerLookupDeps.set(e.id,s)}}readCollectionWithLookupDeps(e,n,s){const r=new Set,i=globalThis,o=i[An];i[An]=r;try{return this.host.silentReadCollection(n,e.auth,s,e.bypassRules)}finally{i[An]=o,this.listenerLookupDeps.set(e.id,r)}}touchesLookupDependency(e,n){const s=this.listenerLookupDeps.get(e);if(s===void 0||s.size===0)return!1;for(const i of n)if(s.has(i))return!0;return!1}fireInitialSnapshot(e){if(e.target.kind==="doc"){const r=this.readDocWithLookupDeps(e,e.target.path);if(!r.allowed){this.markErrored(e,r.error);return}const i=Wn(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:r.data!==null?1:0,modifiedCount:0,removedCount:0,size:r.data!==null?1:0,sample:{docs:[{path:e.target.path,data:r.data}]}});return}const n=this.readCollectionWithLookupDeps(e,Ds(e.target),e.target.constraints);if(!n.allowed){this.markErrored(e,n.error);return}const s=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:Gn(e.target),auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(r=>({path:r.path,data:r.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,n){this.scheduleDelivery(()=>this.triggerScope.run(e,n))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e,n){if(e.size===0||this.snapshotListeners.size===0)return;const s=this.triggerScope.current(),r=Array.from(this.snapshotListeners.values());for(const i of r){const o=n?this.attributeToOp(i,n)??s:s;this.scheduleTriggeredDelivery(o,()=>{this.snapshotListeners.has(i.id)&&(i.errored||(i.target.kind==="doc"?this.notifyDocListener(i,e):this.notifyQueryListener(i,e)))})}}attributeToOp(e,n){const s=e.target;for(const r of n.paths)if(s.kind==="doc"?s.path===r:Vc(new Set([r]),Ds(s)))return{method:n.method,path:r}}notifyDocListener(e,n){if(e.target.kind!=="doc")return;const s=n.has(e.target.path),r=this.touchesLookupDependency(e.id,n);if(!s&&!r)return;const i=this.readDocWithLookupDeps(e,e.target.path);if(!i.allowed){this.markErrored(e,i.error);return}if(!s)return;const o=e.currentDocData??null;if(Wc(o,i.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const a=e.target.path,c=Wn(a,i.data,Bc);e.currentSnapshot=c,e.currentDocData=i.data;const u=o!==null,l=i.data!==null,d=!u&&l?1:0,f=u&&!l?1:0,p=u&&l?1:0;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:a},auth:e.auth,addedCount:d,modifiedCount:p,removedCount:f,size:l?1:0,sample:{docs:[{path:a,data:i.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,a,i.data)}scheduleDocMetadataAck(e,n,s){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const r=Wn(n,s,Ss);e.currentSnapshot=r;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:s!==null?1:0,sample:{docs:[{path:n,data:s}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query")return;const s=Ds(e.target),r=Vc(n,s),i=this.touchesLookupDependency(e.id,n);if(!r&&!i)return;const o=this.readCollectionWithLookupDeps(e,s,e.target.constraints);if(!o.allowed){this.markErrored(e,o.error);return}if(!r)return;const a=e.target.collection,c=Gn(e.target),u=e.currentDocs??[],l=Vn({path:a},o.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},u,Bc),d=l.docChanges();if(d.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=l,e.currentDocs=o.docs;try{e.callback(l)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:c,auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:o.docs.length,sample:{docs:o.docs.map(m=>({path:m.path,data:m.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,e.target,o.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:c,auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=l,e.currentDocs=o.docs;let f=0,p=0,h=0;for(const m of d)m.type==="added"?f++:m.type==="modified"?p++:m.type==="removed"&&h++;try{e.callback(l)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:c,auth:e.auth,addedCount:f,modifiedCount:p,removedCount:h,size:o.docs.length,sample:{docs:o.docs.map(m=>({path:m.path,data:m.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,e.target,o.docs)}scheduleQueryMetadataAck(e,n,s){if(!e.options.includeMetadataChanges)return;const r=Gn(n);this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const i=Vn({path:n.collection},s,{excludesMetadataChanges:!1},s,Ss);e.currentSnapshot=i;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:r,auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:s.length,sample:{docs:s.map(o=>({path:o.path,data:o.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,n){if(e.errored=!0,this.emitSnapshotError(n,e.target,e.id),!!e.errorCallback)try{e.errorCallback(n)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const n of e)this.snapshotListeners.has(n.id)&&(n.target.kind==="doc"?this.reEvaluateDocListener(n):this.reEvaluateQueryListener(n))}reevaluateLiveListeners(e,n){if(this.snapshotListeners.size===0)return;const s=Array.from(this.snapshotListeners.values());for(const r of s)r.followsCurrentUser&&r.authScope===n&&this.snapshotListeners.has(r.id)&&(r.errored||(r.auth=e,r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r)))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.readDocWithLookupDeps(e,e.target.path);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const i=Wn(e.target.path,n.data);e.currentSnapshot=i,e.currentDocData=n.data;try{e.callback(i)}catch{}return}const s=e.currentDocData??null;if(Wc(s,n.data))return;const r=Wn(e.target.path,n.data);e.currentSnapshot=r,e.currentDocData=n.data;try{e.callback(r)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.readCollectionWithLookupDeps(e,Ds(e.target),e.target.constraints);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const o=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=o,e.currentDocs=n.docs;try{e.callback(o)}catch{}return}const s=e.currentDocs??[],r=Vn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},s);if(r.docChanges().length!==0){e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryOwners.clear(),this.listenerLookupDeps.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class wS{eventLog;host;constructor(e,n){this.eventLog=e,this.host=n}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const n=e.type==="batch"&&e.operations?e.operations.map(a=>a.path):e.path?[e.path]:[],s=!!e.snapshot,r=s?void 0:this.host.capturePriors(n),i=s?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const a of e.operations)a.allowed&&this.host.applyWrite(a.method,a.path,a.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const o=this.eventLog.append({...e,snapshot:i,priorDocs:r},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:o}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class _d{truncated=!1;remainingChecks=128;text(e){return e.length<=256?e:(this.truncated=!0,`${e.slice(0,256)}…`)}take(e,n){return e.length>n&&(this.truncated=!0),e.slice(0,n)}}function SS(t,e){const n={expression:e.text(t.source),parent:t.parent,operator:t.operator,kind:t.kind,helper:t.inlinedFrom?.name,binding:t.letBinding?.name};if(n.helper!==void 0&&(n.helper=e.text(n.helper)),n.binding!==void 0&&(n.binding=e.text(n.binding)),t.skipped)return{...n,state:"skipped"};if(t.error!==void 0)return{...n,state:"error",error:e.text(t.error)};const s=t.value;return s===null||typeof s=="boolean"||typeof s=="number"?{...n,state:"value",value:s}:typeof s=="string"?{...n,state:"value",value:e.text(s)}:{...n,state:"unavailable"}}function AS(t,e){const n=t.expressionTrace??[],s=e.take(n,e.remainingChecks);e.remainingChecks-=s.length;const r=t.conditionText??"",i={expression:e.text(r),verdict:t.verdict,checks:s.map(o=>SS(o,e))};return t.line!==void 0&&(i.line=t.line),t.matchPath!==void 0&&(i.path=e.text(t.matchPath)),t.message!==void 0&&(i.error=e.text(t.message)),i}function kS(t,e,n="request"){const s=new _d,r=s.take(t.trace,32).map(a=>AS(a,s)),i=t.pathResolution?.attempts??[],o=s.take(i,32).map(a=>({path:s.text(a.blockPath),matched:a.matched,line:a.line}));return{version:e,scope:n,decision:t.decision,rules:r,paths:o,truncated:s.truncated}}function ES(t,e,n){const s=new _d,r=s.take(t.failures,32).map(c=>{const u={reason:s.text(c.reason)};return c.rule?.expression!==void 0&&(u.expression=s.text(c.rule.expression)),c.rule?.line!==void 0&&(u.line=c.rule.line),u});let i="DENY";(t.kind==="unsupported-path"||t.kind==="unsupported-predicate")&&(i="UNSUPPORTED");const a=n??{version:e,scope:"query-residual",decision:i,truncated:!1,rules:[],paths:[]};return{...a,queryProof:{kind:t.kind,failures:r},truncated:a.truncated||s.truncated}}function Kc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`rules-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class IS{version=Kc();captureEvidence(e,n="request"){return kS(e,this.version,n)}captureQueryEvidence(e,n){return ES(e,this.version,n)}currentSource;parsedCache=null;sourceMapCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource!==e&&(this.version=Kc()),this.currentSource=e}ast(){if(this.parsedCache?.source!==this.currentSource){const e=vo(this.currentSource);this.parsedCache={source:this.currentSource,ast:e&&mo(e).length===0?e:null}}return this.parsedCache.ast}sourceMap(){return this.sourceMapCache?.source!==this.currentSource&&(this.sourceMapCache={source:this.currentSource,sourceMap:_o(this.currentSource)}),this.sourceMapCache.sourceMap}}const sA=["permission-denied","not-found","already-exists","failed-precondition","aborted","invalid-argument","unauthenticated","unimplemented"];function me(t,e,n){const s={code:t,message:e};return n!==void 0&&(n.queryProof!==void 0&&(s.queryProof=n.queryProof),n.request!==void 0&&(s.request=n.request),n.resource!==void 0&&(s.resource=n.resource),n.remediation!==void 0&&(s.remediation=n.remediation),n.query!==void 0&&(s.query=n.query),n.rule!==void 0&&(s.rule=n.rule),n.repro!==void 0&&(s.repro=n.repro)),s}function _S(t,e){const{method:n,data:s,merge:r}=t;if(n==="get"||n==="list")return;if(!s)return s;if(r!==void 0&&r!==!1&&(n==="create"||n==="update")){const o=r===!0?void 0:r.mergeFields;return Mr(e??{},s,o)}return n==="update"?Nr(e??{},s):rn(s).writes}function Pr(t,e,n){const s=t.get(e.path),r=e.method==="set"?s!==null?"update":"create":e.method;return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:r,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:_S(e,s),resource:s??void 0,...n?{requestTime:Rw(n)}:{}}}function xd(t,e,n,s){const r=t.ast();return r?e.simulateParsed(r,t.source,n,{...s,sourceMap:t.sourceMap()}):e.simulate(t.source,n,s)}function Cd(t,e,n,s,r,i){if(r){const o=s.map(a=>Lw(a.description));return{success:!0,data:{passed:o.length,failed:0,unsupported:0,results:o}}}return xd(e,n,s,{getDoc:o=>t.get(o),...i?{batchProjection:i}:{}})}class xS{events;rules;simulator;host;eventLog;clock;constructor(e,n,s,r,i,o=new Pt){this.events=e,this.rules=n,this.simulator=s,this.host=r,this.eventLog=i,this.clock=o}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:n,path:s,auth:r,bypassRules:i}=e;let o;i===!0&&(o={admin:!0});const c=ve.fromMillis(this.clock.now()),u=Pr(this.state,e,c),l=this.clock.now(),d=performance.now(),f=Cd(this.state,this.rules,this.simulator,[u],i),p=performance.now()-d;let h=null;if(r!==void 0&&r!==null&&(h={uid:r.uid}),f.success===!0===!1){const C=this.eventLog.append({type:"single",method:n,path:s,auth:h,allowed:!1,debugMessages:[`Simulation error: ${f.error.message}`]}),S={at:l,evalMs:p,method:n,path:s,auth:r,result:"deny",debugMessages:[`Simulation error: ${f.error.message}`],origin:"user"};return o!==void 0&&(S.detail=o),this.emitRequest(S),{allowed:!1,debugMessages:[f.error.message],event:C}}const y=f.data.results[0],w=this.rules.captureEvidence(y);if(y.state==="UNSUPPORTED"){const C={at:l,evalMs:p,method:n,path:s,auth:r,result:"unsupported",rulesEvidence:w,debugMessages:Ee(y),origin:"user"};throw o!==void 0&&(C.detail=o),this.emitRequest(C),new $n(Pn(n,s,Ee(y)),n,s,Ee(y))}const E=y.state==="PASSED";let I;E&&(n==="get"?I=this.state.get(s):I=this.state.list(s));const j=this.eventLog.append({type:"single",method:n,path:s,auth:h,allowed:E,debugMessages:Ee(y)}),W={allowed:E,debugMessages:Ee(y),event:j};E&&(W.data=I);const V=Jt(y);if(E===!1){const S={request:{method:n,path:s,auth:r}};if(n==="get"){const D=this.state.get(s),H=D!==null;S.resource={data:D,exists:H}}V!==void 0&&(S.rule=V),W.error=me("permission-denied",`${n} ${s} denied by rules`,S),this.emitDenial(W.error)}let T="deny";E&&(T="allow");const N={at:l,evalMs:p,method:n,path:s,auth:r,result:T,debugMessages:Ee(y),evaluatedRule:V,rulesEvidence:w,origin:"user"};if(n==="get"){const C=this.state.get(s),S=C!==null;N.resourceBefore={data:C,exists:S}}return o!==void 0&&(N.detail=o),this.emitRequest(N),W}}const Zc=new WeakMap;let CS=1;function Jc(t){let e=Zc.get(t);return e===void 0&&(e=CS++,Zc.set(t,e)),e}function ai(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return bw(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return gr("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return gr("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=ww(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:Jc(t)}}catch{}return{type:"opaque-object",id:Jc(t)}}function OS(t,e,n){if(e<=0)return[];const s=[];for(const r of t)s.length<e?Qc(s,r,n):n(r,s[s.length-1])<0&&(s.pop(),Qc(s,r,n));return s}function Qc(t,e,n){let s=0,r=t.length;for(;s<r;){const i=s+r>>1;n(e,t[i])<0?r=i:s=i+1}t.splice(s,0,e)}function TS(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function RS(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function LS(t){return t.data instanceof Uint8Array}function NS(t){return typeof t.path=="string"}function wr(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return TS(n)?3:LS(n)?5:RS(n)?7:NS(n)?6:9}return 9}function Yc(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function MS(t,e){const n=Number.isNaN(t),s=Number.isNaN(e);return n&&s?0:n?-1:s?1:t<e?-1:t>e?1:0}function Xc(t,e){return t<e?-1:t>e?1:0}function Qt(t,e){const n=wr(t),s=wr(e);if(n!==s)return n<s?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return MS(Number(t),Number(e));case 3:{const[r,i]=Yc(t),[o,a]=Yc(e);return r!==o?r<o?-1:1:i<a?-1:i>a?1:0}case 4:return Xc(t,e);case 5:{const r=t.data,i=e.data,o=Math.min(r.length,i.length);for(let a=0;a<o;a++)if(r[a]!==i[a])return r[a]<i[a]?-1:1;return r.length<i.length?-1:r.length>i.length?1:0}case 6:return Xc(t.path,e.path);case 7:{const r=t,i=e;return r.latitude!==i.latitude?r.latitude<i.latitude?-1:1:r.longitude<i.longitude?-1:r.longitude>i.longitude?1:0}case 8:{const r=t,i=e,o=Math.min(r.length,i.length);for(let a=0;a<o;a++){const c=Qt(r[a],i[a]);if(c!==0)return c}return r.length<i.length?-1:r.length>i.length?1:0}case 9:{const r=t,i=e,o=Object.keys(r).sort(),a=Object.keys(i).sort(),c=Math.min(o.length,a.length);for(let u=0;u<c;u++){if(o[u]!==a[u])return o[u]<a[u]?-1:1;const l=Qt(r[o[u]],i[a[u]]);if(l!==0)return l}return o.length<a.length?-1:o.length>a.length?1:0}default:return 0}}function eu(t){const e=t.kind;if(e==="collection"){const n=t.path;return Object.freeze({kind:e,path:n})}if(e==="collection-group"){const n=t.collectionId;return Object.freeze({kind:e,collectionId:n})}throw new ws({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function tu(t){const e=u=>{const l=u.kind;if(l==="where"){const f=u.field,p=u.op,h=u.value;return Object.freeze({kind:l,field:f,op:p,value:h})}if(l!=="and"&&l!=="or")throw new ws({code:"invalid-argument",message:`Unknown query filter kind: ${String(l)}`});const d=u.filters;return Object.freeze({kind:l,filters:Object.freeze(Array.from(d,e))})},n=u=>{if(u===void 0)return;const l=u.values,d=u.inclusive,f=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(l)),inclusive:d,fromSnapshot:f})},s=t.filters,r=t.orders,i=t.limitCount,o=t.limitFromEnd,a=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(s,e)),orders:Object.freeze(Array.from(r,u=>{const l=u.field,d=u.direction;return Object.freeze({field:l,direction:d})})),limitCount:i,limitFromEnd:o,start:n(a),end:n(c)})}function nu(t){const e=[],n=s=>{if(s.kind==="where"){if(s.field===Vt)return;const r=s.value;(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"||s.op==="in"&&Array.isArray(r)&&r.length>0&&r.length<=30&&r.every(i=>i===null||typeof i=="string"||typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)))&&e.push(Object.freeze({field:s.field,op:s.op,value:Array.isArray(r)?Object.freeze([...r]):r}));return}s.kind==="and"&&s.filters.forEach(n)};return t.filters.forEach(n),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function DS(t){const e=n=>n.kind==="where"?{kind:n.kind,field:n.field,op:n.op,value:ai(n.value)}:{kind:n.kind,filters:n.filters.map(e)};return{filters:t.filters.map(e),orders:t.orders,limitCount:t.limitCount,limitFromEnd:t.limitFromEnd,...t.start?{start:{...t.start,values:t.start.values.map(ai)}}:{},...t.end?{end:{...t.end,values:t.end.values.map(ai)}}:{}}}function su(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const n=[];for(const[s,r]of Object.entries(t.snapshot())){const i=s.split("/").filter(o=>o.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&n.push({path:s,data:r})}return n}const Vt="__name__";function Wo(t,e){let n=t;for(const s of e.split(".")){if(!rt(n)||!Object.hasOwn(n,s))return;n=n[s]}return n}const $S=new Set(["<","<=",">",">=","!=","not-in"]);function Yi(t,e){return e===Vt?{path:t.path}:Wo(t.data,e)}function Od(t){return t.kind==="where"?$S.has(t.op)?[t.field]:[]:t.filters.flatMap(Od)}function jr(t,e){return wr(t)===wr(e)}function PS(t,e){return jr(t,e)&&Qt(t,e)<0}function jS(t,e){return jr(t,e)&&Qt(t,e)<=0}function FS(t,e){return jr(t,e)&&Qt(t,e)>0}function qS(t,e){return jr(t,e)&&Qt(t,e)>=0}function US(t,e,n){const s=t!==void 0;switch(e){case"==":return s&&ft(t,n);case"!=":return s&&t!==null&&!ft(t,n);case"<":return s&&PS(t,n);case"<=":return s&&jS(t,n);case">":return s&&FS(t,n);case">=":return s&&qS(t,n);case"in":return s&&Array.isArray(n)&&n.some(r=>ft(t,r));case"not-in":return!Array.isArray(n)||n.some(r=>r===null)?!1:s&&t!==null&&!n.some(r=>ft(t,r));case"array-contains":return Array.isArray(t)&&t.some(r=>ft(r,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(r=>t.some(i=>ft(i,r)))}}function BS(t,e){if(e===Vt){const n=t.path.split("/");return n[n.length-1]??t.path}return Wo(t.data,e)}function Td(t){if(Array.isArray(t))return t.map(Td);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function Xi(t,e){if(e.kind==="where"){const n=BS(t,e.field),s=e.field===Vt?Td(e.value):e.value;return US(n,e.op,s)}return e.kind==="and"?e.filters.every(n=>Xi(t,n)):e.filters.some(n=>Xi(t,n))}function zS(t,e){return t.filter(n=>e.every(s=>Xi(n,s)))}function ru(t,e,n){for(let s=0;s<e.length;s++){const r=Qt(Yi(t,n[s].field),e[s]);if(r!==0)return n[s].direction==="desc"?-r:r}return 0}function WS(t,e,n,s){return t.filter(r=>{if(n){const i=ru(r,n.values,e);if(n.inclusive?i<0:i<=0)return!1}if(s){const i=ru(r,s.values,e);if(s.inclusive?i>0:i>=0)return!1}return!0})}function Rd(t,e){return t.filter(n=>e.every(s=>s.field===Vt||Wo(n.data,s.field)!==void 0))}function Ld(t){return(e,n)=>{for(const s of t){const r=Qt(Yi(e,s.field),Yi(n,s.field));if(r!==0)return s.direction==="desc"?-r:r}return 0}}function VS(t,e){return e.length===0?t:Rd(t,e).sort(Ld(e))}function GS(t){const e=[...t.orders],n=new Set(e.map(r=>r.field)),s=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const r of t.filters)for(const i of Od(r))i!==Vt&&!n.has(i)&&(n.add(i),e.push({field:i,direction:s}));return n.has(Vt)||e.push({field:Vt,direction:s}),e}function iu(t,e){let n=zS(t,[...e.filters]);const s=GS(e),r=e.limitCount;if(r!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return OS(Rd(n,s),r,Ld(s));if(n=VS(n,s),!!(e.start||e.end)){for(const u of[e.start,e.end])if(!!(u&&!u.fromSnapshot&&u.values.length>e.orders.length))throw new ws({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=WS(n,s,e.start,e.end)}const a=e.limitCount;if(a!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ws({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});n=a===0?[]:n.slice(-a)}else n=n.slice(0,a);return n}function HS(t,e){if(!t)return null;const n=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],s=new Set,r=t.service.match.children.flatMap(o=>{const a=ZS(o,e,n,s);return a?[a]:[]});if(r.length===0)return null;const i=o=>o?.filter(a=>s.has(a.name));return{...t,functions:i(t.functions),service:{...t.service,functions:i(t.service.functions),match:{...t.service.match,functions:i(t.service.match.functions)??[],children:r}}}}function KS(t,e){const[n,s,r,...i]=t.path.segments;return n?.type!=="recursive"?null:s?s.type==="literal"&&s.value===e&&r?.type==="wildcard"&&i.length===0?new Set([n.name,r.name]):null:new Set([n.name])}function ZS(t,e,n,s){const r=KS(t,e);if(!r)return null;const i=Jl([...n,...t.functions]),o=t.allows.filter(a=>{if(!a.operations.some(u=>u==="list"||u==="read"))return!1;const c=Ql(a.condition,r,i.functions,i.ambiguousNames);if(c.pathInvariant)for(const u of c.requiredFunctions)s.add(u);return c.pathInvariant});return o.length===0?null:{...t,functions:t.functions.filter(a=>s.has(a.name)),allows:o,children:[]}}function JS(t){return ed(t)}class QS{events;rules;simulator;host;clock;constructor(e,n,s,r,i=new Pt){this.events=e,this.rules=n,this.simulator=s,this.host=r,this.clock=i}authorize(e){const{path:n,auth:s,constraints:r,origin:i,triggeredBy:o}=e,a=JS(r),c={...e.bypassRules?{admin:!0}:{},...a?{query:a}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,l=e.timing?.requestTime??(e.bypassRules?void 0:ve.fromMillis(this.clock.now())),d=e.timing?.at??this.clock.now();if(e.bypassRules)return this.emitRequest({at:d,evalMs:0,method:"list",path:n,auth:s,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!0};const f=this.rules.ast(),p=e.collectionGroup?HS(f,n):f;if(e.collectionGroup&&!p){const N=`list ${n} denied: no rule governs every '${n}' collection. A collection-group query needs a list or read rule at match /{path=**}/${n}/{id} or match /{document=**} whose condition reads no path binding`;this.emitRequest({at:d,evalMs:0,method:"list",path:n,auth:s,result:"deny",debugMessages:[N],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}});const B=me("permission-denied",N,{request:{method:"list",path:n,auth:s},query:r});return this.emitUserDenial(i,B),{allowed:!1,error:B}}const h=`${n}/__listPlaceholder__`,m=performance.now(),g=Yl(p,h,s,r,this.rules.source);if(g.kind==="unprovable")return this.denyQuery(e,g,d,performance.now()-m,u);const y=g.kind==="provable"?g.evaluationAst:p,w=Pr(this.host.state,{method:"list",path:h,auth:s},l);this.applyProof(w,g,r);const v=N=>this.host.state.get(N),E=y?this.simulator.simulateParsed(y,this.rules.source,[w],{getDoc:v,sourceMap:this.rules.sourceMap(),skipQueryProof:!0}):this.simulator.simulate(this.rules.source,[w],{getDoc:v}),I=performance.now()-m;if(!E.success)return this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${E.error.message}`],origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!1,error:me("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:s}})};const j=E.data.results[0],W=this.rules.captureEvidence(j,"query-residual"),V=Ee(j);if(j.state==="UNSUPPORTED")throw this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"unsupported",rulesEvidence:W,debugMessages:V,origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),new $n(Pn("list",n,V),"list",n,V);return j.state!=="PASSED"?this.denyQuery(e,g,d,I,u,{reasons:V,rule:Jt(j),evidence:W}):(this.emitRequest({at:d,evalMs:I,method:"list",path:n,auth:s,result:"allow",debugMessages:V,evaluatedRule:Jt(j),rulesEvidence:W,origin:i,...u?{detail:u}:{},...o?{triggeredBy:o}:{}}),{allowed:!0})}denyQuery(e,n,s,r,i,o={reasons:[]}){const{reasons:a,rule:c}=o,u=n.kind==="no-rule"?[]:n.failures,l=u.find(v=>v.kind!=="constraints-not-satisfied")??u[0],d={kind:l?.kind??(n.kind==="no-rule"?"no-rule":"residual-denied"),failures:u,query:e.activityQuery??(e.execution?DS(e.execution):void 0)},f=l?`list ${e.path} denied: Pyric found the query statically unprovable — ${l.reason}`:`list ${e.path} denied by rules`,p=l?[f,...a.filter(v=>!v.startsWith("No allow rules found"))]:a,h=l?$i(l.residual):void 0,m={path:e.path,auth:e.auth,constraints:e.constraints},g=l?td(m):void 0,b=l?Jb(m):void 0,y=h&&b?`${h}
|
|
1723
1723
|
|
|
1724
|
-
${b}`:h??b,w=me("permission-denied",f,{request:{method:"list",path:e.path,auth:e.auth},query:e.constraints,queryProof:d,...y?{remediation:y}:{},...g?{repro:g}:{},...l?.rule||c?{rule:l?.rule??c}:{}});return this.emitRequest({at:s,evalMs:r,method:"list",path:e.path,auth:e.auth,result:"deny",debugMessages:p,queryProof:d,rulesEvidence:this.rules.captureQueryEvidence(d,o.evidence),...c?{evaluatedRule:c}:{},origin:e.origin,...i?{detail:i}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}}),this.emitUserDenial(e.origin,w),{allowed:!1,error:w}}applyProof(e,n,s){n.kind==="provable"&&(e.resource=n.syntheticResource),(s.limit!=null||s.offset!=null||s.orderBy!=null)&&(e.query={...s.limit!=null?{limit:s.limit}:{},...s.offset!=null?{offset:s.offset}:{},...s.orderBy!=null?{orderBy:s.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitUserDenial(e,n){e==="user"&&this.events.denial.emit(n)}}class VS{events;triggerScope;rules;simulator;host;clock;operationReader;listAuthorizer;constructor(e,n,s,r,i,o,a=new Pt){this.events=e,this.triggerScope=n,this.rules=s,this.simulator=r,this.host=i,this.clock=a,this.operationReader=new wS(e,s,r,i,o,a),this.listAuthorizer=new WS(e,s,r,i,a)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,n,s=!1){if(s){const v=this.state.get(e);return this.emitRequest({at:this.clock.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:v,exists:v!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:v}}const r=ve.fromMillis(this.clock.now()),i=Pr(this.state,{method:"get",path:e,auth:n},r),o=this.clock.now(),a=performance.now(),c=kd(this.rules,this.simulator,[i],{getDoc:v=>this.state.get(v)}),u=performance.now()-a;if(!c.success)return this.emitRequest({at:o,evalMs:u,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:me("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const l=c.data.results[0],d=this.rules.captureEvidence(l);if(l.state==="UNSUPPORTED")throw this.emitRequest({at:o,evalMs:u,method:"get",path:e,auth:n,result:"unsupported",rulesEvidence:d,debugMessages:Ee(l),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new $n(Pn("get",e,Ee(l)),"get",e,Ee(l));const f=l.state==="PASSED",p=this.state.get(e),h=Jt(l);let m="deny";f&&(m="allow");const g=p!==null,b={at:o,evalMs:u,method:"get",path:e,auth:n,result:m,debugMessages:Ee(l),evaluatedRule:h,rulesEvidence:d,origin:"listener",resourceBefore:{data:p,exists:g}},y=this.triggerScope.current();if(y!==void 0&&(b.triggeredBy=y),this.emitRequest(b),f===!1){const v={request:{method:"get",path:e,auth:n},resource:{data:p,exists:g}};return h!==void 0&&(v.rule=h),{allowed:!1,error:me("permission-denied",`get ${e} denied by rules`,v)}}return{allowed:!0,data:p}}silentReadCollection(e,n,s,r=!1){if(typeof s=="function")return{allowed:!1,error:me("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=s?tu(s.execution):void 0,o=i?nu(i):{},a={requestTime:ve.fromMillis(this.clock.now()),at:this.clock.now()},c=this.triggerScope.current(),u=eu(e),l=this.listAuthorizer.authorize({path:u.kind==="collection"?u.path:u.collectionId,collectionGroup:u.kind==="collection-group",auth:n,constraints:o,bypassRules:r,...s?.activityQuery?{activityQuery:s.activityQuery}:{},execution:i,origin:"listener",...c?{triggeredBy:c}:{},timing:a});if(!l.allowed)return l;const d=su(this.state,u);return{allowed:!0,docs:i?iu(d,i):d}}runQuery(e){const n=eu(e.scope),s=tu(e.execution),r=e.auth,i=e.bypassRules,o=e.activityQuery,a=su(this.state,n),c=n.kind==="collection"?n.path:n.collectionId,u=nu(s),l=this.listAuthorizer.authorize({path:c,collectionGroup:n.kind==="collection-group",auth:r,constraints:u,bypassRules:i,...o!==void 0?{activityQuery:o}:{},execution:s,origin:"user"});return l.allowed?{allowed:!0,docs:iu(a,s)}:l}}const ou="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",au=20;function GS(){const t=new Uint8Array(au);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<au;n++)e+=ou[t[n]%ou.length];return e}function Od(t,e=""){const n=[],s=new WeakSet;return r(t,e),n;function r(i,o){if(i==null||typeof i!="object"||s.has(i)||(s.add(i),Vv(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,l)=>r(u,`${o}[${l}]`));return}const a=i,c=HS(a);if(c){n.push({field:o,kind:c});return}for(const[u,l]of Object.entries(a)){const d=o?`${o}.${u}`:u;r(l,d)}}}function HS(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}lw();class KS{host;rules;simulator;eventLog;events;triggerScope;clock;constructor(e,n,s,r,i,o,a=new Pt){this.host=e,this.rules=n,this.simulator=s,this.eventLog=r,this.events=i,this.triggerScope=o,this.clock=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitWrite(e){if(!this.events.write.hasSubscribers)return;const s={kind:"write",id:ns().replace(/^req-/,"wr-"),at:this.clock.now(),method:e.method,path:e.path,auth:null,priorState:e.priorState,nextState:e.nextState,requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos}},{auth:r}=e;r!==null&&(s.auth={uid:r.uid},r.token&&(s.auth.token=r.token)),e.data!==void 0&&(s.data=e.data),e.updateMask!==void 0&&(s.updateMask=e.updateMask);const{merge:c}=e;c===!0?s.merge=!0:c!==void 0&&c!==!1&&(s.merge={mergeFields:[...c.mergeFields]}),e.groupId!==void 0&&(s.groupId=e.groupId),e.groupKind!==void 0&&(s.groupKind=e.groupKind),e.sentinels!==void 0&&e.sentinels.length>0&&(s.sentinels=e.sentinels),e.autoId!==void 0&&(s.autoId=e.autoId),e.detail!==void 0&&(s.detail=e.detail),this.events.write.emit({...s,...e.provenance})}capturePriors(e){const n={};for(const s of e){const r=this.state.get(s),i=r!==null;n[s]=i?{...r}:null}return n}captureEvidence(e){return this.rules.captureEvidence(e)}runSimulate(e,n,s){return Ed(this.state,this.rules,this.simulator,e,n,s)}resolvePriorDocumentState(e,n,s){return n.has(e)?n.get(e)??null:s.exists(e)?s.get(e)??null:null}computeProjectedUpdate(e,n){return Nr(e??{},n??{})}computeProjectedOverwrite(e,n){return Mr(e??{},n??{})}buildBatchProjection(e,n=new Map){for(const s of e){if(s.method==="set"){n.set(s.path,rn(s.data??{}).writes);continue}if(s.method==="delete"){n.set(s.path,null);continue}const o=this.resolvePriorDocumentState(s.path,n,this.state);if(s.method==="update"){const c=this.computeProjectedUpdate(o,s.data);n.set(s.path,c)}else{const c=this.computeProjectedOverwrite(o,s.data);n.set(s.path,c)}}return n}buildTestCase(e,n){return Pr(this.state,e,n)}notify(e,n){this.triggerScope.run({method:e,path:n[0]??""},()=>this.host.notifyListenersForPaths(new Set(n),{method:e,paths:n}))}}class Td{runtime;constructor(e){this.runtime=e}prepare(e,n){const s=ve.fromMillis(this.runtime.clock.now()),r=[],i=new Map;for(const[o,a]of e.entries())try{if(a.method==="update"&&i.get(a.path)===null)throw new Error(`Cannot delete then update document '${a.path}' in the same atomic write.`);const u=a.data!==void 0;let l=a.data;if(u){const f=i.has(a.path);let p;f?p=i.get(a.path)??null:p=this.runtime.state.get(a.path),l=ht({...a.data},{path:a.path,method:a.method,prior:p,serverTime:s});const{merge:h}=a;if(h!==void 0&&h!==!1){const b=h===!0?void 0:h.mergeFields;l=Mr(p??{},l,b)}}const d={method:a.method,path:a.path,data:l};r.push(d),this.runtime.buildBatchProjection([d],i)}catch(c){const u=c.message,l=me("invalid-argument",u),d=n.snapshot[a.path]??null,f={at:this.runtime.clock.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:n.auth,result:"deny",debugMessages:[`Write preparation error: ${u}`],resourceBefore:{data:d,exists:d!==null},origin:n.origin,groupId:n.groupId};return this.includesRequestData(n,a)&&Object.assign(f,Xn(a,a.preData)),n.bypassRules===!0&&(f.detail={admin:!0}),n.provenance!==void 0&&(f.provenance=n.provenance),{index:o,input:a,message:u,error:l,request:f}}return{context:n,inputs:e,resolvedOps:r,serverTime:s}}evaluateAndApply(e,n){const{context:s,resolvedOps:r,serverTime:i}=e,o=this.runtime.buildBatchProjection(r,n),a=e.inputs.map(f=>{if(f.method!=="set")return f;const h=o.get(f.path)===null;let m;return h?m="delete":m=this.runtime.state.get(f.path)!==null?"update":"create",{...f,ruleMethod:m}}),c=r.map((f,p)=>{const h=this.runtime.buildTestCase({method:a[p].ruleMethod,path:f.path,auth:s.auth,data:f.data},i);return h.data=o.get(f.path)??void 0,h}),u=[];let l=!0;for(const[f]of r.entries()){const p=a[f],h=s.snapshot[p.path]??null,m=this.runtime.clock.now(),g=performance.now(),b=this.runtime.runSimulate([c[f]],s.bypassRules,o),y=performance.now()-g;if(!b.success){const N=me("invalid-argument",b.error.message);u.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[b.error.message],error:N,request:this.request(e,p,h,m,y,"deny",[`Simulation error: ${b.error.message}`])}),l=!1;continue}const v=b.data.results[0],E=Ee(v);if(v.state==="UNSUPPORTED"){const N=this.request(e,p,h,m,y,"unsupported",E);throw N.rulesEvidence=this.runtime.captureEvidence(v),this.runtime.emitRequest(N),new $n(Pn(p.ruleMethod,p.path,E),p.ruleMethod,p.path,E)}const j=v.state==="PASSED";let W="deny";j&&(W="allow");const V={path:p.path,method:p.ruleMethod,allowed:j,debugMessages:E,request:this.request(e,p,h,m,y,W,E)};if(V.request.rulesEvidence=this.runtime.captureEvidence(v),!j){const N=Jt(v),B=h!==null,G={request:{method:p.ruleMethod,path:p.path,auth:s.auth},resource:{data:h,exists:B}};this.includesRequestData(s,p)&&Object.assign(G.request,Xn(p,p.preData)),N!==void 0&&(G.rule=N),V.error=me("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,G),this.runtime.emitDenial(V.error),l=!1}u.push(V)}let d=null;if(l){const f=this.runtime.state.applyBatch(r);if(!f.success){l=!1;const h=f.errors?.[0];if(h!==void 0){const b=r[h.index]?.method==="create";d=me(b?"already-exists":"not-found",h.error);const y=u[h.index];y!==void 0&&(y.allowed=!1,y.error=d)}}}return{...e,inputs:a,outcomes:u,allowed:l,structuralError:d}}emitAndNotify(e){const{context:n,inputs:s,outcomes:r,serverTime:i}=e;e.allowed&&this.runtime.notify(n.origin,s.map(o=>o.path));for(const[o,a]of r.entries()){const c=s[o],u=e.allowed&&a.allowed,l=n.snapshot[c.path]??null;if(u){const d=c.ruleMethod==="delete";a.request.resourceAfter=d?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}}else a.request.resourceAfter={data:l,exists:l!==null};if(this.runtime.emitRequest(a.request),u){const f=c.preData!==void 0?Xn(c,c.preData):void 0,p=f?Od(f.resourceData):void 0,h=c.ruleMethod==="delete",m={method:c.ruleMethod,path:c.path,auth:n.auth,priorState:l,nextState:h?null:this.runtime.state.get(c.path),groupId:n.groupId,groupKind:n.origin,requestTime:i,merge:c.merge};!h&&f!==void 0&&(m.data=f.resourceData,f.updateMask!==void 0&&(m.updateMask=f.updateMask)),p!==void 0&&p.length>0&&(m.sentinels=p),n.bypassRules===!0&&(m.detail={admin:!0}),n.provenance!==void 0&&(m.provenance=n.provenance),this.runtime.emitWrite(m)}}}request(e,n,s,r,i,o,a){const{context:c}=e,u={at:r,evalMs:i,method:n.ruleMethod,path:n.path,auth:c.auth,result:o,debugMessages:a,resourceBefore:{data:s,exists:s!==null},origin:c.origin,groupId:c.groupId};return this.includesRequestData(c,n)&&Object.assign(u,Xn(n,n.preData)),c.bypassRules===!0&&(u.detail={admin:!0}),c.provenance!==void 0&&(u.provenance=c.provenance),u}includesRequestData(e,n){return n.preData!==void 0&&(e.origin==="batch"||n.ruleMethod!=="delete")}}class ZS{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Td(e)}batch(e,n,s){const r=this.runtime.capturePriors(e.map(w=>w.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,o=e.map(w=>{const{method:v}=w,E=v==="set";let I;return E?I=r[w.path]!==null?"update":"create":I=v,{...w,ruleMethod:I,preData:w.data}}),a=this.pipeline.prepare(o,{origin:"batch",groupId:i,auth:n,bypassRules:s,snapshot:r}),u=n!==null?{uid:n.uid}:null;if(!("resolvedOps"in a)){const w=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:u,allowed:!1,operations:e.map(v=>({method:v.method,path:v.path,data:v.data,allowed:!1})),debugMessages:[`Write preparation error on '${a.input.path}': ${a.message}`]});return this.runtime.emitRequest(a.request),{allowed:!1,results:e.map(v=>{const E={path:v.path,allowed:!1,debugMessages:[a.message]};return v.path===a.input.path&&(E.error=a.error),E}),event:w,error:a.error}}const d=this.pipeline.evaluateAndApply(a),f=d.outcomes.map(w=>{const v={path:w.path,allowed:w.allowed,debugMessages:w.debugMessages};return w.error!==void 0&&(v.error=w.error),v}),{allowed:p}=d,h=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:u,allowed:p,priorDocs:p?r:void 0,operations:d.resolvedOps.map((w,v)=>({method:w.method,path:w.path,data:w.data,allowed:f[v]?.allowed??!1})),debugMessages:p?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(d);let m;!p&&(m=d.structuralError??f.find(w=>w.error)?.error??me("permission-denied","Batch denied"));const b={allowed:p,results:f,event:h};return m!==void 0&&(b.error=m),b}}const cu="Firestore transactions require all reads to be executed before all writes.";class JS extends Error{simError;constructor(){super(cu),this.name="ReadAfterWriteError",this.simError=me("failed-precondition",cu)}}class uu extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class QS extends Error{simError=me("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class ci extends Error{code;simError;constructor(e){super(e.message),this.name="TransactionReadDeniedError",this.code=e.code,this.simError=e}}class YS{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,n=()=>0){this.versionReader=n,this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);!this.readVersions.has(e)&&this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:n});const i=n===null?null:vs(n);return{path:e,exists:i!==null,data:()=>i===null?void 0:i}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n,s){const r={method:"set",path:e,data:n};if(s!==void 0){const o=typeof s=="object";r.merge=o?{mergeFields:[...s.mergeFields]}:s}this.queue(r)}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){const{data:n}=e;n!==void 0&&(e.data=vs(n)),this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new JS}}class XS{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Td(e)}transaction(e,n){return this.runAttempt(e,n,1)}runAttempt(e,n,s){const r=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),o=new Map(Object.keys(r).map(h=>[h,this.runtime.state.version(h)])),a=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,c=new Map;let u;const l=h=>{const m=r[h]??null;if(n.bypassRules!==!0){const b=this.evaluateTransactionRead(h,m,n,a,c);if(b!==null)throw u=b,new ci(b)}return m},d=new YS(l,h=>{const m=o.get(h);if(m!==void 0)return m;const b=this.runtime.state.version(h);return b<=i?b:-1});let f;try{f=e(d)}catch(h){if(h instanceof ci)return this.buildReadDeniedResult(d,n,h.simError);if(u!==void 0)return this.buildReadDeniedResult(d,n,u);throw this.logAbortedTransaction(d,n.auth,h),h}if(f!==null&&typeof f?.then=="function")return f.then(h=>{try{return this.commitTransaction(d,r,n,h,i,a,c,u)}catch(m){return this.retryOrThrow(m,e,n,s)}},h=>{if(h instanceof ci)return this.buildReadDeniedResult(d,n,h.simError);if(u!==void 0)return this.buildReadDeniedResult(d,n,u);throw this.logAbortedTransaction(d,n.auth,h),h});try{return this.commitTransaction(d,r,n,f,i,a,c,u)}catch(h){return this.retryOrThrow(h,e,n,s)}}retryOrThrow(e,n,s,r){if(!(e instanceof uu))throw e;const o=s.maxAttempts??5;if(r>=o)throw new QS;return this.runAttempt(n,s,r+1)}commitTransaction(e,n,s,r,i,o,a,c){if(c!==void 0)return this.buildReadDeniedResult(e,s,c);const{reads:l,writes:d,readVersions:f}=e.consume();for(const[C,S]of f)if(this.runtime.state.version(C)!==S)throw new uu;if(s.bypassRules!==!0&&l.length>0&&this.runtime.state.currentVersion()!==i){const C=new Map(a);for(const S of l){const x=this.runtime.state.get(S.path),F=this.evaluateTransactionRead(S.path,x,s,o,C);if(F!==null)return this.buildReadDeniedResult(e,s,F,l)}}const h=s.auth;if(d.length===0){const C=h!==null,S=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:C?{uid:h.uid}:null,allowed:!0,reads:l.map(x=>({path:x.path,data:x.data})),operations:[],snapshot:n,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...l],writes:[],returnValue:r,event:S}}const g=Object.fromEntries(d.map(C=>[C.path,n[C.path]??null])),b=d.map(C=>{const{method:S}=C,x=S==="set";let F;return x?F=this.runtime.state.get(C.path)!==null?"update":"create":F=S,{...C,ruleMethod:F,preData:C.data}}),y=this.pipeline.prepare(b,{origin:"transaction",groupId:o,auth:h,bypassRules:s.bypassRules,provenance:s.provenance,snapshot:g});if(!("resolvedOps"in y)){const C=h!==null,S=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:C?{uid:h.uid}:null,allowed:!1,aborted:!0,error:{name:"FirebaseError",message:y.message,code:y.error.code},reads:l.map(x=>({path:x.path,data:x.data})),operations:d.map(x=>({method:x.method,path:x.path,data:x.data,allowed:!1})),debugMessages:[`Write preparation error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...l],writes:this.summarizeWrites(b.map((x,F)=>{const D=F===y.index,H={path:x.path,method:x.ruleMethod,allowed:!1,debugMessages:D?[y.message]:[]};return D&&(H.error=y.error),H})),returnValue:r,event:S,error:y.error}}const v=this.pipeline.evaluateAndApply(y,a),E=v.outcomes.map(C=>{const S={path:C.path,method:C.method,allowed:C.allowed,debugMessages:C.debugMessages};return C.error!==void 0&&(S.error=C.error),S}),{allowed:I}=v,j=h!==null,W=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:j?{uid:h.uid}:null,allowed:I,reads:l.map(C=>({path:C.path,data:C.data})),operations:v.resolvedOps.map((C,S)=>({method:C.method,path:C.path,data:C.data,allowed:E[S]?.allowed??!1})),snapshot:I?n:void 0,debugMessages:I?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let V;!I&&(V=v.structuralError??E.find(C=>C.error)?.error??me("permission-denied","Transaction denied"));const N={allowed:I,reads:[...l],writes:this.summarizeWrites(E),returnValue:r,event:W};return V!==void 0&&(N.error=V),s.readOnly===!0&&e.hadWrites()&&(N.readOnlyViolation=!0),N}summarizeWrites(e){const n=new Map;for(const s of e){const r=n.get(s.path);if(r===void 0){n.set(s.path,s);continue}const o=r.allowed&&s.allowed,a={path:s.path,method:s.method,allowed:o,debugMessages:[...r.debugMessages,...s.debugMessages]},c=r.error??s.error;c!==void 0&&(a.error=c),n.set(s.path,a)}return[...n.values()]}evaluateTransactionRead(e,n,s,r,i){const o=this.runtime.clock.now(),a=performance.now(),c=this.runtime.buildTestCase({method:"get",path:e,auth:s.auth}),u=this.runtime.runSimulate([c],s.bypassRules,i),l=performance.now()-a,d=n!==null;if(!u.success){const j={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"deny",debugMessages:[`Simulation error: ${u.error.message}`],resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r};return s.provenance!==void 0&&(j.provenance=s.provenance),this.runtime.emitRequest(j),me("invalid-argument",u.error.message)}const p=u.data.results[0],h=Ee(p);if(p.state==="UNSUPPORTED"){const j={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"unsupported",debugMessages:h,resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r,rulesEvidence:this.runtime.captureEvidence(p)};throw s.provenance!==void 0&&(j.provenance=s.provenance),this.runtime.emitRequest(j),new $n(Pn("get",e,h),"get",e,h)}if(p.state==="PASSED")return null;const b={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"deny",debugMessages:h,resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r,rulesEvidence:this.runtime.captureEvidence(p)};s.provenance!==void 0&&(b.provenance=s.provenance),this.runtime.emitRequest(b);const w=Jt(p),v={request:{method:"get",path:e,auth:s.auth},resource:{data:n,exists:d}};w!==void 0&&(v.rule=w);const I=me("permission-denied",`get ${e} denied by rules`,v);return this.runtime.emitDenial(I),I}buildReadDeniedResult(e,n,s,r){const i=r??e.consume().reads,o=n.auth,a=o!==null,c=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:a?{uid:o.uid}:null,allowed:!1,reads:i.map(u=>({path:u.path,data:u.data})),operations:[],debugMessages:["Transaction rolled back — read denied by rules"]});return{allowed:!1,reads:[...i],writes:[],returnValue:void 0,event:c,error:s}}logAbortedTransaction(e,n,s){const r=s,{reads:i}=e.consume(),o=n!==null,a={name:s.name,message:s.message};r.code!==void 0&&(a.code=String(r.code)),this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:o?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:i.map(u=>({path:u.path,data:u.data})),error:a,debugMessages:[`Transaction aborted: ${s.message}`]})}}class e0{runtime;batches;transactions;constructor(e,n,s,r,i,o,a=new Pt){this.runtime=new KS(e,n,s,r,i,o,a),this.batches=new ZS(this.runtime),this.transactions=new XS(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,n,s,r){if(r!==void 0&&r!==!1&&(e==="create"||e==="update")){const i=r===!0?void 0:r.mergeFields;return this.runtime.state.setMerge(n,s??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(n,s??{});return i.success?null:me("already-exists",i.error??`Document '${n}' already exists`)}case"update":{const i=this.runtime.state.update(n,s??{});return i.success?null:me("not-found",i.error??`Document '${n}' does not exist`)}case"set":return this.runtime.state.set(n,s??{}),null;case"delete":return this.runtime.state.delete(n),null;default:return null}}execute(e){const{method:n,path:s,auth:r,data:i,autoId:o,requestTime:a,merge:c,bypassRules:u}=e,l=i?Xn(e,i):void 0,d=u?{admin:!0}:void 0,f=this.runtime.capturePriors([s]),p=a??ve.fromMillis(this.runtime.clock.now());let h;try{h=i&&ht({...i},{path:s,method:n,prior:this.runtime.state.get(s),serverTime:p}),n==="update"&&h&&yw(h)}catch(B){const G=B.message,C=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:i,allowed:!1,priorDocs:f,debugMessages:[`FieldValue resolve error: ${G}`]});return this.runtime.emitRequest({at:this.runtime.clock.now(),evalMs:0,method:n,path:s,auth:r,result:"deny",debugMessages:[`FieldValue resolve error: ${G}`],...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[G],event:C,error:me("invalid-argument",G)}}const m=this.runtime.buildTestCase({...e,data:h},p),g=this.runtime.clock.now(),b=performance.now(),y=this.runtime.runSimulate([m],u),w=performance.now()-b;if(!y.success){const B=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:h,allowed:!1,priorDocs:f,debugMessages:[`Simulation error: ${y.error.message}`]});return this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:"deny",debugMessages:[`Simulation error: ${y.error.message}`],...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[y.error.message],event:B,error:me("invalid-argument",y.error.message)}}const v=y.data.results[0],E=this.runtime.captureEvidence(v);if(v.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:"unsupported",rulesEvidence:E,debugMessages:Ee(v),...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),new $n(Pn(n,s,Ee(v)),n,s,Ee(v));let I=v.state==="PASSED",j=null;I&&(j=this.applyWrite(n,s,h,c),j&&(I=!1));const W=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:h,allowed:I,priorDocs:I?f:void 0,debugMessages:Ee(v)}),V={allowed:I,debugMessages:Ee(v),event:W};if(I===!1){let B=!1;if(j!==void 0&&j!==null&&(B=!0),B)V.error=j;else{let C=null;const S=f[s];S!==void 0&&(C=S);let F=n;n==="set"&&(C!==null?F="update":F="create");const H=Jt(v),ae={request:{method:F,path:s,auth:r},resource:{data:C,exists:C!==null}};i!==void 0&&Object.assign(ae.request,l),H!==void 0&&(ae.rule=H),V.error=me("permission-denied",`${n} ${s} denied by rules`,ae),this.runtime.emitDenial(V.error)}}I&&this.runtime.notify(n,[s]);const T=f[s]??null,N=I?this.runtime.state.get(s):T;if(this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:I?"allow":"deny",debugMessages:Ee(v),evaluatedRule:Jt(v),rulesEvidence:E,...l??{},resourceBefore:{data:T,exists:T!==null},...n!=="delete"?{resourceAfter:{data:N,exists:N!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),I){const B=l?Od(l.resourceData):void 0,G=o&&n==="create"?s.split("/").pop():void 0;this.runtime.emitWrite({method:n,path:s,auth:r,...n!=="delete"&&l?{data:l.resourceData,...l.updateMask?{updateMask:l.updateMask}:{}}:{},merge:c,priorState:T,nextState:n==="delete"?null:N,...B&&B.length>0?{sentinels:B}:{},...G?{autoId:G}:{},requestTime:p,...d?{detail:d}:{}})}return V}createWithAutoId(e,n,s,r){const i=e.endsWith("/")?e.slice(0,-1):e,o=GS(),a=`${i}/${o}`,c=this.execute({method:"create",path:a,auth:s,data:n,autoId:!0,bypassRules:r});return{path:a,result:c}}batch(e,n,s){return this.batches.batch(e,n,s)}transaction(e,n){return this.transactions.transaction(e,n)}}class lu{state;stateChanges=new Set;onStateChange(e){return this.stateChanges.add(e),()=>{this.stateChanges.delete(e)}}stateChanged=e=>{for(const n of this.stateChanges)n(e)};eventLog;history;simulator;rules;seedSnapshot;events=new xw;triggerScope=new Cw;reads;writes;listeners;constructor(e=new Pt){this.state=new ri({},void 0,this.stateChanged),this.eventLog=new kw(e);const n=this;this.simulator=new Jb,this.rules=new bS(_w),this.reads=new VS(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return n.state}},this.eventLog,e),this.listeners=new fS(this.events,this.triggerScope,this.reads,e),this.writes=new e0({get state(){return n.state},notifyListenersForPaths:(s,r)=>n.listeners.notifyListenersForPaths(s,r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope,e),this.history=new hS(this.eventLog,{get state(){return n.state},capturePriors:s=>this.writes.capturePriors(s),applyWrite:(s,r,i,o)=>this.writes.applyWrite(s,r,i,o)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,n,s={},r=null,i,o=!1,a=!1,c){return this.listeners.addSnapshotListener(e,n,s,r,i,o,a,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear(),this.stateChanges.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new ri({},new Sw(e.baseDocuments),this.stateChanged):new ri(e.documents??{},void 0,this.stateChanged),this.stateChanged(null),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),xi(e.rules)}deployRules(e){const n=xi(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),n}reevaluateLiveListeners(e,n){this.listeners.reevaluateLiveListeners(e,n)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,n){this.state.set(e,n??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:n.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,n,s,r){return this.writes.createWithAutoId(e,n,s,r)}batch(e,n,s){return this.writes.batch(e,n,s)}transaction(e,n){return this.writes.transaction(e,n)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventRetention(){return this.eventLog.getRetention()}getEventCount(){return this.history.getEventCount()}}function t0(t,e,n){const s=t.execute({method:"set",path:e,data:n??{},auth:null,bypassRules:!0});s.allowed||Rd(s,e)}function n0(t,e){if(t.getDocument(e)===null)return{deleted:!1};const s=t.execute({method:"delete",path:e,auth:null,bypassRules:!0});return s.allowed||Rd(s,e),{deleted:!0}}function Rd(t,e){const n=me("failed-precondition",`admin write to '${e}' was not applied: ${t.debugMessages.join("; ")}`);throw new ws(t.error??n)}const s0=/password|credential|secret|token|authorization|cookie|api[-_]?key/i;function r0(t){return t.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,"[redacted token]").replace(/((?:password|api[-_]?key|access[-_]?token|refresh[-_]?token|secret)["']?\s*[:=]\s*["']?)[^\s"',;}]+/gi,"$1[redacted]")}function i0(t,e=16384){try{const n=JSON.stringify(t,(s,r)=>s0.test(s)?"[redacted]":typeof r=="string"?r0(r):r,2);return n===void 0?void 0:{text:n.slice(0,e),truncated:n.length>e}}catch{return}}function eo(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function xs(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function J0(t){const e=xs(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function du(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Vo(t,e){const n=t?.operationContext?.source??t?.actor,s=e?.operationContext?.source??e?.actor;return xs({source:du(t)??du(e)??n??s??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function Ld(t){return Vo(void 0,t)}function o0(t){if(t.result==="deny")return!0;if(!("error"in t)||!t.error||typeof t.error!="object")return!1;const e=t.error.code;if(typeof e!="string")return!1;const n=e.toLowerCase();return n==="permission_denied"||n==="permission-denied"||n==="auth/permission-denied"}function Nd(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:o0(t)?{kind:"evaluated",verdict:"deny"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.kind==="listener"?t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function a0(t){if(t===null)return null;let e;return t.token!==void 0&&(e=Md(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function Md(t){const e={};for(const[n,s]of Object.entries(t))e[n]=Go(s);return Object.freeze(e)}function Go(t){return Array.isArray(t)?Object.freeze(t.map(Go)):t&&typeof t=="object"?Md(t):t}function c0(t){if(eo(t))return t;if(!(t.kind==="service_mutation"&&t.service==="auth"))return null;const n=s=>{const r=i0(s);if(!(!r||r.truncated))return JSON.parse(r.text)};return{kind:"operation",id:t.id,at:t.at,service:"auth",method:t.op,path:t.path,auth:t.auth,origin:"user",result:"not-applicable",rulesDisposition:{kind:"not-evaluated",reason:"not-a-rules-operation"},operationContext:Ld(t),detail:{transition:t.op,evidence:n(t.detail)},resourceBefore:t.before===void 0?void 0:{data:n(t.before),exists:!0},resourceAfter:t.after===void 0?void 0:{data:n(t.after),exists:!0}}}function Q0(t){const e=c0(t);if(!e)return null;let n="listen",s;e.kind==="request"||e.kind==="operation"?(n=e.method,e.path!==void 0&&(s=e.path)):e.kind==="listener"&&(n="listen",e.target.path!==void 0&&(s=e.target.path));let r="firestore";e.service!==void 0&&(r=e.service);let i;return"queryProof"in e&&e.queryProof&&(i=Go(e.queryProof)),Object.freeze({id:e.kind==="operation"?e.observation?.id??e.id:e.id,at:e.kind==="operation"?e.observation?.startedAt??e.at:e.at,...e.kind==="operation"&&e.observation?{observation:e.observation}:{},eventKind:e.kind,service:r,method:n,...s===void 0?{}:{path:s},auth:a0(e.auth),result:e.result,context:Ld(e),rules:Object.freeze({...Nd(e)}),queryProof:i})}function fu(t){if(t===null)return null;if(t.tenant===void 0)return t.token===void 0?{uid:t.uid}:{uid:t.uid,token:structuredClone(t.token)};const e=t.token!==void 0?structuredClone(t.token):{},n=e.firebase;let s;if(typeof n=="object"&&n!==null&&!Array.isArray(n)){const r=n;s={...r,tenant:r.tenant!==void 0?r.tenant:t.tenant}}else s={tenant:t.tenant};return e.firebase=s,{uid:t.uid,tenant:t.tenant,token:e}}function hu(t){if(t===null)return{mode:"anon"};const e={mode:"as",uid:t.uid};return t.token!==void 0&&(e.token=t.token),t.tenant!==void 0&&(e.tenant=t.tenant),e}class Fr{sandbox;auth;operationContext;constructor(e,n,s){this.sandbox=e,Sr(n);const r=fu(n);this.auth=r,this.operationContext=xs(s??{source:{kind:"unattributed"},authLens:hu(r)})}withAuth(e){Sr(e);const n=fu(e);return new Fr(this.sandbox,n,{source:this.operationContext.source,authLens:hu(n),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Y0(t,e){return new Fr(t.sandbox,t.auth,e)}function Sr(t){if(t===null)return;if(t===void 0)throw new ct({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
|
|
1725
|
-
`)});if(typeof t!="object")throw new ct("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new ct("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("tenant"in e&&e.tenant!==void 0&&(typeof e.tenant!="string"||e.tenant.length===0))throw new ct("invalid-argument","withAuth() requires `tenant` (when present) to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new ct("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}class zt{bytes;constructor(e){this.bytes=e,bs(this,fw(e)),Dn(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new zt(e.slice()))}static fromBase64String(e){const n=atob(e),s=Uint8Array.from(n,r=>r.charCodeAt(0));return new zt(s)}static fromUint8Array(e){return new zt(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof zt&&this.bytes.length===e.bytes.length&&this.bytes.every((n,s)=>n===e.bytes[s])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return zt.fromBase64String(n.bytes)}}class _n{lat;lng;constructor(e,n){if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");bs(this,gr("geo-point",String(e),"\0",String(n))),Dn(this,Object.freeze({type:"geo-point",latitude:e,longitude:n}),()=>new _n(e,n))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof _n&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new _n(n.latitude,n.longitude)}}class Tt{_values;constructor(e){this._values=e,Dn(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new Tt(e.slice()))}static create(e){if(!e.every(s=>typeof s=="number"))throw new TypeError("Vector values must be numbers.");return new Tt(e.slice())}toArray(){return this._values.slice()}isEqual(e){if(!(e instanceof Tt))return!1;const s=e._values;return s!==void 0&&this._values.length===s.length&&this._values.every((r,i)=>r===s[i])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(i=>typeof i=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Tt.create(n.vectorValues)}}function X0(t=[]){return Tt.create(t)}const u0=64;function Ho(t){Dd(t,0)}function Dd(t,e){if(t===null||typeof t!="object")return;const s=e+1;if(s>u0)throw new At("invalid-argument","Encoded document nesting exceeds 64 containers.");for(const i of Object.values(t))Dd(i,s)}function $d(t){if(rt(t))return t;throw new At("invalid-argument","Document data must be a plain object.")}const Ko="pyric/firestore-values/1";function Pd(t){const e=t===void 0,n=t===Ko;if(!e&&!n)throw new At("invalid-argument","Unsupported Firestore value encoding.");return n}function to(t){if(t===null||typeof t!="object")return t;if(t instanceof mt)return t.toJSON();if(t instanceof Date)return mt.fromDate(t).toJSON();if(t instanceof zt||t instanceof _n||t instanceof Tt)return t.toJSON();const a=qo(t);if(a!==void 0)return{__type:"reference",path:a};if(Array.isArray(t))return t.map(to);const l=Object.getPrototypeOf(t);if(l===Object.prototype||l===null){const f=Object.fromEntries(Object.entries(t).map(([h,m])=>[h,to(m)]));return Object.hasOwn(f,"type")||Object.hasOwn(f,"__type")||Object.hasOwn(f,"__type__")?{type:"pyric/map/1.0",fields:f}:f}return t}const jd={bytes:t=>new He(t),geoPoint:(t,e)=>new ut(t,e),reference:t=>new wt(t),timestamp:(t,e)=>new ve(t,e),vector:t=>new Ht(t)};function l0(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),s=atob(e+n),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);return r}function d0(t){const e=atob(t),n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n}function f0(t){return xn(t,!0,jd,!1)}function h0(t,e){Ho(t);const n=Pd(e);return xn(t,!0,jd,n)}function eA(t,e,n){Ho(t);const s=Pd(n);return xn(t,!0,{bytes:r=>zt.fromUint8Array(r),geoPoint:(r,i)=>new _n(r,i),reference:r=>e.create(r),timestamp:(r,i)=>new mt(r,i),vector:r=>Tt.create(r.slice())},s)}function xn(t,e,n,s){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const h=t.map(m=>xn(m,!1,n,s));return e&&bs(h,$c(t)),h}const o=t,a=h=>(e&&bs(h,$c(t)),h),c=(h,m)=>(Dn(h,Object.freeze(m),()=>h),a(h));if(o.__type__==="__vector__"&&Array.isArray(o.value)){const h=Object.freeze(o.value.slice());return c(n.vector(h),{type:"vector",values:h})}if(typeof o.__type=="string")switch(o.__type){case"timestamp":return c(n.timestamp(o.seconds,o.nanos),{type:"timestamp",seconds:o.seconds,nanoseconds:o.nanos});case"bytes":{const h=l0(o.base64);return c(n.bytes(h),{type:"bytes",values:Object.freeze(Array.from(h))})}case"latlng":return c(n.geoPoint(o.lat,o.lng),{type:"geo-point",latitude:o.lat,longitude:o.lng});case"duration":return a(new ke(o.seconds,o.nanos));case"reference":{const h=o.path;return a(n.reference(h))}case"path":return a(new nt(o.segments))}if(s&&o.type==="pyric/map/1.0"){const h=o.fields;if(h===null||typeof h!="object"||Array.isArray(h))throw new TypeError("Invalid encoded map fields.");const g=Object.fromEntries(Object.entries(h).map(([b,y])=>[b,xn(y,!1,n,s)]));return a(g)}if(typeof o.type=="string")switch(o.type){case"firestore/timestamp/1.0":{const h=o.seconds,m=o.nanoseconds;return c(n.timestamp(h,m),{type:"timestamp",seconds:h,nanoseconds:m})}case"firestore/bytes/1.0":{const h=d0(o.bytes);return c(n.bytes(h),{type:"bytes",values:Object.freeze(Array.from(h))})}case"firestore/geoPoint/1.0":return c(n.geoPoint(o.latitude,o.longitude),{type:"geo-point",latitude:o.latitude,longitude:o.longitude});case"firestore/vectorValue/1.0":{const h=Tt.fromJSON(o),m=Object.freeze(h.toArray());return c(n.vector(m),{type:"vector",values:m})}}const p={};for(const[h,m]of Object.entries(o))p[h]=xn(m,!1,n,s);return a(p)}function Fd(t){return $d(JSON.parse(JSON.stringify(to(t))))}class $s extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function p0(t){let e;try{e=JSON.parse(t)}catch(u){const l=u instanceof Error;throw new $s(`Persisted blob is not valid JSON: ${l?u.message:String(u)}`)}if(typeof e!="object"||e===null)throw new $s("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new $s(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new $s("Persisted blob has no firestore field");const i={};for(const[u,l]of Object.entries(e.firestore))Ho(l),i[u]=f0(l);const o=e.services;return{firestore:i,services:o!==void 0&&typeof o=="object"&&o!==null?o:{}}}const qd=3,m0=256,As="meta";function Ud(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%m0).toString(16).padStart(2,"0")}function Zo(t){const e=JSON.stringify(t);let n=2166136261,s=0,r=s<e.length;for(;r;)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0,s+=1,r=s<e.length;return n}function Bd(t,e,n){const s=new Map;s.set(As,{version:qd,savedAt:n,services:e});for(const[r,i]of Object.entries(t)){const o=Ud(r),c=s.get(o)??{docs:{},encoding:Ko};s.set(o,c),c.docs[r]=Fd(i)}for(const[r,i]of s)r!==As&&(i.checksum=Zo(i.docs));return s}const zd="pyric-v3-records";function tA(t){return JSON.stringify({format:zd,records:Object.fromEntries(t)})}function nA(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===zd&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):Wd(t)??new Map}function Wd(t){let e;try{e=p0(t)}catch{return null}return Bd(e.firestore,e.services,0)}function g0(t,e={}){const n={};let s={};for(const[r,i]of t){if(r===As){const f=i?.services;typeof f=="object"&&f!==null&&(s=f);continue}const a=i,c=a?.docs;if(typeof c!="object"||c===null)continue;if(typeof a?.checksum=="number"&&Zo(c)!==a.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[d,f]of Object.entries(c))try{n[d]=$d(h0(f,a?.encoding))}catch(p){if(e.skipInvalidDocuments!==!0)throw p;console.warn(`[sandbox/persistence] skipping unreadable Firestore document '${d}' in bucket '${r}':`,p)}}return{firestore:n,services:s}}class y0{snapshot;read;paths=new Map;dirty;needsSnapshot=!0;constructor(e,n,s){this.snapshot=e,this.read=n,this.dirty=new Set(s)}mark(e){if(e===null){this.needsSnapshot=!0;return}const s=Ud(e),r=this.paths.get(s)??new Set;r.add(e),this.paths.set(s,r),this.dirty.add(s)}prepare(){if(this.needsSnapshot){const i=this.snapshot();for(const o of this.paths.keys())this.dirty.add(o);this.paths.clear();for(const o of Object.keys(i))this.mark(o);this.needsSnapshot=!1}const e=this.dirty;this.dirty=new Set;const n=()=>{for(const i of e)this.dirty.add(i)},s=new Map,r=[];try{for(const i of e){const o={},a=this.paths.get(i)??new Set;for(const u of a){const l=this.read(u);l===null?a.delete(u):o[u]=Fd(l)}a.size===0?(this.paths.delete(i),r.push(i)):s.set(i,{docs:o,encoding:Ko,checksum:Zo(o)})}return{records:s,removed:r,retry:n}}catch(i){throw n(),i}}}const Ln="snapshots";function pu(){const t=new Map,e=n=>{let s=t.get(n);return s||(s=new Map,t.set(n,s)),s};return{async getRecord(n,s){const r=t.get(n)?.get(s);return r===void 0?null:structuredClone(r)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,s){const r=e(n);for(const[i,o]of s)r.set(i,structuredClone(o))},async deleteRecords(n,s){const r=t.get(n);if(r)for(const i of s)r.delete(i)},async clear(n){t.delete(n)}}}function Vd(t){return new Promise((e,n)=>{const s=indexedDB.open(t,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(Ln)||r.createObjectStore(Ln)},s.onsuccess=()=>e(s.result),s.onerror=()=>n(s.error??new Error(`Failed to open IndexedDB '${t}'`)),s.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function ui(t,e,n){return Vd(t).then(s=>new Promise((r,i)=>{const o=s.transaction(Ln,e),a=o.objectStore(Ln),c=n(a);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),o.oncomplete=()=>{s.close(),r(u)},o.onerror=()=>{s.close(),i(o.error)},o.onabort=()=>{s.close(),i(o.error??new Error("IndexedDB transaction aborted"))}}))}function mu(t,e){return Vd(t).then(n=>new Promise((s,r)=>{const i=n.transaction(Ln,"readwrite");e(i.objectStore(Ln)),i.oncomplete=()=>{n.close(),s()},i.onerror=()=>{n.close(),r(i.error)},i.onabort=()=>{n.close(),r(i.error??new Error("IndexedDB transaction aborted"))}}))}function b0(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ui(t,"readonly",s=>s.get(e))??null},async listRecords(t){return(await ui(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await mu(t,n=>{for(const[s,r]of e)n.put(r,s)})},async deleteRecords(t,e){await mu(t,n=>{for(const s of e)n.delete(s)})},async clear(t){await ui(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const v0=250,gu="pyric:sandbox:auth-session";function li(t){return t==="auth"||t==="auth-session:[DEFAULT]"?gu:`${gu}:${encodeURIComponent(t)}`}function Gd(t){const e=JSON.stringify(t);let n=2166136261;for(let s=0;s<e.length;s++)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return n}function w0(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function S0(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?pu():b0()}async function A0(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??v0,backend:e.backend??"indexedDB"},s=S0(n),r=new Map,i=await k0(t,s,n.key,r),o=new Map(Object.entries(i??{})),a=new Map;let c=null,u=!1;const l=new Map,d=t instanceof vt?t:null,f=d?new y0(()=>d.getEnv().snapshot(),S=>d.getEnv().getDocument(S),[...r.keys()].filter(S=>S!==As)):null,p=async()=>{if(u)return;const S=f?.prepare();try{const x={...Object.fromEntries(o)};let F;if(S!==void 0&&d!==null){for(const[Y,X]of d.getServiceRegistry())(!X.subscribe||!a.has(Y))&&a.set(Y,structuredClone(X.snapshot())),x[Y]=a.get(Y);F=new Map(S.records),F.set(As,{version:qd,savedAt:Fc(t).now(),services:x})}else{const Y=t.snapshot();F=Bd(Y.firestore,{...x,...Y.services},Fc(t).now())}const H=new Map,ne=new Map;for(const[Y,X]of F){const be=Gd(X);ne.set(Y,be),r.get(Y)!==be&&H.set(Y,X)}const ae=S?.removed??[...r.keys()].filter(Y=>!F.has(Y)),Oe=s.applyChanges;Oe!==void 0?await Oe(n.key,H,ae):(H.size>0&&await s.putRecords(n.key,H),ae.length>0&&await s.deleteRecords(n.key,ae));for(const Y of ae)r.delete(Y);for(const[Y,X]of ne)r.set(Y,X)}catch(x){throw S?.retry(),x}};let h=Promise.resolve();const m=()=>(c&&(clearTimeout(c),c=null),h=h.then(p,p),h),g=()=>{u||c!==null||(c=setTimeout(()=>{c=null,m().catch(x=>{if(w0(x)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}if(s.retryFailedFlush===!1){console.warn("[sandbox/persistence] auto-flush failed; repair and restart required.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",x),g()})},n.flushIntervalMs))},b=(S,x)=>{if(!x.subscribe||l.has(S))return;const F=x.subscribe(()=>{a.delete(S),g()});l.set(S,F)},y=new Map,w=new Map,v=(S,x)=>{if(!n.sessionStorage)return;const{local:F,session:D}=n.sessionStorage,H=li(S),ne=x.currentUid(),ae=x.mode();if(ne===null||ae==="NONE"){F.removeItem(H),D.removeItem(H);return}const Oe=JSON.stringify({uid:ne});ae==="LOCAL"?(D.removeItem(H),F.setItem(H,Oe)):(F.removeItem(H),D.setItem(H,Oe))},E=S=>{if(!n.sessionStorage)return null;const x=li(S);for(const[F,D]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const H=D.getItem(x);if(H)try{const ne=JSON.parse(H);if(typeof ne?.uid=="string")return{uid:ne.uid,mode:F}}catch{D.removeItem(x)}}return null},I=S=>{if(!n.sessionStorage)return;const x=li(S);n.sessionStorage.local.removeItem(x),n.sessionStorage.session.removeItem(x)},j=(S,x,F)=>{if(F.session)try{F.session.restore(x.uid,x.mode),w.delete(S)}catch(D){console.warn(`[sandbox/persistence] session restore for uid '${x.uid}' failed — clearing stored session:`,D),I(S),w.delete(S)}},W=(S,x)=>{if(!n.sessionStorage||!x.session||y.has(S))return;const F=x.session;y.set(S,F.subscribe(()=>v(S,F)))},V=(S,x)=>{if(!x.session)return;const F=w.get(S)??E(S);F&&j(S,F,x)};if(t instanceof vt){for(const[S,x]of t.getServiceRegistry())o.delete(S),b(S,x),V(S,x),W(S,x);t.setServiceRegistrationHook((S,x)=>{if(a.delete(S),o.has(S))try{x.restore(o.get(S)),o.delete(S)}catch(ne){console.warn(`[sandbox/persistence] late-restore for service '${S}' failed:`,ne)}const D=E(S);D!==null&&w.set(S,D),V(S,x),b(S,x),W(S,x),g()}),t.setServiceUnregistrationHook(S=>{a.delete(S),l.get(S)?.(),l.delete(S),y.get(S)?.(),y.delete(S),w.delete(S),g()})}const N=d?.onDocumentChange(S=>{f?.mark(S),S===null&&a.clear(),g()}),B=t.onEvent(S=>{E0(S)&&g()}),G=()=>{m().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",G),{options:n,flush:m,async clear(){c&&(clearTimeout(c),c=null),await s.clear(n.key),r.clear(),f?.mark(null)},dispose(){if(!u){u=!0,c&&(clearTimeout(c),c=null),B(),N?.();for(const S of l.values())S();l.clear();for(const S of y.values())S();y.clear(),t instanceof vt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",G)}}}}async function k0(t,e,n,s){let r;try{r=await e.listRecords(n)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(r.length===0)return null;const i=[];for(const d of r)try{const f=await e.getRecord(n,d);f!==null&&i.push([d,f])}catch(f){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,f)}const o=[],a=[];let c=null;for(const[d,f]of i)if(typeof f=="string"){const p=Wd(f);p&&(a.push(d),c=p)}else o.push([d,f]);if(c){try{await e.putRecords(n,c),a.length>0&&await e.deleteRecords(n,a)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,f]of c)o.push([d,f])}for(const[d,f]of o)s.set(d,Gd(f));const u=g0(o,{skipInvalidDocuments:!0}),l=t instanceof vt;for(const[d,f]of Object.entries(u.firestore))l?Rt(t).adminSetDocument(d,f):t.admin.setDocument(d,f);if(t instanceof vt){const d=t.getServiceRegistry();for(const[f,p]of Object.entries(u.services)){const h=d.get(f);if(h)try{h.restore(p)}catch(m){console.warn(`[sandbox/persistence] service '${f}' restore failed — Firestore state is intact; auth users may need to be re-created:`,m)}}}return u.services}function E0(t){return t.kind==="write"||t.kind==="session_boundary"}function I0(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let _0=0;function x0(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++_0}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function C0(t,e={}){let n,s=!1;if(e.channel)n=e.channel,s=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),s=!0;else return()=>{};const r=e.originId??x0();let i=!1,o=!1;const a=t.onEvent(d=>{if(d.kind!=="write"||i)return;const f={kind:"write",origin:r,event:d};n.postMessage(f)}),c=d=>{if(!I0(d.data))return;const f=d.data;if(f.origin!==r){if(f.kind==="write")l(f.event);else if(f.kind==="hello"){const p={kind:"state",origin:r,to:f.origin,snapshot:t.snapshot()};n.postMessage(p)}else if(f.kind==="state"){if(f.to!==r||o)return;if(Object.keys(Rt(t).snapshot()).length>0){o=!0;return}i=!0;try{for(const[h,m]of Object.entries(f.snapshot.firestore))Rt(t).adminSetDocument(h,m)}finally{i=!1}o=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:r};return n.postMessage(u),()=>{a(),n.removeEventListener("message",c),s&&n.close()};function l(d){i=!0;try{if(d.method==="delete")Rt(t).adminDeleteDocument(d.path);else{const f=d.nextState;f!=null&&Rt(t).adminSetDocument(d.path,f)}}finally{i=!1}}}function O0(t,e=!1,n=!0){if(!t||typeof t!="object")return{unmeasured:1};const s=t;if(s.metadata?.fromCache)return{documentReads:0};if(Array.isArray(s.docs)){if(!e||n)return{documentReads:Math.max(1,s.docs.length)};if(!s.docChanges)return{unmeasured:1};const r=s.docChanges();return{documentReads:r.filter(i=>i.type==="added"||i.type==="modified").length,...r.some(i=>i.type==="removed")?{unmeasured:1}:{}}}if(s.exists!==void 0){const r=typeof s.exists=="function"?s.exists():s.exists;return{documentReads:!e||n||r?1:0}}return{unmeasured:1}}function T0(t){if(!t||typeof t!="object"||!("val"in t)||typeof t.val!="function")return{unmeasured:1};const e=JSON.stringify(t.val());return e===void 0?{unmeasured:1}:{payloadBytes:new TextEncoder().encode(e).byteLength}}function R0(t){if(["setDoc","updateDoc","addDoc"].includes(t))return{documentWrites:1};if(t==="deleteDoc")return{documentDeletes:1};if(t==="writeBatch.commit"||t==="runTransaction")return{unmeasured:1}}function L0(t){return t==="database"?"rtdb":t}function N0(t,e,n,s){if(t.phase==="progress"||t.phase==="transport"&&!t.record.ai)return;const{record:r,phase:i}=t;return Object.freeze({...t.usage?{usage:Object.freeze({...t.usage})}:{},...r.ai?{ai:r.ai}:{},sequence:s,id:`${r.id}/${i}/${r.deliveryCount}`,activityId:r.id,appId:r.appId,sourceId:r.sourceId,service:L0(r.service),method:r.method,kind:r.kind,status:r.status,phase:i,deliveryNumber:r.deliveryCount,at:e,monotonicAt:n})}function M0(t={}){const e=t.now??Date.now,n=t.monotonicNow??(()=>performance.now()),s=t.correlationWindowMs??250,r=Math.max(t.retentionMs??3e4,s),i=t.maxCompleted??100,o=new WeakMap,a=new Map,c=new Map,u=new Set,l=new Set,d=[];let f=0,p=!1,h=0,m=0,g=0,b,y=!1,w,v=!1,E=!1;function I(T,N,B){const G=N0({phase:T,record:N,usage:B},e(),n(),f+1);if(G&&(f++,d.push({event:G,observers:[...l]})),!p){p=!0;try{for(;d.length;){const C=d.shift();for(const S of C.observers)try{S(C.event)}catch{}}}finally{p=!1}}for(const C of[...u])try{C({phase:T,record:N})}catch{}}function j(T){a.delete(T.id)&&(c.get(T.id)?.(),c.delete(T.id),I("remove",T))}const W=T=>Math.max(T.endedAt??0,T.lastProgressAt??0);function V(){if(!E){E=!0;try{clearTimeout(b),b=void 0;const T=[...a.values()].filter(B=>B.endedAt!==void 0).sort((B,G)=>W(B)-W(G)),N=e()-r;for(;T.length&&(W(T[0])<=N||T.length>i&&W(T[0])<=e()-s);)j(T.shift());if(T.length&&!y){const B=T.length>i?s:r;b=setTimeout(V,Math.max(1,W(T[0])+B-e())),typeof b=="object"&&"unref"in b&&b.unref()}}finally{E=!1}}}return{silence(T){const N=v;v=!0;try{return T()}finally{v=N}},isSilenced(){return v},registering(T,N){const B=w;w=T.id;try{return N()}finally{w=B}},registrationId(){return w},begin(T){if(y||v)return{id:"",delivered(){},progress(){},complete(){},fail(){},close(){},transport(){},ai(){},response(){}};let N=o.get(T.app);N||(N={id:`app-${++h}`,sources:new Map},o.set(T.app,N));const B=JSON.stringify([T.source.service,T.source.key]);let G=N.sources.get(B);G||(G={id:`${N.id}/source-${++m}`,uses:0},N.sources.set(B,G)),++G.uses;const C=`${N.id}/activity-${++g}`,S=Object.freeze({id:C,appId:N.id,sourceId:G.id,service:T.source.service,target:T.source.target,isQuery:T.source.isQuery??!1,...T.source.indexQuery?{indexQuery:structuredClone(T.source.indexQuery)}:{},method:T.method,kind:T.kind,status:T.kind==="operation"?"pending":"active",startedAt:e(),deliveryCount:0,owners:Object.freeze([...T.owners??[]]),...T.transportId===void 0?{}:{transportId:T.transportId}});if(!y){a.set(C,S);const D=N,H=G;c.set(C,()=>{--H.uses===0&&D.sources.delete(B)}),I("start",S)}function x(D,H,ne){const ae=a.get(C);if(!ae||ae.endedAt!==void 0&&!(D==="progress"&&ae.status==="completed"))return;const Oe=Object.freeze({...ae,...H});a.set(C,Oe),I(D,Oe,ne)}function F(D,H){x("end",{status:D,endedAt:e()},H),V()}return{id:C,delivered(D,H){const ne=a.get(C);if(!ne||ne.kind==="operation"&&ne.deliveryCount>0)return;let ae;try{ae=H??(ne.service==="firestore"?ne.method.endsWith("FromCache")?{documentReads:0}:O0(D,ne.kind==="subscription",ne.deliveryCount===0):T0(D))}catch{ae={unmeasured:1}}x("delivery",{deliveryCount:ne.deliveryCount+1,lastDeliveryAt:e()},ae)},progress(){x("progress",{lastProgressAt:e()}),V()},complete(D){F("completed",D??(S.service==="firestore"?R0(S.method):void 0))},fail(D){F("failed",D)},response(D){try{const H=JSON.stringify(D,null,2);H!==void 0&&x("transport",{response:Object.freeze({text:H.slice(0,65536),truncated:H.length>65536})})}catch{}},ai(D){x("transport",{ai:Object.freeze({...D})})},close(){F("closed")},transport(D){x("transport",{transportId:D})}}},records(){return V(),[...a.values()]},subscribe(T){return y||u.add(T),()=>{u.delete(T)}},observe(T){return y||l.add(T),()=>{l.delete(T)}},dispose(){y=!0,clearTimeout(b);for(const T of[...a.values()])j(T);u.clear(),l.clear()}}}const yu=Symbol.for("pyric.sdk-activity"),bu=globalThis,D0=bu[yu]??(bu[yu]=M0());function sA(t,e){return t.delivered(e),t.complete(),e}function $0(t,e){const n={...t};if(t.kind==="listener_attach"||t.kind==="listener"&&t.phase==="attach"){const o=D0.registrationId();o&&(n.activity={...n.activity,listenerId:o})}n.service=t.service??e?.service??"firestore";const r="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=eo(n)||t.operationContext!==void 0?Vo(e,r):P0(t,e);return n.operationContext=i,n.actor=i.source,n.authLens=i.authLens,i.planId!==void 0&&(n.planId=i.planId),e?.activity!==void 0&&(n.activity={...n.activity,...e.activity}),eo(n)&&(n.rulesDisposition=Object.freeze({...Nd(n)})),n}function P0(t,e){return xs({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function j0(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Hd(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const s=xs({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:s,actor:s.source,authLens:s.authLens,...s.planId===void 0?{}:{planId:s.planId}}}function Hd(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const s=Vo(t,e);return{...t,...e,operationContext:s,actor:s.source,authLens:s.authLens,...s.planId===void 0?{}:{planId:s.planId}}}let F0=1;function on(){const t=(F0++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class vt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory;ambientProvenance;_currentUser=null;currentUserSubs=new Set;documentChanges=new Set;onDocumentChange(e){return this.documentChanges.add(e),()=>{this.documentChanges.delete(e)}}documentChanged=e=>{for(const n of this.documentChanges)n(e)};persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;clock;constructor(e,n,s){this.eventHistory=new Rv(s),this._env=e,this.clock=n,Object.defineProperty(this,pd,{value:n,enumerable:!1}),this.attachToEnv()}static createRoot(e){const n=new Pt;return new vt(new lu(n),n,e)}getEnv(){return this._env}withAuth(e){return Sr(e),new Fr(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onStateChange(this.documentChanged)),this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,s)=>{const r={kind:"listener_errored",id:on(),at:this.clock.now(),listenerId:s,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection,...n.collectionGroup?{collectionGroup:!0}:{}},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(r)}))}emitEvent(e,n){const s=Hd(this.ambientProvenance,n);this.dispatch($0(e,s))}runWithProvenance(e,n){const s=this.ambientProvenance;this.ambientProvenance=j0(s,e);try{return n()}finally{this.ambientProvenance=s}}dispatch(e){if(e={...e,observedAt:Date.now()},this.eventHistory.append(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const s of this.eventSubs)try{const r=s(e);r!=null&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return this.eventHistory.snapshot()}primeEventHistory(e){const n=this.eventHistory.length>0,s=e.length===0;if(n||s)return 0;for(const r of e)if(r.kind==="operation"&&r.observation?.status==="pending"){const o={...r.observation,status:"interrupted",error:{code:"host-restarted"}};this.eventHistory.append({...r,observation:o})}else this.eventHistory.append(r);return e.length}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>t0(this._env,e,n),deleteDocument:e=>n0(this._env,e)}}reset(){const e={kind:"session_boundary",id:on(),at:this.clock.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory.clear(),this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const s of this.envUnsubs)s();this.envUnsubs=[],this._env.dispose(),this._env=new lu(this.clock),this.attachToEnv(),this.documentChanged(null)}async resetAll(){this.reset();const e=[],n=[];for(const[s,r]of this.serviceRegistry)r.reset&&n.push(Promise.resolve().then(()=>r.reset()).catch(i=>{e.push(`${s}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:on(),at:this.clock.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear(),this.documentChanges.clear()}snapshot(){const e={};for(const[n,s]of this.serviceRegistry)e[n]=s.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,s]of Object.entries(e.firestore))this._env.adminSetDocument(n,s);for(const[n,s]of this.serviceRegistry)if(n in e.services)try{s.restore(e.services[n])}catch(r){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,r)}}get currentUser(){return this._currentUser}set currentUser(e){Sr(e),!q0(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const s=n(e);s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ct("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await A0(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return C0(this,e)}async flush(){if(!this.persistence)throw new ct("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new ct("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function q0(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),s=e.token===void 0?void 0:JSON.stringify(e.token);return n===s}function Rt(t){if(!(t instanceof vt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function rA(t,e,n){if(!(t instanceof vt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function iA(t){const{at:e,...n}=t;return{kind:"service_mutation",id:on(),at:e,...n}}function oA(t){const{at:e,...n}=t;return{kind:"operation",id:on(),at:e,...n}}function aA(t){const{at:e,...n}=t;return{kind:"commit",id:on(),at:e,...n}}function cA(t){const{at:e,...n}=t;return{kind:"listener",id:on(),at:e,...n}}function uA(t){return vt.createRoot(t)}function lA(t,e){return Rt(t).deployRules(e)}function dA(t,e){const n=Rt(t);return n.seed({rules:n.getRules(),documents:e})}function fA(t){return Rt(t).snapshot()}function hA(t,e={}){const n=e.recentEventLimit??10,s=Rt(t),r=s.getRules(),i=r?xi(r):{warnings:[]},o=i.warnings.map(g=>({rule:g.rule,severity:g.severity,message:g.message})),a={errors:0,warnings:0,info:0};for(const g of i.warnings)g.severity==="error"?a.errors++:g.severity==="warning"?a.warnings++:a.info++;const c=r?Qh(r):null;c!==null&&(o.unshift({rule:c.kind==="parse"?"PARSE_ERROR":"COMPILE_LIMIT",severity:"error",message:`Firestore ${c.message}`}),a.errors++);const u=s.snapshot(),l={};for(const g of Object.keys(u)){const b=g.split("/")[0]??"";b&&(l[b]=(l[b]??0)+1)}const d=t.history(),f=[];for(const g of d){const b=g.kind==="request",y=g.kind==="operation",w=g.kind==="listener";(b||y||w&&g.phase==="errored")&&f.push(g)}const p=[];for(const g of f)if(g.result==="deny")p.push(g);else{const y=g.error;y!==void 0&&y.code==="PERMISSION_DENIED"&&p.push(g)}const h=f.slice(-n).map(g=>{let b="";if(g.path!==void 0)b=String(g.path);else{const E=g.target;E!==void 0&&E.path!==void 0&&(b=String(E.path))}let y="listen";g.method!==void 0&&(y=String(g.method));let w="error";if(g.result!==void 0)w=String(g.result);else{const E=g.error;E!==void 0&&E.code==="PERMISSION_DENIED"&&(w="deny")}let v=null;return g.auth!==void 0&&(v=g.auth),{path:b,method:y,result:w,auth:v}}),m=p.slice(-n).map(g=>{let b="";if(g.path!==void 0)b=String(g.path);else{const j=g.target;j!==void 0&&j.path!==void 0&&(b=String(j.path))}let y="listen";g.method!==void 0&&(y=String(g.method));let w=null;g.auth!==void 0&&(w=g.auth);let v;typeof g.debugMessage=="string"&&(v=g.debugMessage);const E=g.evaluatedRule??g.rule??void 0,I=Array.isArray(g.debugMessages)?g.debugMessages:typeof g.debugMessage=="string"?[g.debugMessage]:void 0;return{path:b,method:y,auth:w,debugMessage:v,rule:E,reasons:I}});return{rules:{source:r,sizeBytes:new TextEncoder().encode(r).byteLength,isEmpty:r.trim().length===0,lint:{...a,findings:o}},documents:{totalCount:Object.keys(u).length,byCollection:l},events:{totalCount:d.length,recentDenials:m,recentRequests:h}}}export{Hg as $,Rr as A,fu as B,D0 as C,oS as D,lS as E,At as F,ct as G,Es as H,Jh as I,mo as J,ah as K,B0 as L,Vs as M,He as N,ho as O,Y0 as P,Fr as Q,re as R,Pt as S,Vo as T,J0 as U,oe as V,ge as W,ts as X,Ge as Y,ve as Z,Ci as _,dA as a,ln as a$,Tl as a0,fe as a1,Mt as a2,Ny as a3,J as a4,Js as a5,Vg as a6,tn as a7,Ly as a8,My as a9,Rt as aA,ws as aB,Z0 as aC,nA as aD,tA as aE,iS as aF,vd as aG,Ww as aH,sS as aI,ai as aJ,eA as aK,h0 as aL,Mw as aM,Nw as aN,yd as aO,GS as aP,Ko as aQ,to as aR,$d as aS,Rv as aT,Aw as aU,Se as aV,Zt as aW,Nt as aX,Ot as aY,Rn as aZ,ji as a_,Ry as aa,ut as ab,nt as ac,Gy as ad,Oy as ae,qs as af,$g as ag,ke as ah,Dg as ai,Ab as aj,os as ak,Sb as al,qa as am,Qg as an,Gg as ao,sy as ap,Fs as aq,Ml as ar,Re as as,ty as at,Dl as au,$l as av,Is as aw,Hv as ax,Ow as ay,sA as az,fA as b,ir as b0,nr as b1,Sr as b2,pu as b3,Q0 as b4,eo as b5,zt as b6,mt as b7,_n as b8,md as b9,Vv as ba,z0 as bb,W0 as bc,Dn as bd,bs as be,ft as bf,FS as bg,gr as bh,K0 as bi,G0 as bj,me as bk,vs as bl,JS as bm,QS as bn,Vn as bo,Wn as bp,cu as bq,V0 as br,X0 as bs,wt as bt,Ht as bu,H0 as bv,Ji as bw,uA as c,zu as d,th as e,rA as f,Jf as g,Fc as h,hA as i,U0 as j,oA as k,aA as l,iA as m,cA as n,Ld as o,pt as p,Wi as q,_m as r,lA as s,jo as t,ms as u,yt as v,gs as w,_s as x,nd as y,lr as z};
|
|
1724
|
+
${b}`:h??b,w=me("permission-denied",f,{request:{method:"list",path:e.path,auth:e.auth},query:e.constraints,queryProof:d,...y?{remediation:y}:{},...g?{repro:g}:{},...l?.rule||c?{rule:l?.rule??c}:{}});return this.emitRequest({at:s,evalMs:r,method:"list",path:e.path,auth:e.auth,result:"deny",debugMessages:p,queryProof:d,rulesEvidence:this.rules.captureQueryEvidence(d,o.evidence),...c?{evaluatedRule:c}:{},origin:e.origin,...i?{detail:i}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}}),this.emitUserDenial(e.origin,w),{allowed:!1,error:w}}applyProof(e,n,s){n.kind==="provable"&&(e.resource=n.syntheticResource),(s.limit!=null||s.offset!=null||s.orderBy!=null)&&(e.query={...s.limit!=null?{limit:s.limit}:{},...s.offset!=null?{offset:s.offset}:{},...s.orderBy!=null?{orderBy:s.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitUserDenial(e,n){e==="user"&&this.events.denial.emit(n)}}class YS{events;triggerScope;rules;simulator;host;clock;operationReader;listAuthorizer;constructor(e,n,s,r,i,o,a=new Pt){this.events=e,this.triggerScope=n,this.rules=s,this.simulator=r,this.host=i,this.clock=a,this.operationReader=new xS(e,s,r,i,o,a),this.listAuthorizer=new QS(e,s,r,i,a)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,n,s=!1){if(s){const v=this.state.get(e);return this.emitRequest({at:this.clock.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:v,exists:v!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:v}}const r=ve.fromMillis(this.clock.now()),i=Pr(this.state,{method:"get",path:e,auth:n},r),o=this.clock.now(),a=performance.now(),c=xd(this.rules,this.simulator,[i],{getDoc:v=>this.state.get(v)}),u=performance.now()-a;if(!c.success)return this.emitRequest({at:o,evalMs:u,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:me("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const l=c.data.results[0],d=this.rules.captureEvidence(l);if(l.state==="UNSUPPORTED")throw this.emitRequest({at:o,evalMs:u,method:"get",path:e,auth:n,result:"unsupported",rulesEvidence:d,debugMessages:Ee(l),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new $n(Pn("get",e,Ee(l)),"get",e,Ee(l));const f=l.state==="PASSED",p=this.state.get(e),h=Jt(l);let m="deny";f&&(m="allow");const g=p!==null,b={at:o,evalMs:u,method:"get",path:e,auth:n,result:m,debugMessages:Ee(l),evaluatedRule:h,rulesEvidence:d,origin:"listener",resourceBefore:{data:p,exists:g}},y=this.triggerScope.current();if(y!==void 0&&(b.triggeredBy=y),this.emitRequest(b),f===!1){const v={request:{method:"get",path:e,auth:n},resource:{data:p,exists:g}};return h!==void 0&&(v.rule=h),{allowed:!1,error:me("permission-denied",`get ${e} denied by rules`,v)}}return{allowed:!0,data:p}}silentReadCollection(e,n,s,r=!1){if(typeof s=="function")return{allowed:!1,error:me("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=s?tu(s.execution):void 0,o=i?nu(i):{},a={requestTime:ve.fromMillis(this.clock.now()),at:this.clock.now()},c=this.triggerScope.current(),u=eu(e),l=this.listAuthorizer.authorize({path:u.kind==="collection"?u.path:u.collectionId,collectionGroup:u.kind==="collection-group",auth:n,constraints:o,bypassRules:r,...s?.activityQuery?{activityQuery:s.activityQuery}:{},execution:i,origin:"listener",...c?{triggeredBy:c}:{},timing:a});if(!l.allowed)return l;const d=su(this.state,u);return{allowed:!0,docs:i?iu(d,i):d}}runQuery(e){const n=eu(e.scope),s=tu(e.execution),r=e.auth,i=e.bypassRules,o=e.activityQuery,a=su(this.state,n),c=n.kind==="collection"?n.path:n.collectionId,u=nu(s),l=this.listAuthorizer.authorize({path:c,collectionGroup:n.kind==="collection-group",auth:r,constraints:u,bypassRules:i,...o!==void 0?{activityQuery:o}:{},execution:s,origin:"user"});return l.allowed?{allowed:!0,docs:iu(a,s)}:l}}const ou="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",au=20;function XS(){const t=new Uint8Array(au);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<au;n++)e+=ou[t[n]%ou.length];return e}function Nd(t,e=""){const n=[],s=new WeakSet;return r(t,e),n;function r(i,o){if(i==null||typeof i!="object"||s.has(i)||(s.add(i),Yv(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,l)=>r(u,`${o}[${l}]`));return}const a=i,c=e0(a);if(c){n.push({field:o,kind:c});return}for(const[u,l]of Object.entries(a)){const d=o?`${o}.${u}`:u;r(l,d)}}}function e0(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}yw();class t0{host;rules;simulator;eventLog;events;triggerScope;clock;constructor(e,n,s,r,i,o,a=new Pt){this.host=e,this.rules=n,this.simulator=s,this.eventLog=r,this.events=i,this.triggerScope=o,this.clock=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Dr(e))}emitWrite(e){if(!this.events.write.hasSubscribers)return;const s={kind:"write",id:ns().replace(/^req-/,"wr-"),at:this.clock.now(),method:e.method,path:e.path,auth:null,priorState:e.priorState,nextState:e.nextState,requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos}},{auth:r}=e;r!==null&&(s.auth={uid:r.uid},r.token&&(s.auth.token=r.token)),e.data!==void 0&&(s.data=e.data),e.updateMask!==void 0&&(s.updateMask=e.updateMask);const{merge:c}=e;c===!0?s.merge=!0:c!==void 0&&c!==!1&&(s.merge={mergeFields:[...c.mergeFields]}),e.groupId!==void 0&&(s.groupId=e.groupId),e.groupKind!==void 0&&(s.groupKind=e.groupKind),e.sentinels!==void 0&&e.sentinels.length>0&&(s.sentinels=e.sentinels),e.autoId!==void 0&&(s.autoId=e.autoId),e.detail!==void 0&&(s.detail=e.detail),this.events.write.emit({...s,...e.provenance})}capturePriors(e){const n={};for(const s of e){const r=this.state.get(s),i=r!==null;n[s]=i?{...r}:null}return n}captureEvidence(e){return this.rules.captureEvidence(e)}runSimulate(e,n,s){return Cd(this.state,this.rules,this.simulator,e,n,s)}resolvePriorDocumentState(e,n,s){return n.has(e)?n.get(e)??null:s.exists(e)?s.get(e)??null:null}computeProjectedUpdate(e,n){return Nr(e??{},n??{})}computeProjectedOverwrite(e,n){return Mr(e??{},n??{})}buildBatchProjection(e,n=new Map){for(const s of e){if(s.method==="set"){n.set(s.path,rn(s.data??{}).writes);continue}if(s.method==="delete"){n.set(s.path,null);continue}const o=this.resolvePriorDocumentState(s.path,n,this.state);if(s.method==="update"){const c=this.computeProjectedUpdate(o,s.data);n.set(s.path,c)}else{const c=this.computeProjectedOverwrite(o,s.data);n.set(s.path,c)}}return n}buildTestCase(e,n){return Pr(this.state,e,n)}notify(e,n){this.triggerScope.run({method:e,path:n[0]??""},()=>this.host.notifyListenersForPaths(new Set(n),{method:e,paths:n}))}}class Md{runtime;constructor(e){this.runtime=e}prepare(e,n){const s=ve.fromMillis(this.runtime.clock.now()),r=[],i=new Map;for(const[o,a]of e.entries())try{if(a.method==="update"&&i.get(a.path)===null)throw new Error(`Cannot delete then update document '${a.path}' in the same atomic write.`);const u=a.data!==void 0;let l=a.data;if(u){const f=i.has(a.path);let p;f?p=i.get(a.path)??null:p=this.runtime.state.get(a.path),l=ht({...a.data},{path:a.path,method:a.method,prior:p,serverTime:s});const{merge:h}=a;if(h!==void 0&&h!==!1){const b=h===!0?void 0:h.mergeFields;l=Mr(p??{},l,b)}}const d={method:a.method,path:a.path,data:l};r.push(d),this.runtime.buildBatchProjection([d],i)}catch(c){const u=c.message,l=me("invalid-argument",u),d=n.snapshot[a.path]??null,f={at:this.runtime.clock.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:n.auth,result:"deny",debugMessages:[`Write preparation error: ${u}`],resourceBefore:{data:d,exists:d!==null},origin:n.origin,groupId:n.groupId};return this.includesRequestData(n,a)&&Object.assign(f,Xn(a,a.preData)),n.bypassRules===!0&&(f.detail={admin:!0}),n.provenance!==void 0&&(f.provenance=n.provenance),{index:o,input:a,message:u,error:l,request:f}}return{context:n,inputs:e,resolvedOps:r,serverTime:s}}evaluateAndApply(e,n){const{context:s,resolvedOps:r,serverTime:i}=e,o=this.runtime.buildBatchProjection(r,n),a=e.inputs.map(f=>{if(f.method!=="set")return f;const h=o.get(f.path)===null;let m;return h?m="delete":m=this.runtime.state.get(f.path)!==null?"update":"create",{...f,ruleMethod:m}}),c=r.map((f,p)=>{const h=this.runtime.buildTestCase({method:a[p].ruleMethod,path:f.path,auth:s.auth,data:f.data},i);return h.data=o.get(f.path)??void 0,h}),u=[];let l=!0;for(const[f]of r.entries()){const p=a[f],h=s.snapshot[p.path]??null,m=this.runtime.clock.now(),g=performance.now(),b=this.runtime.runSimulate([c[f]],s.bypassRules,o),y=performance.now()-g;if(!b.success){const N=me("invalid-argument",b.error.message);u.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[b.error.message],error:N,request:this.request(e,p,h,m,y,"deny",[`Simulation error: ${b.error.message}`])}),l=!1;continue}const v=b.data.results[0],E=Ee(v);if(v.state==="UNSUPPORTED"){const N=this.request(e,p,h,m,y,"unsupported",E);throw N.rulesEvidence=this.runtime.captureEvidence(v),this.runtime.emitRequest(N),new $n(Pn(p.ruleMethod,p.path,E),p.ruleMethod,p.path,E)}const j=v.state==="PASSED";let W="deny";j&&(W="allow");const V={path:p.path,method:p.ruleMethod,allowed:j,debugMessages:E,request:this.request(e,p,h,m,y,W,E)};if(V.request.rulesEvidence=this.runtime.captureEvidence(v),!j){const N=Jt(v),B=h!==null,G={request:{method:p.ruleMethod,path:p.path,auth:s.auth},resource:{data:h,exists:B}};this.includesRequestData(s,p)&&Object.assign(G.request,Xn(p,p.preData)),N!==void 0&&(G.rule=N),V.error=me("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,G),this.runtime.emitDenial(V.error),l=!1}u.push(V)}let d=null;if(l){const f=this.runtime.state.applyBatch(r);if(!f.success){l=!1;const h=f.errors?.[0];if(h!==void 0){const b=r[h.index]?.method==="create";d=me(b?"already-exists":"not-found",h.error);const y=u[h.index];y!==void 0&&(y.allowed=!1,y.error=d)}}}return{...e,inputs:a,outcomes:u,allowed:l,structuralError:d}}emitAndNotify(e){const{context:n,inputs:s,outcomes:r,serverTime:i}=e;e.allowed&&this.runtime.notify(n.origin,s.map(o=>o.path));for(const[o,a]of r.entries()){const c=s[o],u=e.allowed&&a.allowed,l=n.snapshot[c.path]??null;if(u){const d=c.ruleMethod==="delete";a.request.resourceAfter=d?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}}else a.request.resourceAfter={data:l,exists:l!==null};if(this.runtime.emitRequest(a.request),u){const f=c.preData!==void 0?Xn(c,c.preData):void 0,p=f?Nd(f.resourceData):void 0,h=c.ruleMethod==="delete",m={method:c.ruleMethod,path:c.path,auth:n.auth,priorState:l,nextState:h?null:this.runtime.state.get(c.path),groupId:n.groupId,groupKind:n.origin,requestTime:i,merge:c.merge};!h&&f!==void 0&&(m.data=f.resourceData,f.updateMask!==void 0&&(m.updateMask=f.updateMask)),p!==void 0&&p.length>0&&(m.sentinels=p),n.bypassRules===!0&&(m.detail={admin:!0}),n.provenance!==void 0&&(m.provenance=n.provenance),this.runtime.emitWrite(m)}}}request(e,n,s,r,i,o,a){const{context:c}=e,u={at:r,evalMs:i,method:n.ruleMethod,path:n.path,auth:c.auth,result:o,debugMessages:a,resourceBefore:{data:s,exists:s!==null},origin:c.origin,groupId:c.groupId};return this.includesRequestData(c,n)&&Object.assign(u,Xn(n,n.preData)),c.bypassRules===!0&&(u.detail={admin:!0}),c.provenance!==void 0&&(u.provenance=c.provenance),u}includesRequestData(e,n){return n.preData!==void 0&&(e.origin==="batch"||n.ruleMethod!=="delete")}}class n0{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Md(e)}batch(e,n,s){const r=this.runtime.capturePriors(e.map(w=>w.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,o=e.map(w=>{const{method:v}=w,E=v==="set";let I;return E?I=r[w.path]!==null?"update":"create":I=v,{...w,ruleMethod:I,preData:w.data}}),a=this.pipeline.prepare(o,{origin:"batch",groupId:i,auth:n,bypassRules:s,snapshot:r}),u=n!==null?{uid:n.uid}:null;if(!("resolvedOps"in a)){const w=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:u,allowed:!1,operations:e.map(v=>({method:v.method,path:v.path,data:v.data,allowed:!1})),debugMessages:[`Write preparation error on '${a.input.path}': ${a.message}`]});return this.runtime.emitRequest(a.request),{allowed:!1,results:e.map(v=>{const E={path:v.path,allowed:!1,debugMessages:[a.message]};return v.path===a.input.path&&(E.error=a.error),E}),event:w,error:a.error}}const d=this.pipeline.evaluateAndApply(a),f=d.outcomes.map(w=>{const v={path:w.path,allowed:w.allowed,debugMessages:w.debugMessages};return w.error!==void 0&&(v.error=w.error),v}),{allowed:p}=d,h=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:u,allowed:p,priorDocs:p?r:void 0,operations:d.resolvedOps.map((w,v)=>({method:w.method,path:w.path,data:w.data,allowed:f[v]?.allowed??!1})),debugMessages:p?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(d);let m;!p&&(m=d.structuralError??f.find(w=>w.error)?.error??me("permission-denied","Batch denied"));const b={allowed:p,results:f,event:h};return m!==void 0&&(b.error=m),b}}const cu="Firestore transactions require all reads to be executed before all writes.";class s0 extends Error{simError;constructor(){super(cu),this.name="ReadAfterWriteError",this.simError=me("failed-precondition",cu)}}class uu extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class r0 extends Error{simError=me("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class ci extends Error{code;simError;constructor(e){super(e.message),this.name="TransactionReadDeniedError",this.code=e.code,this.simError=e}}class i0{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,n=()=>0){this.versionReader=n,this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);!this.readVersions.has(e)&&this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:n});const i=n===null?null:vs(n);return{path:e,exists:i!==null,data:()=>i===null?void 0:i}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n,s){const r={method:"set",path:e,data:n};if(s!==void 0){const o=typeof s=="object";r.merge=o?{mergeFields:[...s.mergeFields]}:s}this.queue(r)}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){const{data:n}=e;n!==void 0&&(e.data=vs(n)),this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new s0}}class o0{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Md(e)}transaction(e,n){return this.runAttempt(e,n,1)}runAttempt(e,n,s){const r=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),o=new Map(Object.keys(r).map(h=>[h,this.runtime.state.version(h)])),a=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,c=new Map;let u;const l=h=>{const m=r[h]??null;if(n.bypassRules!==!0){const b=this.evaluateTransactionRead(h,m,n,a,c);if(b!==null)throw u=b,new ci(b)}return m},d=new i0(l,h=>{const m=o.get(h);if(m!==void 0)return m;const b=this.runtime.state.version(h);return b<=i?b:-1});let f;try{f=e(d)}catch(h){if(h instanceof ci)return this.buildReadDeniedResult(d,n,h.simError);if(u!==void 0)return this.buildReadDeniedResult(d,n,u);throw this.logAbortedTransaction(d,n.auth,h),h}if(f!==null&&typeof f?.then=="function")return f.then(h=>{try{return this.commitTransaction(d,r,n,h,i,a,c,u)}catch(m){return this.retryOrThrow(m,e,n,s)}},h=>{if(h instanceof ci)return this.buildReadDeniedResult(d,n,h.simError);if(u!==void 0)return this.buildReadDeniedResult(d,n,u);throw this.logAbortedTransaction(d,n.auth,h),h});try{return this.commitTransaction(d,r,n,f,i,a,c,u)}catch(h){return this.retryOrThrow(h,e,n,s)}}retryOrThrow(e,n,s,r){if(!(e instanceof uu))throw e;const o=s.maxAttempts??5;if(r>=o)throw new r0;return this.runAttempt(n,s,r+1)}commitTransaction(e,n,s,r,i,o,a,c){if(c!==void 0)return this.buildReadDeniedResult(e,s,c);const{reads:l,writes:d,readVersions:f}=e.consume();for(const[C,S]of f)if(this.runtime.state.version(C)!==S)throw new uu;if(s.bypassRules!==!0&&l.length>0&&this.runtime.state.currentVersion()!==i){const C=new Map(a);for(const S of l){const x=this.runtime.state.get(S.path),F=this.evaluateTransactionRead(S.path,x,s,o,C);if(F!==null)return this.buildReadDeniedResult(e,s,F,l)}}const h=s.auth;if(d.length===0){const C=h!==null,S=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:C?{uid:h.uid}:null,allowed:!0,reads:l.map(x=>({path:x.path,data:x.data})),operations:[],snapshot:n,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...l],writes:[],returnValue:r,event:S}}const g=Object.fromEntries(d.map(C=>[C.path,n[C.path]??null])),b=d.map(C=>{const{method:S}=C,x=S==="set";let F;return x?F=this.runtime.state.get(C.path)!==null?"update":"create":F=S,{...C,ruleMethod:F,preData:C.data}}),y=this.pipeline.prepare(b,{origin:"transaction",groupId:o,auth:h,bypassRules:s.bypassRules,provenance:s.provenance,snapshot:g});if(!("resolvedOps"in y)){const C=h!==null,S=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:C?{uid:h.uid}:null,allowed:!1,aborted:!0,error:{name:"FirebaseError",message:y.message,code:y.error.code},reads:l.map(x=>({path:x.path,data:x.data})),operations:d.map(x=>({method:x.method,path:x.path,data:x.data,allowed:!1})),debugMessages:[`Write preparation error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...l],writes:this.summarizeWrites(b.map((x,F)=>{const D=F===y.index,H={path:x.path,method:x.ruleMethod,allowed:!1,debugMessages:D?[y.message]:[]};return D&&(H.error=y.error),H})),returnValue:r,event:S,error:y.error}}const v=this.pipeline.evaluateAndApply(y,a),E=v.outcomes.map(C=>{const S={path:C.path,method:C.method,allowed:C.allowed,debugMessages:C.debugMessages};return C.error!==void 0&&(S.error=C.error),S}),{allowed:I}=v,j=h!==null,W=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:j?{uid:h.uid}:null,allowed:I,reads:l.map(C=>({path:C.path,data:C.data})),operations:v.resolvedOps.map((C,S)=>({method:C.method,path:C.path,data:C.data,allowed:E[S]?.allowed??!1})),snapshot:I?n:void 0,debugMessages:I?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let V;!I&&(V=v.structuralError??E.find(C=>C.error)?.error??me("permission-denied","Transaction denied"));const N={allowed:I,reads:[...l],writes:this.summarizeWrites(E),returnValue:r,event:W};return V!==void 0&&(N.error=V),s.readOnly===!0&&e.hadWrites()&&(N.readOnlyViolation=!0),N}summarizeWrites(e){const n=new Map;for(const s of e){const r=n.get(s.path);if(r===void 0){n.set(s.path,s);continue}const o=r.allowed&&s.allowed,a={path:s.path,method:s.method,allowed:o,debugMessages:[...r.debugMessages,...s.debugMessages]},c=r.error??s.error;c!==void 0&&(a.error=c),n.set(s.path,a)}return[...n.values()]}evaluateTransactionRead(e,n,s,r,i){const o=this.runtime.clock.now(),a=performance.now(),c=this.runtime.buildTestCase({method:"get",path:e,auth:s.auth}),u=this.runtime.runSimulate([c],s.bypassRules,i),l=performance.now()-a,d=n!==null;if(!u.success){const j={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"deny",debugMessages:[`Simulation error: ${u.error.message}`],resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r};return s.provenance!==void 0&&(j.provenance=s.provenance),this.runtime.emitRequest(j),me("invalid-argument",u.error.message)}const p=u.data.results[0],h=Ee(p);if(p.state==="UNSUPPORTED"){const j={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"unsupported",debugMessages:h,resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r,rulesEvidence:this.runtime.captureEvidence(p)};throw s.provenance!==void 0&&(j.provenance=s.provenance),this.runtime.emitRequest(j),new $n(Pn("get",e,h),"get",e,h)}if(p.state==="PASSED")return null;const b={at:o,evalMs:l,method:"get",path:e,auth:s.auth,result:"deny",debugMessages:h,resourceBefore:{data:n,exists:d},origin:"transaction",groupId:r,rulesEvidence:this.runtime.captureEvidence(p)};s.provenance!==void 0&&(b.provenance=s.provenance),this.runtime.emitRequest(b);const w=Jt(p),v={request:{method:"get",path:e,auth:s.auth},resource:{data:n,exists:d}};w!==void 0&&(v.rule=w);const I=me("permission-denied",`get ${e} denied by rules`,v);return this.runtime.emitDenial(I),I}buildReadDeniedResult(e,n,s,r){const i=r??e.consume().reads,o=n.auth,a=o!==null,c=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:a?{uid:o.uid}:null,allowed:!1,reads:i.map(u=>({path:u.path,data:u.data})),operations:[],debugMessages:["Transaction rolled back — read denied by rules"]});return{allowed:!1,reads:[...i],writes:[],returnValue:void 0,event:c,error:s}}logAbortedTransaction(e,n,s){const r=s,{reads:i}=e.consume(),o=n!==null,a={name:s.name,message:s.message};r.code!==void 0&&(a.code=String(r.code)),this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:o?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:i.map(u=>({path:u.path,data:u.data})),error:a,debugMessages:[`Transaction aborted: ${s.message}`]})}}class a0{runtime;batches;transactions;constructor(e,n,s,r,i,o,a=new Pt){this.runtime=new t0(e,n,s,r,i,o,a),this.batches=new n0(this.runtime),this.transactions=new o0(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,n,s,r){if(r!==void 0&&r!==!1&&(e==="create"||e==="update")){const i=r===!0?void 0:r.mergeFields;return this.runtime.state.setMerge(n,s??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(n,s??{});return i.success?null:me("already-exists",i.error??`Document '${n}' already exists`)}case"update":{const i=this.runtime.state.update(n,s??{});return i.success?null:me("not-found",i.error??`Document '${n}' does not exist`)}case"set":return this.runtime.state.set(n,s??{}),null;case"delete":return this.runtime.state.delete(n),null;default:return null}}execute(e){const{method:n,path:s,auth:r,data:i,autoId:o,requestTime:a,merge:c,bypassRules:u}=e,l=i?Xn(e,i):void 0,d=u?{admin:!0}:void 0,f=this.runtime.capturePriors([s]),p=a??ve.fromMillis(this.runtime.clock.now());let h;try{h=i&&ht({...i},{path:s,method:n,prior:this.runtime.state.get(s),serverTime:p}),n==="update"&&h&&Ew(h)}catch(B){const G=B.message,C=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:i,allowed:!1,priorDocs:f,debugMessages:[`FieldValue resolve error: ${G}`]});return this.runtime.emitRequest({at:this.runtime.clock.now(),evalMs:0,method:n,path:s,auth:r,result:"deny",debugMessages:[`FieldValue resolve error: ${G}`],...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[G],event:C,error:me("invalid-argument",G)}}const m=this.runtime.buildTestCase({...e,data:h},p),g=this.runtime.clock.now(),b=performance.now(),y=this.runtime.runSimulate([m],u),w=performance.now()-b;if(!y.success){const B=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:h,allowed:!1,priorDocs:f,debugMessages:[`Simulation error: ${y.error.message}`]});return this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:"deny",debugMessages:[`Simulation error: ${y.error.message}`],...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[y.error.message],event:B,error:me("invalid-argument",y.error.message)}}const v=y.data.results[0],E=this.runtime.captureEvidence(v);if(v.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:"unsupported",rulesEvidence:E,debugMessages:Ee(v),...l??{},resourceBefore:{data:f[s]??null,exists:(f[s]??null)!==null},origin:"user",...d?{detail:d}:{}}),new $n(Pn(n,s,Ee(v)),n,s,Ee(v));let I=v.state==="PASSED",j=null;I&&(j=this.applyWrite(n,s,h,c),j&&(I=!1));const W=this.runtime.eventLog.append({type:"single",method:n,path:s,auth:r?{uid:r.uid}:null,data:h,allowed:I,priorDocs:I?f:void 0,debugMessages:Ee(v)}),V={allowed:I,debugMessages:Ee(v),event:W};if(I===!1){let B=!1;if(j!==void 0&&j!==null&&(B=!0),B)V.error=j;else{let C=null;const S=f[s];S!==void 0&&(C=S);let F=n;n==="set"&&(C!==null?F="update":F="create");const H=Jt(v),ae={request:{method:F,path:s,auth:r},resource:{data:C,exists:C!==null}};i!==void 0&&Object.assign(ae.request,l),H!==void 0&&(ae.rule=H),V.error=me("permission-denied",`${n} ${s} denied by rules`,ae),this.runtime.emitDenial(V.error)}}I&&this.runtime.notify(n,[s]);const T=f[s]??null,N=I?this.runtime.state.get(s):T;if(this.runtime.emitRequest({at:g,evalMs:w,method:n,path:s,auth:r,result:I?"allow":"deny",debugMessages:Ee(v),evaluatedRule:Jt(v),rulesEvidence:E,...l??{},resourceBefore:{data:T,exists:T!==null},...n!=="delete"?{resourceAfter:{data:N,exists:N!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),I){const B=l?Nd(l.resourceData):void 0,G=o&&n==="create"?s.split("/").pop():void 0;this.runtime.emitWrite({method:n,path:s,auth:r,...n!=="delete"&&l?{data:l.resourceData,...l.updateMask?{updateMask:l.updateMask}:{}}:{},merge:c,priorState:T,nextState:n==="delete"?null:N,...B&&B.length>0?{sentinels:B}:{},...G?{autoId:G}:{},requestTime:p,...d?{detail:d}:{}})}return V}createWithAutoId(e,n,s,r){const i=e.endsWith("/")?e.slice(0,-1):e,o=XS(),a=`${i}/${o}`,c=this.execute({method:"create",path:a,auth:s,data:n,autoId:!0,bypassRules:r});return{path:a,result:c}}batch(e,n,s){return this.batches.batch(e,n,s)}transaction(e,n){return this.transactions.transaction(e,n)}}class lu{state;stateChanges=new Set;onStateChange(e){return this.stateChanges.add(e),()=>{this.stateChanges.delete(e)}}stateChanged=e=>{for(const n of this.stateChanges)n(e)};eventLog;history;simulator;rules;seedSnapshot;events=new Mw;triggerScope=new Dw;reads;writes;listeners;constructor(e=new Pt){this.state=new ri({},void 0,this.stateChanged),this.eventLog=new Tw(e);const n=this;this.simulator=new sv,this.rules=new IS(Nw),this.reads=new YS(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return n.state}},this.eventLog,e),this.listeners=new vS(this.events,this.triggerScope,this.reads,e),this.writes=new a0({get state(){return n.state},notifyListenersForPaths:(s,r)=>n.listeners.notifyListenersForPaths(s,r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope,e),this.history=new wS(this.eventLog,{get state(){return n.state},capturePriors:s=>this.writes.capturePriors(s),applyWrite:(s,r,i,o)=>this.writes.applyWrite(s,r,i,o)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,n,s={},r=null,i,o=!1,a=!1,c){return this.listeners.addSnapshotListener(e,n,s,r,i,o,a,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear(),this.stateChanges.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new ri({},new Cw(e.baseDocuments),this.stateChanged):new ri(e.documents??{},void 0,this.stateChanged),this.stateChanged(null),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),xi(e.rules)}deployRules(e){const n=xi(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),n}reevaluateLiveListeners(e,n){this.listeners.reevaluateLiveListeners(e,n)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,n){this.state.set(e,n??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:n.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,n,s,r){return this.writes.createWithAutoId(e,n,s,r)}batch(e,n,s){return this.writes.batch(e,n,s)}transaction(e,n){return this.writes.transaction(e,n)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventRetention(){return this.eventLog.getRetention()}getEventCount(){return this.history.getEventCount()}}function c0(t,e,n){const s=t.execute({method:"set",path:e,data:n??{},auth:null,bypassRules:!0});s.allowed||Dd(s,e)}function u0(t,e){if(t.getDocument(e)===null)return{deleted:!1};const s=t.execute({method:"delete",path:e,auth:null,bypassRules:!0});return s.allowed||Dd(s,e),{deleted:!0}}function Dd(t,e){const n=me("failed-precondition",`admin write to '${e}' was not applied: ${t.debugMessages.join("; ")}`);throw new ws(t.error??n)}const l0=/password|credential|secret|token|authorization|cookie|api[-_]?key/i;function d0(t){return t.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,"[redacted token]").replace(/((?:password|api[-_]?key|access[-_]?token|refresh[-_]?token|secret)["']?\s*[:=]\s*["']?)[^\s"',;}]+/gi,"$1[redacted]")}function f0(t,e=16384){try{const n=JSON.stringify(t,(s,r)=>l0.test(s)?"[redacted]":typeof r=="string"?d0(r):r,2);return n===void 0?void 0:{text:n.slice(0,e),truncated:n.length>e}}catch{return}}function eo(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function xs(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function rA(t){const e=xs(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function du(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Vo(t,e){const n=t?.operationContext?.source??t?.actor,s=e?.operationContext?.source??e?.actor;return xs({source:du(t)??du(e)??n??s??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function $d(t){return Vo(void 0,t)}function h0(t){if(t.result==="deny")return!0;if(!("error"in t)||!t.error||typeof t.error!="object")return!1;const e=t.error.code;if(typeof e!="string")return!1;const n=e.toLowerCase();return n==="permission_denied"||n==="permission-denied"||n==="auth/permission-denied"}function Pd(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:h0(t)?{kind:"evaluated",verdict:"deny"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.kind==="listener"?t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function p0(t){if(t===null)return null;let e;return t.token!==void 0&&(e=jd(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function jd(t){const e={};for(const[n,s]of Object.entries(t))e[n]=Go(s);return Object.freeze(e)}function Go(t){return Array.isArray(t)?Object.freeze(t.map(Go)):t&&typeof t=="object"?jd(t):t}function m0(t){if(eo(t))return t;if(!(t.kind==="service_mutation"&&t.service==="auth"))return null;const n=s=>{const r=f0(s);if(!(!r||r.truncated))return JSON.parse(r.text)};return{kind:"operation",id:t.id,at:t.at,service:"auth",method:t.op,path:t.path,auth:t.auth,origin:"user",result:"not-applicable",rulesDisposition:{kind:"not-evaluated",reason:"not-a-rules-operation"},operationContext:$d(t),detail:{transition:t.op,evidence:n(t.detail)},resourceBefore:t.before===void 0?void 0:{data:n(t.before),exists:!0},resourceAfter:t.after===void 0?void 0:{data:n(t.after),exists:!0}}}function iA(t){const e=m0(t);if(!e)return null;let n="listen",s;e.kind==="request"||e.kind==="operation"?(n=e.method,e.path!==void 0&&(s=e.path)):e.kind==="listener"&&(n="listen",e.target.path!==void 0&&(s=e.target.path));let r="firestore";e.service!==void 0&&(r=e.service);let i;return"queryProof"in e&&e.queryProof&&(i=Go(e.queryProof)),Object.freeze({id:e.kind==="operation"?e.observation?.id??e.id:e.id,at:e.kind==="operation"?e.observation?.startedAt??e.at:e.at,...e.kind==="operation"&&e.observation?{observation:e.observation}:{},eventKind:e.kind,service:r,method:n,...s===void 0?{}:{path:s},auth:p0(e.auth),result:e.result,context:$d(e),rules:Object.freeze({...Pd(e)}),queryProof:i})}function fu(t){if(t===null)return null;if(t.tenant===void 0)return t.token===void 0?{uid:t.uid}:{uid:t.uid,token:structuredClone(t.token)};const e=t.token!==void 0?structuredClone(t.token):{},n=e.firebase;let s;if(typeof n=="object"&&n!==null&&!Array.isArray(n)){const r=n;s={...r,tenant:r.tenant!==void 0?r.tenant:t.tenant}}else s={tenant:t.tenant};return e.firebase=s,{uid:t.uid,tenant:t.tenant,token:e}}function hu(t){if(t===null)return{mode:"anon"};const e={mode:"as",uid:t.uid};return t.token!==void 0&&(e.token=t.token),t.tenant!==void 0&&(e.tenant=t.tenant),e}class Fr{sandbox;auth;operationContext;constructor(e,n,s){this.sandbox=e,Sr(n);const r=fu(n);this.auth=r,this.operationContext=xs(s??{source:{kind:"unattributed"},authLens:hu(r)})}withAuth(e){Sr(e);const n=fu(e);return new Fr(this.sandbox,n,{source:this.operationContext.source,authLens:hu(n),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function oA(t,e){return new Fr(t.sandbox,t.auth,e)}function Sr(t){if(t===null)return;if(t===void 0)throw new ct({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
|
|
1725
|
+
`)});if(typeof t!="object")throw new ct("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new ct("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("tenant"in e&&e.tenant!==void 0&&(typeof e.tenant!="string"||e.tenant.length===0))throw new ct("invalid-argument","withAuth() requires `tenant` (when present) to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new ct("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}class zt{bytes;constructor(e){this.bytes=e,bs(this,vw(e)),Dn(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new zt(e.slice()))}static fromBase64String(e){const n=atob(e),s=Uint8Array.from(n,r=>r.charCodeAt(0));return new zt(s)}static fromUint8Array(e){return new zt(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof zt&&this.bytes.length===e.bytes.length&&this.bytes.every((n,s)=>n===e.bytes[s])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return zt.fromBase64String(n.bytes)}}class _n{lat;lng;constructor(e,n){if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");bs(this,gr("geo-point",String(e),"\0",String(n))),Dn(this,Object.freeze({type:"geo-point",latitude:e,longitude:n}),()=>new _n(e,n))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof _n&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new _n(n.latitude,n.longitude)}}class Tt{_values;constructor(e){this._values=e,Dn(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new Tt(e.slice()))}static create(e){if(!e.every(s=>typeof s=="number"))throw new TypeError("Vector values must be numbers.");return new Tt(e.slice())}toArray(){return this._values.slice()}isEqual(e){if(!(e instanceof Tt))return!1;const s=e._values;return s!==void 0&&this._values.length===s.length&&this._values.every((r,i)=>r===s[i])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(i=>typeof i=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Tt.create(n.vectorValues)}}function aA(t=[]){return Tt.create(t)}const g0=64;function Ho(t){Fd(t,0)}function Fd(t,e){if(t===null||typeof t!="object")return;const s=e+1;if(s>g0)throw new At("invalid-argument","Encoded document nesting exceeds 64 containers.");for(const i of Object.values(t))Fd(i,s)}function qd(t){if(rt(t))return t;throw new At("invalid-argument","Document data must be a plain object.")}const Ko="pyric/firestore-values/1";function Ud(t){const e=t===void 0,n=t===Ko;if(!e&&!n)throw new At("invalid-argument","Unsupported Firestore value encoding.");return n}function to(t){if(t===null||typeof t!="object")return t;if(t instanceof mt)return t.toJSON();if(t instanceof Date)return mt.fromDate(t).toJSON();if(t instanceof zt||t instanceof _n||t instanceof Tt)return t.toJSON();const a=qo(t);if(a!==void 0)return{__type:"reference",path:a};if(Array.isArray(t))return t.map(to);const l=Object.getPrototypeOf(t);if(l===Object.prototype||l===null){const f=Object.fromEntries(Object.entries(t).map(([h,m])=>[h,to(m)]));return Object.hasOwn(f,"type")||Object.hasOwn(f,"__type")||Object.hasOwn(f,"__type__")?{type:"pyric/map/1.0",fields:f}:f}return t}const Bd={bytes:t=>new He(t),geoPoint:(t,e)=>new ut(t,e),reference:t=>new wt(t),timestamp:(t,e)=>new ve(t,e),vector:t=>new Ht(t)};function y0(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),s=atob(e+n),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);return r}function b0(t){const e=atob(t),n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n}function v0(t){return xn(t,!0,Bd,!1)}function w0(t,e){Ho(t);const n=Ud(e);return xn(t,!0,Bd,n)}function cA(t,e,n){Ho(t);const s=Ud(n);return xn(t,!0,{bytes:r=>zt.fromUint8Array(r),geoPoint:(r,i)=>new _n(r,i),reference:r=>e.create(r),timestamp:(r,i)=>new mt(r,i),vector:r=>Tt.create(r.slice())},s)}function xn(t,e,n,s){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const h=t.map(m=>xn(m,!1,n,s));return e&&bs(h,$c(t)),h}const o=t,a=h=>(e&&bs(h,$c(t)),h),c=(h,m)=>(Dn(h,Object.freeze(m),()=>h),a(h));if(o.__type__==="__vector__"&&Array.isArray(o.value)){const h=Object.freeze(o.value.slice());return c(n.vector(h),{type:"vector",values:h})}if(typeof o.__type=="string")switch(o.__type){case"timestamp":return c(n.timestamp(o.seconds,o.nanos),{type:"timestamp",seconds:o.seconds,nanoseconds:o.nanos});case"bytes":{const h=y0(o.base64);return c(n.bytes(h),{type:"bytes",values:Object.freeze(Array.from(h))})}case"latlng":return c(n.geoPoint(o.lat,o.lng),{type:"geo-point",latitude:o.lat,longitude:o.lng});case"duration":return a(new ke(o.seconds,o.nanos));case"reference":{const h=o.path;return a(n.reference(h))}case"path":return a(new nt(o.segments))}if(s&&o.type==="pyric/map/1.0"){const h=o.fields;if(h===null||typeof h!="object"||Array.isArray(h))throw new TypeError("Invalid encoded map fields.");const g=Object.fromEntries(Object.entries(h).map(([b,y])=>[b,xn(y,!1,n,s)]));return a(g)}if(typeof o.type=="string")switch(o.type){case"firestore/timestamp/1.0":{const h=o.seconds,m=o.nanoseconds;return c(n.timestamp(h,m),{type:"timestamp",seconds:h,nanoseconds:m})}case"firestore/bytes/1.0":{const h=b0(o.bytes);return c(n.bytes(h),{type:"bytes",values:Object.freeze(Array.from(h))})}case"firestore/geoPoint/1.0":return c(n.geoPoint(o.latitude,o.longitude),{type:"geo-point",latitude:o.latitude,longitude:o.longitude});case"firestore/vectorValue/1.0":{const h=Tt.fromJSON(o),m=Object.freeze(h.toArray());return c(n.vector(m),{type:"vector",values:m})}}const p={};for(const[h,m]of Object.entries(o))p[h]=xn(m,!1,n,s);return a(p)}function zd(t){return qd(JSON.parse(JSON.stringify(to(t))))}class $s extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function S0(t){let e;try{e=JSON.parse(t)}catch(u){const l=u instanceof Error;throw new $s(`Persisted blob is not valid JSON: ${l?u.message:String(u)}`)}if(typeof e!="object"||e===null)throw new $s("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new $s(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new $s("Persisted blob has no firestore field");const i={};for(const[u,l]of Object.entries(e.firestore))Ho(l),i[u]=v0(l);const o=e.services;return{firestore:i,services:o!==void 0&&typeof o=="object"&&o!==null?o:{}}}const Wd=3,A0=256,As="meta";function Vd(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%A0).toString(16).padStart(2,"0")}function Zo(t){const e=JSON.stringify(t);let n=2166136261,s=0,r=s<e.length;for(;r;)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0,s+=1,r=s<e.length;return n}function Gd(t,e,n){const s=new Map;s.set(As,{version:Wd,savedAt:n,services:e});for(const[r,i]of Object.entries(t)){const o=Vd(r),c=s.get(o)??{docs:{},encoding:Ko};s.set(o,c),c.docs[r]=zd(i)}for(const[r,i]of s)r!==As&&(i.checksum=Zo(i.docs));return s}const Hd="pyric-v3-records";function uA(t){return JSON.stringify({format:Hd,records:Object.fromEntries(t)})}function lA(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===Hd&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):Kd(t)??new Map}function Kd(t){let e;try{e=S0(t)}catch{return null}return Gd(e.firestore,e.services,0)}function k0(t,e={}){const n={};let s={};for(const[r,i]of t){if(r===As){const f=i?.services;typeof f=="object"&&f!==null&&(s=f);continue}const a=i,c=a?.docs;if(typeof c!="object"||c===null)continue;if(typeof a?.checksum=="number"&&Zo(c)!==a.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[d,f]of Object.entries(c))try{n[d]=qd(w0(f,a?.encoding))}catch(p){if(e.skipInvalidDocuments!==!0)throw p;console.warn(`[sandbox/persistence] skipping unreadable Firestore document '${d}' in bucket '${r}':`,p)}}return{firestore:n,services:s}}class E0{snapshot;read;paths=new Map;dirty;needsSnapshot=!0;constructor(e,n,s){this.snapshot=e,this.read=n,this.dirty=new Set(s)}mark(e){if(e===null){this.needsSnapshot=!0;return}const s=Vd(e),r=this.paths.get(s)??new Set;r.add(e),this.paths.set(s,r),this.dirty.add(s)}prepare(){if(this.needsSnapshot){const i=this.snapshot();for(const o of this.paths.keys())this.dirty.add(o);this.paths.clear();for(const o of Object.keys(i))this.mark(o);this.needsSnapshot=!1}const e=this.dirty;this.dirty=new Set;const n=()=>{for(const i of e)this.dirty.add(i)},s=new Map,r=[];try{for(const i of e){const o={},a=this.paths.get(i)??new Set;for(const u of a){const l=this.read(u);l===null?a.delete(u):o[u]=zd(l)}a.size===0?(this.paths.delete(i),r.push(i)):s.set(i,{docs:o,encoding:Ko,checksum:Zo(o)})}return{records:s,removed:r,retry:n}}catch(i){throw n(),i}}}const Ln="snapshots";function pu(){const t=new Map,e=n=>{let s=t.get(n);return s||(s=new Map,t.set(n,s)),s};return{async getRecord(n,s){const r=t.get(n)?.get(s);return r===void 0?null:structuredClone(r)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,s){const r=e(n);for(const[i,o]of s)r.set(i,structuredClone(o))},async deleteRecords(n,s){const r=t.get(n);if(r)for(const i of s)r.delete(i)},async clear(n){t.delete(n)}}}function Zd(t){return new Promise((e,n)=>{const s=indexedDB.open(t,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(Ln)||r.createObjectStore(Ln)},s.onsuccess=()=>e(s.result),s.onerror=()=>n(s.error??new Error(`Failed to open IndexedDB '${t}'`)),s.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function ui(t,e,n){return Zd(t).then(s=>new Promise((r,i)=>{const o=s.transaction(Ln,e),a=o.objectStore(Ln),c=n(a);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),o.oncomplete=()=>{s.close(),r(u)},o.onerror=()=>{s.close(),i(o.error)},o.onabort=()=>{s.close(),i(o.error??new Error("IndexedDB transaction aborted"))}}))}function mu(t,e){return Zd(t).then(n=>new Promise((s,r)=>{const i=n.transaction(Ln,"readwrite");e(i.objectStore(Ln)),i.oncomplete=()=>{n.close(),s()},i.onerror=()=>{n.close(),r(i.error)},i.onabort=()=>{n.close(),r(i.error??new Error("IndexedDB transaction aborted"))}}))}function I0(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ui(t,"readonly",s=>s.get(e))??null},async listRecords(t){return(await ui(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await mu(t,n=>{for(const[s,r]of e)n.put(r,s)})},async deleteRecords(t,e){await mu(t,n=>{for(const s of e)n.delete(s)})},async clear(t){await ui(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const _0=250,gu="pyric:sandbox:auth-session";function li(t){return t==="auth"||t==="auth-session:[DEFAULT]"?gu:`${gu}:${encodeURIComponent(t)}`}function Jd(t){const e=JSON.stringify(t);let n=2166136261;for(let s=0;s<e.length;s++)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return n}function x0(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function C0(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?pu():I0()}async function O0(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??_0,backend:e.backend??"indexedDB"},s=C0(n),r=new Map,i=await T0(t,s,n.key,r),o=new Map(Object.entries(i??{})),a=new Map;let c=null,u=!1;const l=new Map,d=t instanceof vt?t:null,f=d?new E0(()=>d.getEnv().snapshot(),S=>d.getEnv().getDocument(S),[...r.keys()].filter(S=>S!==As)):null,p=async()=>{if(u)return;const S=f?.prepare();try{const x={...Object.fromEntries(o)};let F;if(S!==void 0&&d!==null){for(const[Y,X]of d.getServiceRegistry())(!X.subscribe||!a.has(Y))&&a.set(Y,structuredClone(X.snapshot())),x[Y]=a.get(Y);F=new Map(S.records),F.set(As,{version:Wd,savedAt:Fc(t).now(),services:x})}else{const Y=t.snapshot();F=Gd(Y.firestore,{...x,...Y.services},Fc(t).now())}const H=new Map,ne=new Map;for(const[Y,X]of F){const be=Jd(X);ne.set(Y,be),r.get(Y)!==be&&H.set(Y,X)}const ae=S?.removed??[...r.keys()].filter(Y=>!F.has(Y)),Oe=s.applyChanges;Oe!==void 0?await Oe(n.key,H,ae):(H.size>0&&await s.putRecords(n.key,H),ae.length>0&&await s.deleteRecords(n.key,ae));for(const Y of ae)r.delete(Y);for(const[Y,X]of ne)r.set(Y,X)}catch(x){throw S?.retry(),x}};let h=Promise.resolve();const m=()=>(c&&(clearTimeout(c),c=null),h=h.then(p,p),h),g=()=>{u||c!==null||(c=setTimeout(()=>{c=null,m().catch(x=>{if(x0(x)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}if(s.retryFailedFlush===!1){console.warn("[sandbox/persistence] auto-flush failed; repair and restart required.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",x),g()})},n.flushIntervalMs))},b=(S,x)=>{if(!x.subscribe||l.has(S))return;const F=x.subscribe(()=>{a.delete(S),g()});l.set(S,F)},y=new Map,w=new Map,v=(S,x)=>{if(!n.sessionStorage)return;const{local:F,session:D}=n.sessionStorage,H=li(S),ne=x.currentUid(),ae=x.mode();if(ne===null||ae==="NONE"){F.removeItem(H),D.removeItem(H);return}const Oe=JSON.stringify({uid:ne});ae==="LOCAL"?(D.removeItem(H),F.setItem(H,Oe)):(F.removeItem(H),D.setItem(H,Oe))},E=S=>{if(!n.sessionStorage)return null;const x=li(S);for(const[F,D]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const H=D.getItem(x);if(H)try{const ne=JSON.parse(H);if(typeof ne?.uid=="string")return{uid:ne.uid,mode:F}}catch{D.removeItem(x)}}return null},I=S=>{if(!n.sessionStorage)return;const x=li(S);n.sessionStorage.local.removeItem(x),n.sessionStorage.session.removeItem(x)},j=(S,x,F)=>{if(F.session)try{F.session.restore(x.uid,x.mode),w.delete(S)}catch(D){console.warn(`[sandbox/persistence] session restore for uid '${x.uid}' failed — clearing stored session:`,D),I(S),w.delete(S)}},W=(S,x)=>{if(!n.sessionStorage||!x.session||y.has(S))return;const F=x.session;y.set(S,F.subscribe(()=>v(S,F)))},V=(S,x)=>{if(!x.session)return;const F=w.get(S)??E(S);F&&j(S,F,x)};if(t instanceof vt){for(const[S,x]of t.getServiceRegistry())o.delete(S),b(S,x),V(S,x),W(S,x);t.setServiceRegistrationHook((S,x)=>{if(a.delete(S),o.has(S))try{x.restore(o.get(S)),o.delete(S)}catch(ne){console.warn(`[sandbox/persistence] late-restore for service '${S}' failed:`,ne)}const D=E(S);D!==null&&w.set(S,D),V(S,x),b(S,x),W(S,x),g()}),t.setServiceUnregistrationHook(S=>{a.delete(S),l.get(S)?.(),l.delete(S),y.get(S)?.(),y.delete(S),w.delete(S),g()})}const N=d?.onDocumentChange(S=>{f?.mark(S),S===null&&a.clear(),g()}),B=t.onEvent(S=>{R0(S)&&g()}),G=()=>{m().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",G),{options:n,flush:m,async clear(){c&&(clearTimeout(c),c=null),await s.clear(n.key),r.clear(),f?.mark(null)},dispose(){if(!u){u=!0,c&&(clearTimeout(c),c=null),B(),N?.();for(const S of l.values())S();l.clear();for(const S of y.values())S();y.clear(),t instanceof vt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",G)}}}}async function T0(t,e,n,s){let r;try{r=await e.listRecords(n)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(r.length===0)return null;const i=[];for(const d of r)try{const f=await e.getRecord(n,d);f!==null&&i.push([d,f])}catch(f){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,f)}const o=[],a=[];let c=null;for(const[d,f]of i)if(typeof f=="string"){const p=Kd(f);p&&(a.push(d),c=p)}else o.push([d,f]);if(c){try{await e.putRecords(n,c),a.length>0&&await e.deleteRecords(n,a)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,f]of c)o.push([d,f])}for(const[d,f]of o)s.set(d,Jd(f));const u=k0(o,{skipInvalidDocuments:!0}),l=t instanceof vt;for(const[d,f]of Object.entries(u.firestore))l?Rt(t).adminSetDocument(d,f):t.admin.setDocument(d,f);if(t instanceof vt){const d=t.getServiceRegistry();for(const[f,p]of Object.entries(u.services)){const h=d.get(f);if(h)try{h.restore(p)}catch(m){console.warn(`[sandbox/persistence] service '${f}' restore failed — Firestore state is intact; auth users may need to be re-created:`,m)}}}return u.services}function R0(t){return t.kind==="write"||t.kind==="session_boundary"}function L0(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let N0=0;function M0(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++N0}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function D0(t,e={}){let n,s=!1;if(e.channel)n=e.channel,s=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),s=!0;else return()=>{};const r=e.originId??M0();let i=!1,o=!1;const a=t.onEvent(d=>{if(d.kind!=="write"||i)return;const f={kind:"write",origin:r,event:d};n.postMessage(f)}),c=d=>{if(!L0(d.data))return;const f=d.data;if(f.origin!==r){if(f.kind==="write")l(f.event);else if(f.kind==="hello"){const p={kind:"state",origin:r,to:f.origin,snapshot:t.snapshot()};n.postMessage(p)}else if(f.kind==="state"){if(f.to!==r||o)return;if(Object.keys(Rt(t).snapshot()).length>0){o=!0;return}i=!0;try{for(const[h,m]of Object.entries(f.snapshot.firestore))Rt(t).adminSetDocument(h,m)}finally{i=!1}o=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:r};return n.postMessage(u),()=>{a(),n.removeEventListener("message",c),s&&n.close()};function l(d){i=!0;try{if(d.method==="delete")Rt(t).adminDeleteDocument(d.path);else{const f=d.nextState;f!=null&&Rt(t).adminSetDocument(d.path,f)}}finally{i=!1}}}function $0(t,e=!1,n=!0){if(!t||typeof t!="object")return{unmeasured:1};const s=t;if(s.metadata?.fromCache)return{documentReads:0};if(Array.isArray(s.docs)){if(!e||n)return{documentReads:Math.max(1,s.docs.length)};if(!s.docChanges)return{unmeasured:1};const r=s.docChanges();return{documentReads:r.filter(i=>i.type==="added"||i.type==="modified").length,...r.some(i=>i.type==="removed")?{unmeasured:1}:{}}}if(s.exists!==void 0){const r=typeof s.exists=="function"?s.exists():s.exists;return{documentReads:!e||n||r?1:0}}return{unmeasured:1}}function P0(t){if(!t||typeof t!="object"||!("val"in t)||typeof t.val!="function")return{unmeasured:1};const e=JSON.stringify(t.val());return e===void 0?{unmeasured:1}:{payloadBytes:new TextEncoder().encode(e).byteLength}}function j0(t){if(["setDoc","updateDoc","addDoc"].includes(t))return{documentWrites:1};if(t==="deleteDoc")return{documentDeletes:1};if(t==="writeBatch.commit"||t==="runTransaction")return{unmeasured:1}}function F0(t){return t==="database"?"rtdb":t}function q0(t,e,n,s){if(t.phase==="progress"||t.phase==="transport"&&!t.record.ai)return;const{record:r,phase:i}=t;return Object.freeze({...t.usage?{usage:Object.freeze({...t.usage})}:{},...r.ai?{ai:r.ai}:{},sequence:s,id:`${r.id}/${i}/${r.deliveryCount}`,activityId:r.id,appId:r.appId,sourceId:r.sourceId,service:F0(r.service),method:r.method,kind:r.kind,status:r.status,phase:i,deliveryNumber:r.deliveryCount,at:e,monotonicAt:n})}function U0(t={}){const e=t.now??Date.now,n=t.monotonicNow??(()=>performance.now()),s=t.correlationWindowMs??250,r=Math.max(t.retentionMs??3e4,s),i=t.maxCompleted??100,o=new WeakMap,a=new Map,c=new Map,u=new Set,l=new Set,d=[];let f=0,p=!1,h=0,m=0,g=0,b,y=!1,w,v=!1,E=!1;function I(T,N,B){const G=q0({phase:T,record:N,usage:B},e(),n(),f+1);if(G&&(f++,d.push({event:G,observers:[...l]})),!p){p=!0;try{for(;d.length;){const C=d.shift();for(const S of C.observers)try{S(C.event)}catch{}}}finally{p=!1}}for(const C of[...u])try{C({phase:T,record:N})}catch{}}function j(T){a.delete(T.id)&&(c.get(T.id)?.(),c.delete(T.id),I("remove",T))}const W=T=>Math.max(T.endedAt??0,T.lastProgressAt??0);function V(){if(!E){E=!0;try{clearTimeout(b),b=void 0;const T=[...a.values()].filter(B=>B.endedAt!==void 0).sort((B,G)=>W(B)-W(G)),N=e()-r;for(;T.length&&(W(T[0])<=N||T.length>i&&W(T[0])<=e()-s);)j(T.shift());if(T.length&&!y){const B=T.length>i?s:r;b=setTimeout(V,Math.max(1,W(T[0])+B-e())),typeof b=="object"&&"unref"in b&&b.unref()}}finally{E=!1}}}return{silence(T){const N=v;v=!0;try{return T()}finally{v=N}},isSilenced(){return v},registering(T,N){const B=w;w=T.id;try{return N()}finally{w=B}},registrationId(){return w},begin(T){if(y||v)return{id:"",delivered(){},progress(){},complete(){},fail(){},close(){},transport(){},ai(){},response(){}};let N=o.get(T.app);N||(N={id:`app-${++h}`,sources:new Map},o.set(T.app,N));const B=JSON.stringify([T.source.service,T.source.key]);let G=N.sources.get(B);G||(G={id:`${N.id}/source-${++m}`,uses:0},N.sources.set(B,G)),++G.uses;const C=`${N.id}/activity-${++g}`,S=Object.freeze({id:C,appId:N.id,sourceId:G.id,service:T.source.service,target:T.source.target,isQuery:T.source.isQuery??!1,...T.source.indexQuery?{indexQuery:structuredClone(T.source.indexQuery)}:{},method:T.method,kind:T.kind,status:T.kind==="operation"?"pending":"active",startedAt:e(),deliveryCount:0,owners:Object.freeze([...T.owners??[]]),...T.transportId===void 0?{}:{transportId:T.transportId}});if(!y){a.set(C,S);const D=N,H=G;c.set(C,()=>{--H.uses===0&&D.sources.delete(B)}),I("start",S)}function x(D,H,ne){const ae=a.get(C);if(!ae||ae.endedAt!==void 0&&!(D==="progress"&&ae.status==="completed"))return;const Oe=Object.freeze({...ae,...H});a.set(C,Oe),I(D,Oe,ne)}function F(D,H){x("end",{status:D,endedAt:e()},H),V()}return{id:C,delivered(D,H){const ne=a.get(C);if(!ne||ne.kind==="operation"&&ne.deliveryCount>0)return;let ae;try{ae=H??(ne.service==="firestore"?ne.method.endsWith("FromCache")?{documentReads:0}:$0(D,ne.kind==="subscription",ne.deliveryCount===0):P0(D))}catch{ae={unmeasured:1}}x("delivery",{deliveryCount:ne.deliveryCount+1,lastDeliveryAt:e()},ae)},progress(){x("progress",{lastProgressAt:e()}),V()},complete(D){F("completed",D??(S.service==="firestore"?j0(S.method):void 0))},fail(D){F("failed",D)},response(D){try{const H=JSON.stringify(D,null,2);H!==void 0&&x("transport",{response:Object.freeze({text:H.slice(0,65536),truncated:H.length>65536})})}catch{}},ai(D){x("transport",{ai:Object.freeze({...D})})},close(){F("closed")},transport(D){x("transport",{transportId:D})}}},records(){return V(),[...a.values()]},subscribe(T){return y||u.add(T),()=>{u.delete(T)}},observe(T){return y||l.add(T),()=>{l.delete(T)}},dispose(){y=!0,clearTimeout(b);for(const T of[...a.values()])j(T);u.clear(),l.clear()}}}const yu=Symbol.for("pyric.sdk-activity"),bu=globalThis,B0=bu[yu]??(bu[yu]=U0());function dA(t,e){return t.delivered(e),t.complete(),e}function z0(t,e){const n={...t};if(t.kind==="listener_attach"||t.kind==="listener"&&t.phase==="attach"){const o=B0.registrationId();o&&(n.activity={...n.activity,listenerId:o})}n.service=t.service??e?.service??"firestore";const r="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=eo(n)||t.operationContext!==void 0?Vo(e,r):W0(t,e);return n.operationContext=i,n.actor=i.source,n.authLens=i.authLens,i.planId!==void 0&&(n.planId=i.planId),e?.activity!==void 0&&(n.activity={...n.activity,...e.activity}),eo(n)&&(n.rulesDisposition=Object.freeze({...Pd(n)})),n}function W0(t,e){return xs({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function V0(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Qd(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const s=xs({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:s,actor:s.source,authLens:s.authLens,...s.planId===void 0?{}:{planId:s.planId}}}function Qd(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const s=Vo(t,e);return{...t,...e,operationContext:s,actor:s.source,authLens:s.authLens,...s.planId===void 0?{}:{planId:s.planId}}}let G0=1;function on(){const t=(G0++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class vt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory;ambientProvenance;_currentUser=null;currentUserSubs=new Set;documentChanges=new Set;onDocumentChange(e){return this.documentChanges.add(e),()=>{this.documentChanges.delete(e)}}documentChanged=e=>{for(const n of this.documentChanges)n(e)};persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;clock;constructor(e,n,s){this.eventHistory=new jv(s),this._env=e,this.clock=n,Object.defineProperty(this,bd,{value:n,enumerable:!1}),this.attachToEnv()}static createRoot(e){const n=new Pt;return new vt(new lu(n),n,e)}getEnv(){return this._env}withAuth(e){return Sr(e),new Fr(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onStateChange(this.documentChanged)),this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,s)=>{const r={kind:"listener_errored",id:on(),at:this.clock.now(),listenerId:s,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection,...n.collectionGroup?{collectionGroup:!0}:{}},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(r)}))}emitEvent(e,n){const s=Qd(this.ambientProvenance,n);this.dispatch(z0(e,s))}runWithProvenance(e,n){const s=this.ambientProvenance;this.ambientProvenance=V0(s,e);try{return n()}finally{this.ambientProvenance=s}}dispatch(e){if(e={...e,observedAt:Date.now()},this.eventHistory.append(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const s of this.eventSubs)try{const r=s(e);r!=null&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return this.eventHistory.snapshot()}primeEventHistory(e){const n=this.eventHistory.length>0,s=e.length===0;if(n||s)return 0;for(const r of e)if(r.kind==="operation"&&r.observation?.status==="pending"){const o={...r.observation,status:"interrupted",error:{code:"host-restarted"}};this.eventHistory.append({...r,observation:o})}else this.eventHistory.append(r);return e.length}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>c0(this._env,e,n),deleteDocument:e=>u0(this._env,e)}}reset(){const e={kind:"session_boundary",id:on(),at:this.clock.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory.clear(),this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const s of this.envUnsubs)s();this.envUnsubs=[],this._env.dispose(),this._env=new lu(this.clock),this.attachToEnv(),this.documentChanged(null)}async resetAll(){this.reset();const e=[],n=[];for(const[s,r]of this.serviceRegistry)r.reset&&n.push(Promise.resolve().then(()=>r.reset()).catch(i=>{e.push(`${s}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:on(),at:this.clock.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear(),this.documentChanges.clear()}snapshot(){const e={};for(const[n,s]of this.serviceRegistry)e[n]=s.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,s]of Object.entries(e.firestore))this._env.adminSetDocument(n,s);for(const[n,s]of this.serviceRegistry)if(n in e.services)try{s.restore(e.services[n])}catch(r){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,r)}}get currentUser(){return this._currentUser}set currentUser(e){Sr(e),!H0(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const s=n(e);s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ct("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await O0(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return D0(this,e)}async flush(){if(!this.persistence)throw new ct("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new ct("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function H0(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),s=e.token===void 0?void 0:JSON.stringify(e.token);return n===s}function Rt(t){if(!(t instanceof vt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function fA(t,e,n){if(!(t instanceof vt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function hA(t){const{at:e,...n}=t;return{kind:"service_mutation",id:on(),at:e,...n}}function pA(t){const{at:e,...n}=t;return{kind:"operation",id:on(),at:e,...n}}function mA(t){const{at:e,...n}=t;return{kind:"commit",id:on(),at:e,...n}}function gA(t){const{at:e,...n}=t;return{kind:"listener",id:on(),at:e,...n}}function yA(t){return vt.createRoot(t)}function bA(t,e){return Rt(t).deployRules(e)}function vA(t,e){const n=Rt(t);return n.seed({rules:n.getRules(),documents:e})}function wA(t){return Rt(t).snapshot()}function SA(t,e={}){const n=e.recentEventLimit??10,s=Rt(t),r=s.getRules(),i=r?xi(r):{warnings:[]},o=i.warnings.map(g=>({rule:g.rule,severity:g.severity,message:g.message})),a={errors:0,warnings:0,info:0};for(const g of i.warnings)g.severity==="error"?a.errors++:g.severity==="warning"?a.warnings++:a.info++;const c=r?tp(r):null;c!==null&&(o.unshift({rule:c.kind==="parse"?"PARSE_ERROR":"COMPILE_LIMIT",severity:"error",message:`Firestore ${c.message}`}),a.errors++);const u=s.snapshot(),l={};for(const g of Object.keys(u)){const b=g.split("/")[0]??"";b&&(l[b]=(l[b]??0)+1)}const d=t.history(),f=[];for(const g of d){const b=g.kind==="request",y=g.kind==="operation",w=g.kind==="listener";(b||y||w&&g.phase==="errored")&&f.push(g)}const p=[];for(const g of f)if(g.result==="deny")p.push(g);else{const y=g.error;y!==void 0&&y.code==="PERMISSION_DENIED"&&p.push(g)}const h=f.slice(-n).map(g=>{let b="";if(g.path!==void 0)b=String(g.path);else{const E=g.target;E!==void 0&&E.path!==void 0&&(b=String(E.path))}let y="listen";g.method!==void 0&&(y=String(g.method));let w="error";if(g.result!==void 0)w=String(g.result);else{const E=g.error;E!==void 0&&E.code==="PERMISSION_DENIED"&&(w="deny")}let v=null;return g.auth!==void 0&&(v=g.auth),{path:b,method:y,result:w,auth:v}}),m=p.slice(-n).map(g=>{let b="";if(g.path!==void 0)b=String(g.path);else{const j=g.target;j!==void 0&&j.path!==void 0&&(b=String(j.path))}let y="listen";g.method!==void 0&&(y=String(g.method));let w=null;g.auth!==void 0&&(w=g.auth);let v;typeof g.debugMessage=="string"&&(v=g.debugMessage);const E=g.evaluatedRule??g.rule??void 0,I=Array.isArray(g.debugMessages)?g.debugMessages:typeof g.debugMessage=="string"?[g.debugMessage]:void 0;return{path:b,method:y,auth:w,debugMessage:v,rule:E,reasons:I}});return{rules:{source:r,sizeBytes:new TextEncoder().encode(r).byteLength,isEmpty:r.trim().length===0,lint:{...a,findings:o}},documents:{totalCount:Object.keys(u).length,byCollection:l},events:{totalCount:d.length,recentDenials:m,recentRequests:h}}}export{Ci as $,lr as A,Rr as B,fu as C,B0 as D,hS as E,At as F,yS as G,ct as H,Es as I,ep as J,mo as K,dh as L,Vs as M,Z0 as N,He as O,ho as P,oA as Q,re as R,Pt as S,Fr as T,Vo as U,rA as V,oe as W,ge as X,ts as Y,Ge as Z,ve as _,vA as a,ji as a$,ey as a0,Ml as a1,fe as a2,Mt as a3,qy as a4,J as a5,Js as a6,Yg as a7,tn as a8,Fy as a9,dA as aA,Rt as aB,ws as aC,sA as aD,lA as aE,uA as aF,fS as aG,kd as aH,Qw as aI,lS as aJ,ai as aK,cA as aL,w0 as aM,Uw as aN,qw as aO,Sd as aP,XS as aQ,Ko as aR,to as aS,qd as aT,jv as aU,Ow as aV,Se as aW,Zt as aX,Nt as aY,Ot as aZ,Rn as a_,Uy as aa,jy as ab,ut as ac,nt as ad,Xy as ae,$y as af,qs as ag,zg as ah,ke as ai,Fg as aj,Ob as ak,os as al,Cb as am,qa as an,ry as ao,Xg as ap,ly as aq,Fs as ar,jl as as,Re as at,cy as au,Fl as av,ql as aw,Is as ax,ew as ay,$w as az,wA as b,ln as b0,ir as b1,nr as b2,Sr as b3,pu as b4,iA as b5,eo as b6,zt as b7,mt as b8,_n as b9,vd as ba,Yv as bb,Q0 as bc,Y0 as bd,Dn as be,bs as bf,ft as bg,GS as bh,gr as bi,nA as bj,eA as bk,me as bl,vs as bm,s0 as bn,r0 as bo,Vn as bp,Wn as bq,cu as br,X0 as bs,aA as bt,wt as bu,Ht as bv,tA as bw,Ji as bx,yA as c,zu as d,ih as e,J0 as f,eh as g,fA as h,SA as i,K0 as j,Fc as k,pA as l,hA as m,mA as n,$d as o,gA as p,pt as q,Tm as r,bA as s,Wi as t,jo as u,ms as v,yt as w,gs as x,_s as y,od as z};
|