@pyric/cli 0.1.0-alpha.20 → 0.1.0-alpha.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -89
- package/dist/assurance/.generated/conformance-verdicts.d.ts +238 -1
- package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
- package/dist/assurance/.generated/conformance-verdicts.js +238 -1
- package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
- package/dist/bridge/client/dispatch.d.ts +25 -19
- package/dist/bridge/client/dispatch.d.ts.map +1 -1
- package/dist/bridge/client/dispatch.js +41 -48
- package/dist/bridge/client/dispatch.js.map +1 -1
- package/dist/bridge/client/tool-family-factories.d.ts +26 -0
- package/dist/bridge/client/tool-family-factories.d.ts.map +1 -0
- package/dist/bridge/client/tool-family-factories.js +10 -0
- package/dist/bridge/client/tool-family-factories.js.map +1 -0
- package/dist/bridge/server/mcp-contract.d.ts +7 -6
- package/dist/bridge/server/mcp-contract.d.ts.map +1 -1
- package/dist/bridge/server/mcp-contract.js +9 -48
- package/dist/bridge/server/mcp-contract.js.map +1 -1
- package/dist/bridge/server/peer.d.ts +11 -1
- package/dist/bridge/server/peer.d.ts.map +1 -1
- package/dist/bridge/server/peer.js +22 -1
- package/dist/bridge/server/peer.js.map +1 -1
- package/dist/bridge/server/tool-family-factories.d.ts +30 -0
- package/dist/bridge/server/tool-family-factories.d.ts.map +1 -0
- package/dist/bridge/server/tool-family-factories.js +22 -0
- package/dist/bridge/server/tool-family-factories.js.map +1 -0
- package/dist/bridge/server/tool-metadata.d.ts +17 -18
- package/dist/bridge/server/tool-metadata.d.ts.map +1 -1
- package/dist/bridge/server/tool-metadata.js +24 -59
- package/dist/bridge/server/tool-metadata.js.map +1 -1
- package/dist/bridge/tool-families.d.ts +48 -0
- package/dist/bridge/tool-families.d.ts.map +1 -0
- package/dist/bridge/tool-families.generated.d.ts +32 -0
- package/dist/bridge/tool-families.generated.d.ts.map +1 -0
- package/dist/bridge/tool-families.generated.js +15 -0
- package/dist/bridge/tool-families.generated.js.map +1 -0
- package/dist/bridge/tool-families.js +51 -0
- package/dist/bridge/tool-families.js.map +1 -0
- package/dist/bridge/tool-family-records/conformance.d.ts +7 -0
- package/dist/bridge/tool-family-records/conformance.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/conformance.js +6 -0
- package/dist/bridge/tool-family-records/conformance.js.map +1 -0
- package/dist/bridge/tool-family-records/firestore-data.d.ts +7 -0
- package/dist/bridge/tool-family-records/firestore-data.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/firestore-data.js +15 -0
- package/dist/bridge/tool-family-records/firestore-data.js.map +1 -0
- package/dist/bridge/tool-family-records/firestore-inspect.d.ts +7 -0
- package/dist/bridge/tool-family-records/firestore-inspect.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/firestore-inspect.js +6 -0
- package/dist/bridge/tool-family-records/firestore-inspect.js.map +1 -0
- package/dist/bridge/tool-family-records/firestore-rules.d.ts +7 -0
- package/dist/bridge/tool-family-records/firestore-rules.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/firestore-rules.js +15 -0
- package/dist/bridge/tool-family-records/firestore-rules.js.map +1 -0
- package/dist/bridge/tool-family-records/firestore-simulator.d.ts +7 -0
- package/dist/bridge/tool-family-records/firestore-simulator.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/firestore-simulator.js +16 -0
- package/dist/bridge/tool-family-records/firestore-simulator.js.map +1 -0
- package/dist/bridge/tool-family-records/rtdb-inspection.d.ts +7 -0
- package/dist/bridge/tool-family-records/rtdb-inspection.d.ts.map +1 -0
- package/dist/bridge/tool-family-records/rtdb-inspection.js +6 -0
- package/dist/bridge/tool-family-records/rtdb-inspection.js.map +1 -0
- package/dist/bundler/externals.d.ts +37 -0
- package/dist/bundler/externals.d.ts.map +1 -0
- package/dist/bundler/externals.js +52 -0
- package/dist/bundler/externals.js.map +1 -0
- package/dist/bundler/index.d.ts +17 -0
- package/dist/bundler/index.d.ts.map +1 -0
- package/dist/bundler/index.js +17 -0
- package/dist/bundler/index.js.map +1 -0
- package/dist/cli/inlined-sdk-scanner.d.ts +6 -0
- package/dist/cli/inlined-sdk-scanner.d.ts.map +1 -0
- package/dist/cli/inlined-sdk-scanner.js +82 -0
- package/dist/cli/inlined-sdk-scanner.js.map +1 -0
- package/dist/cli/sandbox-interlock.d.ts +97 -0
- package/dist/cli/sandbox-interlock.d.ts.map +1 -0
- package/dist/cli/sandbox-interlock.js +112 -0
- package/dist/cli/sandbox-interlock.js.map +1 -0
- package/dist/cli/sandbox-runner.d.ts +20 -12
- package/dist/cli/sandbox-runner.d.ts.map +1 -1
- package/dist/cli/sandbox-runner.js +24 -21
- package/dist/cli/sandbox-runner.js.map +1 -1
- package/dist/cli/serve.d.ts +6 -10
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +57 -77
- package/dist/cli/serve.js.map +1 -1
- package/dist/cli/unsupported-runtime.d.ts +27 -0
- package/dist/cli/unsupported-runtime.d.ts.map +1 -0
- package/dist/cli/unsupported-runtime.js +63 -0
- package/dist/cli/unsupported-runtime.js.map +1 -0
- package/dist/conformance/.generated/can-i-use-browser.d.ts +1 -1
- package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
- package/dist/conformance/.generated/can-i-use.d.ts +1 -1
- 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/functions-rtdb/child.d.ts +37 -0
- package/dist/functions-rtdb/child.d.ts.map +1 -1
- package/dist/functions-rtdb/child.js +90 -21
- package/dist/functions-rtdb/child.js.map +1 -1
- package/dist/functions-rtdb/development-runtime.d.ts +3 -0
- package/dist/functions-rtdb/development-runtime.d.ts.map +1 -1
- package/dist/functions-rtdb/development-runtime.js +1 -0
- package/dist/functions-rtdb/development-runtime.js.map +1 -1
- package/dist/google-endpoints.d.ts +67 -0
- package/dist/google-endpoints.d.ts.map +1 -0
- package/dist/google-endpoints.js +119 -0
- package/dist/google-endpoints.js.map +1 -0
- package/dist/next/runtime-env.d.ts.map +1 -1
- package/dist/next/runtime-env.js +5 -0
- package/dist/next/runtime-env.js.map +1 -1
- package/dist/next/with-pyric.d.ts +1 -1
- package/dist/next/with-pyric.js +1 -1
- package/dist/register/beacon.d.ts +69 -0
- package/dist/register/beacon.d.ts.map +1 -0
- package/dist/register/beacon.js +199 -0
- package/dist/register/beacon.js.map +1 -0
- package/dist/register/index.d.ts.map +1 -1
- package/dist/register/index.js +65 -6
- package/dist/register/index.js.map +1 -1
- package/dist/register/net-guard.d.ts +110 -0
- package/dist/register/net-guard.d.ts.map +1 -0
- package/dist/register/net-guard.js +462 -0
- package/dist/register/net-guard.js.map +1 -0
- package/dist/serve/ai-diagnostics-relay.d.ts +63 -0
- package/dist/serve/ai-diagnostics-relay.d.ts.map +1 -0
- package/dist/serve/ai-diagnostics-relay.js +125 -0
- package/dist/serve/ai-diagnostics-relay.js.map +1 -0
- package/dist/serve/ai-proxy.d.ts +92 -0
- package/dist/serve/ai-proxy.d.ts.map +1 -0
- package/dist/serve/ai-proxy.js +269 -0
- package/dist/serve/ai-proxy.js.map +1 -0
- package/dist/serve/ai-status.d.ts +44 -0
- package/dist/serve/ai-status.d.ts.map +1 -0
- package/dist/serve/ai-status.js +77 -0
- package/dist/serve/ai-status.js.map +1 -0
- package/dist/serve/ai-terminal-blocks.d.ts +97 -0
- package/dist/serve/ai-terminal-blocks.d.ts.map +1 -0
- package/dist/serve/ai-terminal-blocks.js +128 -0
- package/dist/serve/ai-terminal-blocks.js.map +1 -0
- package/dist/serve/ai-terminal-text.d.ts +36 -0
- package/dist/serve/ai-terminal-text.d.ts.map +1 -0
- package/dist/serve/ai-terminal-text.js +48 -0
- package/dist/serve/ai-terminal-text.js.map +1 -0
- package/dist/serve/beacon-route.d.ts +53 -0
- package/dist/serve/beacon-route.d.ts.map +1 -0
- package/dist/serve/beacon-route.js +101 -0
- package/dist/serve/beacon-route.js.map +1 -0
- package/dist/serve/entries/active-auth-registry.d.ts +16 -0
- package/dist/serve/entries/active-auth-registry.d.ts.map +1 -0
- package/dist/serve/entries/active-auth-registry.js +48 -0
- package/dist/serve/entries/active-auth-registry.js.map +1 -0
- package/dist/serve/entries/active-auth.d.ts +18 -0
- package/dist/serve/entries/active-auth.d.ts.map +1 -0
- package/dist/serve/entries/active-auth.js +84 -0
- package/dist/serve/entries/active-auth.js.map +1 -0
- package/dist/serve/entries/auth-helper-core.d.ts +1 -0
- package/dist/serve/entries/auth-helper-core.d.ts.map +1 -1
- package/dist/serve/entries/auth-helper-core.js +4 -0
- package/dist/serve/entries/auth-helper-core.js.map +1 -1
- package/dist/serve/entries/auth-helper-dom.d.ts.map +1 -1
- package/dist/serve/entries/auth-helper-dom.js +28 -2
- package/dist/serve/entries/auth-helper-dom.js.map +1 -1
- package/dist/serve/entries/auth.d.ts.map +1 -1
- package/dist/serve/entries/auth.js +8 -0
- package/dist/serve/entries/auth.js.map +1 -1
- package/dist/serve/entries/bridge-url.d.ts +1 -1
- package/dist/serve/entries/bridge-url.js +1 -1
- package/dist/serve/entries/init.d.ts.map +1 -1
- package/dist/serve/entries/init.js +70 -4
- package/dist/serve/entries/init.js.map +1 -1
- package/dist/serve/entries/runtime.d.ts.map +1 -1
- package/dist/serve/entries/runtime.js +9 -0
- package/dist/serve/entries/runtime.js.map +1 -1
- package/dist/serve/namespace.d.ts +14 -5
- package/dist/serve/namespace.d.ts.map +1 -1
- package/dist/serve/namespace.js +57 -124
- package/dist/serve/namespace.js.map +1 -1
- package/dist/serve/runtime/chip-config.d.ts.map +1 -1
- package/dist/serve/runtime/chip-config.js +16 -2
- package/dist/serve/runtime/chip-config.js.map +1 -1
- package/dist/serve/runtime/chip-dialog.d.ts +18 -0
- package/dist/serve/runtime/chip-dialog.d.ts.map +1 -0
- package/dist/serve/runtime/chip-dialog.js +315 -0
- package/dist/serve/runtime/chip-dialog.js.map +1 -0
- package/dist/serve/runtime/chip-install.d.ts +2 -0
- package/dist/serve/runtime/chip-install.d.ts.map +1 -1
- package/dist/serve/runtime/chip-install.js +9 -4
- package/dist/serve/runtime/chip-install.js.map +1 -1
- package/dist/serve/runtime/chip-user-search.d.ts +16 -0
- package/dist/serve/runtime/chip-user-search.d.ts.map +1 -0
- package/dist/serve/runtime/chip-user-search.js +354 -0
- package/dist/serve/runtime/chip-user-search.js.map +1 -0
- package/dist/serve/runtime/chip.d.ts +10 -0
- package/dist/serve/runtime/chip.d.ts.map +1 -1
- package/dist/serve/runtime/chip.js +118 -15
- package/dist/serve/runtime/chip.js.map +1 -1
- package/dist/serve/runtime/identity.d.ts +17 -0
- package/dist/serve/runtime/identity.d.ts.map +1 -0
- package/dist/serve/runtime/identity.js +10 -0
- package/dist/serve/runtime/identity.js.map +1 -0
- package/dist/serve/sandbox-session.d.ts +7 -0
- package/dist/serve/sandbox-session.d.ts.map +1 -1
- package/dist/serve/sandbox-session.js +2 -0
- package/dist/serve/sandbox-session.js.map +1 -1
- package/dist/serve/site-ui/_astro/{RulesCodeEditor.XtDmHOlN.js → RulesCodeEditor.DsTAsKIa.js} +1 -1
- package/dist/serve/site-ui/_astro/app.CMmTxyhL.js +1 -0
- package/dist/serve/site-ui/_astro/app.DhALsVii.js +115 -0
- package/dist/serve/site-ui/_astro/{chess-showcase.B72XYeoh.js → chess-showcase.Bn_pP6UJ.js} +2 -2
- package/dist/serve/site-ui/_astro/{example-runtime.C25_lx6Z.js → example-runtime.CXopTGv7.js} +1 -1
- package/dist/serve/site-ui/_astro/sandbox-controls.rOuZTOUG.js +510 -0
- package/dist/serve/site-ui/_astro/{seed.Co0yUJY5.js → seed.lywYbXZ0.js} +2 -2
- package/dist/serve/site-ui/_astro/writes.BsPBG3dp.js +653 -0
- 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 +8 -1
- package/dist/serve/site-ui/docs/api-reference.md +7 -0
- package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-compat/index.html +3 -3
- package/dist/serve/site-ui/docs/auth-compat.md +2 -2
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +6 -1
- package/dist/serve/site-ui/docs/build/ai-logic.md +6 -0
- package/dist/serve/site-ui/docs/build/authentication/index.html +2 -2
- package/dist/serve/site-ui/docs/build/authentication.md +1 -1
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +4 -2
- package/dist/serve/site-ui/docs/build/cloud-firestore.md +4 -0
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/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 +14 -2
- package/dist/serve/site-ui/docs/conformance-scores.md +13 -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 +44 -44
- package/dist/serve/site-ui/docs/database-compat.md +43 -43
- 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 +4 -4
- package/dist/serve/site-ui/docs/firestore-compat.md +3 -3
- package/dist/serve/site-ui/docs/firestore-flutter-compat/index.html +319 -0
- package/dist/serve/site-ui/docs/firestore-flutter-compat.md +344 -0
- package/dist/serve/site-ui/docs/firestore-kotlin-compat/index.html +319 -0
- package/dist/serve/site-ui/docs/firestore-kotlin-compat.md +344 -0
- package/dist/serve/site-ui/docs/firestore-swift-compat/index.html +490 -0
- package/dist/serve/site-ui/docs/firestore-swift-compat.md +517 -0
- 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 +105 -0
- package/dist/serve/site-ui/docs/get-started/backend-bundlers.md +165 -0
- package/dist/serve/site-ui/docs/get-started/flutter/index.html +98 -0
- package/dist/serve/site-ui/docs/get-started/flutter.md +105 -0
- 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/start-building/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
- package/dist/serve/site-ui/docs/index.json +3211 -1471
- package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +4 -3
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status.md +3 -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 +110 -0
- package/dist/serve/site-ui/docs/observe/switch-and-impersonate-identities.md +134 -0
- package/dist/serve/site-ui/docs/overview/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-database-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-messaging-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-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 +124 -0
- package/dist/serve/site-ui/docs/pyric-analytics-reference-api.md +287 -0
- package/dist/serve/site-ui/docs/pyric-app-check-reference-api/index.html +87 -0
- package/dist/serve/site-ui/docs/pyric-app-check-reference-api.md +199 -0
- 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 +6 -2
- package/dist/serve/site-ui/docs/pyric-auth-reference-api.md +2 -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 +2 -2
- package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api.md +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 +56 -0
- package/dist/serve/site-ui/docs/pyric-cli-bundler-reference-api.md +72 -0
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +4 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api.md +3 -0
- 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 +4 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api.md +3 -0
- 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-next-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api.md +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-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +34 -9
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api.md +16 -8
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +133 -93
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api.md +61 -1
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api.md +2 -2
- package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-database-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-lite-reference-api/index.html +559 -0
- package/dist/serve/site-ui/docs/pyric-firestore-lite-reference-api.md +1240 -0
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +40 -11
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api.md +18 -8
- package/dist/serve/site-ui/docs/pyric-functions-reference-api/index.html +67 -0
- package/dist/serve/site-ui/docs/pyric-functions-reference-api.md +149 -0
- 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 +35 -0
- package/dist/serve/site-ui/docs/pyric-performance-reference-api.md +69 -0
- package/dist/serve/site-ui/docs/pyric-remote-config-reference-api/index.html +132 -0
- package/dist/serve/site-ui/docs/pyric-remote-config-reference-api.md +307 -0
- package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +52 -17
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api.md +48 -9
- 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 +239 -49
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api.md +148 -31
- package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +22 -4
- package/dist/serve/site-ui/docs/pyric-storage-reference-api.md +25 -3
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +26 -96
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api.md +20 -51
- 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 +2 -2
- package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api.md +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 +2 -2
- package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +124 -26
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api.md +58 -5
- 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 +4 -5
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api.md +3 -4
- 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 +6 -3
- package/dist/serve/site-ui/docs/reference/cli.md +8 -2
- package/dist/serve/site-ui/docs/rules-compat/index.html +10 -2
- package/dist/serve/site-ui/docs/rules-compat.md +9 -1
- 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/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 +1 -1
- 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 +13 -13
- package/dist/serve/site-ui/docs/storage-compat.md +12 -12
- 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 +13 -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/studio/disk-workspace.d.ts.map +1 -1
- package/dist/serve/studio/disk-workspace.js +64 -2
- package/dist/serve/studio/disk-workspace.js.map +1 -1
- package/dist/serve/vite-plugin.d.ts +7 -7
- package/dist/serve/vite-plugin.js +1 -1
- package/dist/serve/vite-plugin.js.map +1 -1
- package/dist/serve/vite-sandbox-generation.d.ts.map +1 -1
- package/dist/serve/vite-sandbox-generation.js +12 -0
- package/dist/serve/vite-sandbox-generation.js.map +1 -1
- package/dist/serve/worker/client/auth.js +1 -2
- package/dist/serve/worker/client/auth.js.map +1 -1
- package/dist/serve/worker/client/core.d.ts +21 -1
- package/dist/serve/worker/client/core.d.ts.map +1 -1
- package/dist/serve/worker/client/core.js +79 -3
- package/dist/serve/worker/client/core.js.map +1 -1
- package/dist/serve/worker/client.d.ts +1 -1
- package/dist/serve/worker/client.d.ts.map +1 -1
- package/dist/serve/worker/client.js +1 -1
- package/dist/serve/worker/client.js.map +1 -1
- package/dist/serve/worker/context-resolver.d.ts +30 -0
- package/dist/serve/worker/context-resolver.d.ts.map +1 -0
- package/dist/serve/worker/context-resolver.js +44 -0
- package/dist/serve/worker/context-resolver.js.map +1 -0
- package/dist/serve/worker/entry.js +23 -19
- package/dist/serve/worker/entry.js.map +1 -1
- package/dist/serve/worker/host/core.d.ts +1 -0
- package/dist/serve/worker/host/core.d.ts.map +1 -1
- package/dist/serve/worker/host/core.js +12 -6
- package/dist/serve/worker/host/core.js.map +1 -1
- package/dist/serve/worker/host/storage.js +2 -2
- package/dist/serve/worker/host-auth.js +1 -2
- package/dist/serve/worker/host-auth.js.map +1 -1
- package/dist/serve/worker/index.d.ts +1 -1
- package/dist/serve/worker/index.d.ts.map +1 -1
- package/dist/serve/worker/index.js +2 -2
- package/dist/serve/worker/index.js.map +1 -1
- package/dist/serve/worker/port-lifecycle.d.ts +18 -0
- package/dist/serve/worker/port-lifecycle.d.ts.map +1 -0
- package/dist/serve/worker/port-lifecycle.js +28 -0
- package/dist/serve/worker/port-lifecycle.js.map +1 -0
- package/dist/serve/worker/serve-init.d.ts.map +1 -1
- package/dist/serve/worker/serve-init.js +8 -2
- package/dist/serve/worker/serve-init.js.map +1 -1
- package/dist/verify/fixture.d.ts +1 -1
- package/package.json +16 -5
- package/src/assurance/.generated/conformance-verdicts.ts +238 -1
- package/src/bridge/client/dispatch.ts +52 -56
- package/src/bridge/client/tool-family-factories.ts +34 -0
- package/src/bridge/server/mcp-contract.ts +15 -59
- package/src/bridge/server/peer.ts +24 -1
- package/src/bridge/server/tool-family-factories.ts +40 -0
- package/src/bridge/server/tool-metadata.ts +29 -61
- package/src/bridge/tool-families.generated.ts +17 -0
- package/src/bridge/tool-families.ts +87 -0
- package/src/bridge/tool-family-records/conformance.ts +6 -0
- package/src/bridge/tool-family-records/firestore-data.ts +15 -0
- package/src/bridge/tool-family-records/firestore-inspect.ts +6 -0
- package/src/bridge/tool-family-records/firestore-rules.ts +15 -0
- package/src/bridge/tool-family-records/firestore-simulator.ts +16 -0
- package/src/bridge/tool-family-records/rtdb-inspection.ts +6 -0
- package/src/bundler/externals.ts +55 -0
- package/src/bundler/index.ts +21 -0
- package/src/cli/cli.test.ts +0 -44
- package/src/cli/inlined-sdk-scanner.ts +77 -0
- package/src/cli/sandbox-interlock.ts +167 -0
- package/src/cli/sandbox-runner.ts +37 -26
- package/src/cli/serve.ts +68 -69
- package/src/cli/unsupported-runtime.ts +68 -0
- package/src/conformance/.generated/can-i-use-browser.ts +2 -2
- package/src/conformance/.generated/can-i-use.ts +2 -2
- package/src/conformance/.generated/conformance-docs.ts +1 -1
- package/src/functions-rtdb/child.ts +115 -21
- package/src/functions-rtdb/development-runtime.ts +4 -0
- package/src/google-endpoints.ts +155 -0
- package/src/next/runtime-env.ts +5 -0
- package/src/next/with-pyric.ts +1 -1
- package/src/register/beacon.ts +232 -0
- package/src/register/index.ts +68 -6
- package/src/register/net-guard.ts +567 -0
- package/src/serve/ai-diagnostics-relay.ts +243 -0
- package/src/serve/ai-proxy.ts +327 -0
- package/src/serve/ai-status.ts +109 -0
- package/src/serve/ai-terminal-blocks.ts +210 -0
- package/src/serve/ai-terminal-text.ts +52 -0
- package/src/serve/beacon-route.ts +141 -0
- package/src/serve/entries/active-auth-registry.ts +56 -0
- package/src/serve/entries/active-auth.ts +100 -0
- package/src/serve/entries/auth-helper-core.ts +5 -0
- package/src/serve/entries/auth-helper-dom.ts +26 -2
- package/src/serve/entries/auth.ts +8 -0
- package/src/serve/entries/bridge-url.ts +1 -1
- package/src/serve/entries/init.ts +78 -3
- package/src/serve/entries/runtime.ts +10 -0
- package/src/serve/namespace.ts +73 -140
- package/src/serve/runtime/chip-config.ts +16 -2
- package/src/serve/runtime/chip-dialog.ts +366 -0
- package/src/serve/runtime/chip-install.ts +10 -4
- package/src/serve/runtime/chip-user-search.ts +391 -0
- package/src/serve/runtime/chip.ts +140 -15
- package/src/serve/runtime/identity.ts +26 -0
- package/src/serve/sandbox-session.ts +9 -0
- package/src/serve/studio/disk-workspace.ts +76 -2
- package/src/serve/vite-plugin.ts +8 -8
- package/src/serve/vite-sandbox-generation.ts +15 -0
- package/src/serve/worker/client/auth.ts +1 -1
- package/src/serve/worker/client/core.ts +80 -3
- package/src/serve/worker/client.ts +1 -1
- package/src/serve/worker/context-resolver.ts +60 -0
- package/src/serve/worker/entry.ts +22 -18
- package/src/serve/worker/host/core.ts +9 -7
- package/src/serve/worker/host/storage.ts +2 -2
- package/src/serve/worker/host-auth.ts +1 -1
- package/src/serve/worker/index.ts +4 -1
- package/src/serve/worker/port-lifecycle.ts +45 -0
- package/src/serve/worker/serve-init.ts +9 -2
- package/src/verify/fixture.ts +1 -1
- package/dist/serve/site-ui/_astro/app.B52xr-DK.js +0 -1
- package/dist/serve/site-ui/_astro/app.DWBraPUw.js +0 -12
- package/dist/serve/site-ui/_astro/sandbox-controls.DEpnKg-O.js +0 -1169
- package/dist/serve/site-ui/_astro/writes.rpjrFzmu.js +0 -102
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
var da=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bo(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var br={exports:{}},en={};/**
|
|
2
|
+
* @license React
|
|
3
|
+
* react-jsx-runtime.production.js
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
+
*
|
|
7
|
+
* This source code is licensed under the MIT license found in the
|
|
8
|
+
* LICENSE file in the root directory of this source tree.
|
|
9
|
+
*/var Ps;function zo(){if(Ps)return en;Ps=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,s,i){var a=null;if(i!==void 0&&(a=""+i),s.key!==void 0&&(a=""+s.key),"key"in s){i={};for(var o in s)o!=="key"&&(i[o]=s[o])}else i=s;return s=i.ref,{$$typeof:t,type:r,key:a,ref:s!==void 0?s:null,props:i}}return en.Fragment=e,en.jsx=n,en.jsxs=n,en}var qs;function Vo(){return qs||(qs=1,br.exports=zo()),br.exports}var lp=Vo();function Me(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function St(t,e){if(!t)throw new Error(e||"Assertion failed")}function Dr(t,e,n){let r;Object.defineProperty(t,e,{get(){return r||(r=n.call(this)),r}})}function ha(t,e){const n=[];for(;e-- >0;)n.push(t());return n}function fa(t,e){return new Array(e+1).join(t)}function ur(t,e){return ha(()=>t,e)}function Fr(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n];t.lastIndexOf(r)!==n&&e.indexOf(r)<0&&e.push(r)}return e}function pa(t){const e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function kt(t){const e=t[0];return e===e.toUpperCase()}function ma(t){return!kt(t)}function ga(t,e,n){return t.length<e?fa(" ",e-t.length)+t:t}function Mt(){this.strings=[]}Mt.prototype.append=function(t){this.strings.push(t)};Mt.prototype.contents=function(){return this.strings.join("")};const wr=t=>String.fromCodePoint(parseInt(t,16));function ya(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 wr(t.slice(2,4));case"u":return t.charAt(2)==="{"?wr(t.slice(3,-1)):wr(t.slice(2,6));default:return t.charAt(1)}else return t}function gs(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 va(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const Wo=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Mt,abstract:Me,assert:St,checkNotNull:va,copyWithoutDuplicates:pa,defineLazyProperty:Dr,getDuplicates:Fr,isLexical:ma,isSyntactic:kt,padLeft:ga,repeat:ur,repeatFn:ha,repeatStr:fa,unescapeCodePoint:ya,unexpectedObjToString:gs},Symbol.toStringTag,{value:"Module"})),ba=t=>new RegExp(String.raw`\p{${t}}`,"u"),Mr=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,ba(t)]));Mr.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Us=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,ba(t)]));class W{constructor(){if(this.constructor===W)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Re=Object.create(W.prototype),Te=Object.create(W.prototype);class ke extends W{constructor(e){super(),this.obj=e}}class Ne extends W{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}}class Le extends W{constructor(e){super(),this.index=e}}class ge extends W{constructor(e){super(),this.terms=e}}class lr extends ge{constructor(e,n,r){const s=e.rules[n].body;super([r,s]),this.superGrammar=e,this.name=n,this.body=r}}class dr extends ge{constructor(e,n,r,s){const i=e.rules[n].body;super([...r,i,...s]),this.superGrammar=e,this.ruleName=n,this.expansionPos=r.length}}class Se extends W{constructor(e){super(),this.factors=e}}class je extends W{constructor(e){super(),this.expr=e}}class jt extends je{}class Yt extends je{}class ht extends je{}jt.prototype.operator="*";Yt.prototype.operator="+";ht.prototype.operator="?";jt.prototype.minNumMatches=0;Yt.prototype.minNumMatches=1;ht.prototype.minNumMatches=0;jt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;Yt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ht.prototype.maxNumMatches=1;class Ee extends W{constructor(e){super(),this.expr=e}}class $e extends W{constructor(e){super(),this.expr=e}}class qe extends W{constructor(e){super(),this.expr=e}}class Y extends W{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return kt(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class xe extends W{constructor(e){if(super(),this.categoryOrProp=e,e in Mr)this.pattern=Mr[e];else if(e in Us)this.pattern=Us[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function ce(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function jr(){return ce("Interval sources don't match")}function Ho(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 Go(t,e,n){const r=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return ce(r,n)}function Ko(t,e){return ce("Grammar "+t.name+" is already declared in this namespace")}function Zo(t){return ce(`Grammar '${t.name}' does not support incremental parsing`)}function wa(t,e,n){return ce("Rule "+t+" is not declared in grammar "+e,n)}function Jo(t,e,n){return ce("Cannot override rule "+t+" because it is not declared in "+e,n)}function Qo(t,e,n){return ce("Cannot extend rule "+t+" because it is not declared in "+e,n)}function Bs(t,e,n,r){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(s+=" (originally declared in '"+n+"')"),ce(s,r)}function Sa(t,e,n,r){return ce("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",r)}function Yo(t,e,n,r){return ce("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",r)}function zs(t,e,n){return ce("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function Xo(t,e){return ce("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const ec="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function tc(t,e){return ce("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function nc(t){const{ruleName:e}=t;return ce(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+ec,t.source)}function rc(t){return ce("applySyntactic is not required here (in a syntactic context)",t.source)}function Vs(t,e){return ce("Incorrect argument type: expected "+t,e.source)}function sc(t){return ce("'...' can appear at most once in a rule body",t.source)}function ic(t){const e=t._node;St(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const n=t.children.slice(1,-1).map(s=>s.source),r=n[0].coverageWith(...n.slice(1));return ce(`U+${r.contents} is not a valid Unicode code point`,r)}function _a(t,e){const n=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const i=e.map(a=>new Y(a.ruleName,a.args)).join(`
|
|
11
|
+
`);s+=`
|
|
12
|
+
Application stack (most recent application last):
|
|
13
|
+
`+i}return ce(s,t.expr.source)}function Aa(t,e,n,r){return ce("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",r.source)}function ac(t){const e=t.map(n=>n.message);return ce(["Errors:"].concat(e).join(`
|
|
14
|
+
- `),t[0].interval)}function oc(t,e,n,r){let s=r.slice(0,-1).map(c=>{const u=" "+c[0].name+" > "+c[1];return c.length===3?u+" for '"+c[2]+"'":u}).join(`
|
|
15
|
+
`);s+=`
|
|
16
|
+
`+e+" > "+t;let i="";t==="_iter"&&(i=[`
|
|
17
|
+
NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
|
|
18
|
+
`));const a=[`Missing semantic action for '${t}' in ${n} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
|
|
19
|
+
`),o=ce(a);return o.name="missingSemanticAction",o}function cc(t){if(t.length===1)throw t[0];if(t.length>1)throw ac(t)}function uc(t){let e=0;return t.map(r=>{const s=r.toString();return e=Math.max(e,s.length),s}).map(r=>ga(r,e))}function Ws(t,e,n){const r=t.length,s=t.slice(0,n),i=t.slice(n+e.length);return(s+e+i).substr(0,r)}function lc(...t){const e=this,{offset:n}=e,{repeatStr:r}=Wo,s=new Mt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
|
|
20
|
+
`);const i=uc([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(f,l,p)=>{s.append(p+i[f]+" | "+l+`
|
|
21
|
+
`)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=r(" ",o+1);for(let f=0;f<t.length;++f){let l=t[f][0],p=t[f][1];St(l>=0&&l<=p,"range start must be >= 0 and <= end");const y=n-e.colNum+1;l=Math.max(0,l-y),p=Math.min(p-y,o),c=Ws(c,r("~",p-l),l)}const u=2+i[1].length+3;return s.append(r(" ",u)),c=Ws(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
|
|
22
|
+
`),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let $r=[];function Ia(t){$r.push(t)}function dc(t){$r.forEach(e=>{e(t)}),$r=null}function ys(t,e){let n=1,r=1,s=0,i=0,a=null,o=null,c=-1;for(;s<e;){const l=t.charAt(s++);l===`
|
|
23
|
+
`?(n++,r=1,c=i,i=s):l!=="\r"&&r++}let u=t.indexOf(`
|
|
24
|
+
`,i);if(u===-1)u=t.length;else{const l=t.indexOf(`
|
|
25
|
+
`,u+1);a=l===-1?t.slice(u):t.slice(u,l),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(o=t.slice(c,i).replace(/\r?\n$/,""));const f=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:r,line:f,prevLine:o,nextLine:a,toString:lc}}function vs(t,e,...n){return ys(t,e).toString(...n)}const Hs=(()=>{let t=0;return e=>""+e+t++})();class Ce{constructor(e,n,r){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=n,this.endIdx=r}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 Ce.coverage(...e,this)}collapsedLeft(){return new Ce(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Ce(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return ys(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return vs(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw jr();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx),new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw jr();return St(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Ce(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,r=this.endIdx-e.match(/\s*$/)[0].length;return new Ce(this.sourceString,n,r)}subInterval(e,n){const r=this.startIdx+e;return new Ce(this.sourceString,r,r+n)}}Ce.coverage=function(t,...e){let{startIdx:n,endIdx:r}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw jr();n=Math.min(n,s.startIdx),r=Math.max(r,s.endIdx)}return new Ce(t.sourceString,n,r)};const hc=65535,fc=1114111;class hr{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>hc&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let r;if(n){for(r=0;r<e.length;r++){const s=this.next(),i=e[r];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(r=0;r<e.length;r++)if(this.next()!==e[r])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new Ce(this.source,e,n||this.pos)}}class Ea{constructor(e,n,r,s,i,a,o){this.matcher=e,this.input=n,this.startExpr=r,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=o,this.failed()&&(Dr(this,"message",function(){const c="Expected "+this.getExpectedText();return vs(this.input,this.getRightmostFailurePosition())+c}),Dr(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=ys(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 Mt;let n=this.getRightmostFailures();n=n.filter(r=>!r.isFluffy());for(let r=0;r<n.length;r++)r>0&&(r===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[r].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Ce(this.input,e,e)}}class pc{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:r}=this,s=r.indexOf(e.toMemoKey())+1,i=r.slice(s);n.isInvolved=function(a){return i.indexOf(a)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<r.length;a++){const o=r[a];this.isInvolved(o)||i.push(o)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:n}=this;for(let r=0;r<n.length;r++){const s=n[r];if(e.isInvolved(s))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:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach(s=>{const i=r[s];e+i.examinedLength>n?delete r[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const mc="✗",gc="✓",yc="⋅",vc="⇒",bc="␉",wc="␊",Sc="␍",Pr={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function _c(t){return ur(" ",t).join("")}function Ac(t,e,n){const r=xa(t.slice(e,e+n));return r.length<n?r+ur(" ",n-r.length).join(""):r}function xa(t){return typeof t=="string"?t.replace(/ /g,yc).replace(/\t/g,bc).replace(/\n/g,wc).replace(/\r/g,Sc):String(t)}class mt{constructor(e,n,r,s,i,a,o){this.input=e,this.pos=this.pos1=n,this.pos2=r,this.source=new Ce(e,n,r),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?Pr.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const n=new mt(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 mt(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let r=e;typeof r=="function"&&(r={enter:r});function s(i,a,o){let c=!0;r.enter&&r.enter.call(n,i,a,o)===mt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),r.exit&&r.exit.call(n,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Mt;return this.walk((n,r,s)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(Ac(n.input,n.pos,10)+_c(s*2+1)),e.append((n.succeeded?gc:mc)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){const a=xa(n.source.contents);e.append(" "+vc+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
|
|
26
|
+
`)}}),e.contents()}}mt.prototype.SKIP={};Object.keys(Pr).forEach(t=>{const e=Pr[t];Object.defineProperty(mt.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});W.prototype.allowsSkippingPrecedingSpace=Me("allowsSkippingPrecedingSpace");Re.allowsSkippingPrecedingSpace=Te.allowsSkippingPrecedingSpace=Y.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=xe.prototype.allowsSkippingPrecedingSpace=function(){return!0};ge.prototype.allowsSkippingPrecedingSpace=je.prototype.allowsSkippingPrecedingSpace=qe.prototype.allowsSkippingPrecedingSpace=$e.prototype.allowsSkippingPrecedingSpace=Ee.prototype.allowsSkippingPrecedingSpace=Le.prototype.allowsSkippingPrecedingSpace=Se.prototype.allowsSkippingPrecedingSpace=function(){return!1};let sn;Ia(t=>{sn=t});let Rn;W.prototype.assertAllApplicationsAreValid=function(t,e){Rn=0,this._assertAllApplicationsAreValid(t,e)};W.prototype._assertAllApplicationsAreValid=Me("_assertAllApplicationsAreValid");Re._assertAllApplicationsAreValid=Te._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Le.prototype._assertAllApplicationsAreValid=xe.prototype._assertAllApplicationsAreValid=function(t,e){};qe.prototype._assertAllApplicationsAreValid=function(t,e){Rn++,this.expr._assertAllApplicationsAreValid(t,e),Rn--};ge.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};Se.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};je.prototype._assertAllApplicationsAreValid=Ee.prototype._assertAllApplicationsAreValid=$e.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};Y.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const r=e.rules[this.ruleName],s=kt(t)&&Rn===0;if(!r)throw wa(this.ruleName,e.name,this.source);if(!n&&kt(this.ruleName)&&!s)throw tc(this.ruleName,this);const i=this.args.length,a=r.formals.length;if(i!==a)throw Yo(this.ruleName,a,i,this.source);const o=sn&&r===sn.rules.applySyntactic;if(sn&&r===sn.rules.caseInsensitive&&!(this.args[0]instanceof ke))throw Vs('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof Y))throw Vs("a syntactic rule application",u);if(!kt(u.ruleName))throw nc(u);if(s)throw rc(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw Xo(this.ruleName,u)})};W.prototype.assertChoicesHaveUniformArity=Me("assertChoicesHaveUniformArity");Re.assertChoicesHaveUniformArity=Te.assertChoicesHaveUniformArity=ke.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Le.prototype.assertChoicesHaveUniformArity=qe.prototype.assertChoicesHaveUniformArity=xe.prototype.assertChoicesHaveUniformArity=function(t){};ge.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 r=this.terms[n];r.assertChoicesHaveUniformArity();const s=r.getArity();if(e!==s)throw Aa(t,e,s,r)}};lr.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw Aa(t,n,e,this.terms[0])};Se.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};je.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Ee.prototype.assertChoicesHaveUniformArity=function(t){};$e.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Y.prototype.assertChoicesHaveUniformArity=function(t){};W.prototype.assertIteratedExprsAreNotNullable=Me("assertIteratedExprsAreNotNullable");Re.assertIteratedExprsAreNotNullable=Te.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Le.prototype.assertIteratedExprsAreNotNullable=xe.prototype.assertIteratedExprsAreNotNullable=function(t){};ge.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Se.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};je.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw _a(this,[])};ht.prototype.assertIteratedExprsAreNotNullable=Ee.prototype.assertIteratedExprsAreNotNullable=$e.prototype.assertIteratedExprsAreNotNullable=qe.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};Y.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class bs{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 $t extends bs{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Ic extends bs{constructor(e,n,r,s){super(s),this.ruleName=e,this.children=n,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return ma(this.ctorName)}isSyntactic(){return kt(this.ctorName)}}class ka extends bs{constructor(e,n,r,s){super(r),this.children=e,this.childOffsets=n,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}W.prototype.eval=Me("eval");Re.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();return r!==void 0?(t.pushBinding(new $t(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Te.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new $t(0),n),!0):(t.processFailure(n,this),!1)};ke.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new $t(this.obj.length),n),!0):(t.processFailure(n,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return r!==void 0&&this.from.codePointAt(0)<=r&&r<=this.to.codePointAt(0)?(t.pushBinding(new $t(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Le.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};qe.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};ge.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Se.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};je.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.getArity(),s=[],i=[];for(;s.length<r;)s.push([]),i.push([]);let a=0,o=n,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw _a(this,t._applicationStack);o=e.pos,a++;const p=t._bindings.splice(t._bindings.length-r,r),y=t._bindingOffsets.splice(t._bindingOffsets.length-r,r);for(c=0;c<p.length;c++)s[c].push(p[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(n),f=0;if(a>0){const p=s[r-1],y=i[r-1],v=y[y.length-1]+p[p.length-1].matchLength;u=i[0][0],f=v-u}const l=this instanceof ht;for(c=0;c<s.length;c++)t._bindings.push(new ka(s[c],i[c],f,l)),t._bindingOffsets.push(u);return!0};Ee.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const r=t.eval(this.expr);return t.popFailuresInfo(),r?(t.processFailure(n,this),!1):(e.pos=n,!0)};$e.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};Y.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],r=this.substituteParams(n),s=t.getCurrentPosInfo();if(s.isActive(r))return r.handleCycle(t);const i=r.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return r.reallyEval(t)};Y.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,r=this.toMemoKey();let s=e.memo[r];return n&&n.headApplication.toMemoKey()===r?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(r,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};Y.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,r=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(r,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=r.currentLeftRecursion,f=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===f;let p;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,n,u,c),r.endLeftRecursion(),p=u,p.examinedLength=e.examinedLength-n,p.rightmostFailureOffset=t._getRightmostFailureOffset(),r.memoize(f,p)):(!u||!u.isInvolved(f))&&(p=r.memoize(f,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(n,this),p&&(p.failuresAtRightmostPosition=t.cloneRecordedFailures(),p.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&p){const v=t.getTraceEntry(n,this,y,y?[c]:[]);l&&(St(v.terminatingLREntry!=null||!y),v.isHeadOfLeftRecursion=!0),p.traceEntry=v}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(r,c),y};Y.prototype.evalOnce=function(t,e){const{inputStream:n}=e,r=n.pos;if(e.eval(t)){const s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),o=n.pos-r;return new Ic(this.ruleName,i,a,o)}else return!1};Y.prototype.growSeedResult=function(t,e,n,r,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(r.matchLength=i.pos-n,r.value=s,r.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];r.traceEntry=new mt(e.input,n,i.pos,this,!0,[s],[a.clone()])}if(i.pos=n,s=this.evalOnce(t,e),i.pos-n<=r.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&r.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=n+r.matchLength,r.value};xe.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();if(r!==void 0&&r<=fc){const s=String.fromCodePoint(r);if(this.pattern.test(s))return t.pushBinding(new $t(s.length),n),!0}return t.processFailure(n,this),!1};W.prototype.getArity=Me("getArity");Re.getArity=Te.getArity=ke.prototype.getArity=Ne.prototype.getArity=Le.prototype.getArity=Y.prototype.getArity=xe.prototype.getArity=function(){return 1};ge.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Se.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};je.prototype.getArity=function(){return this.expr.getArity()};Ee.prototype.getArity=function(){return 0};$e.prototype.getArity=qe.prototype.getArity=function(){return this.expr.getArity()};function Ke(t,e){const n={};if(t.source&&e){const r=t.source.relativeTo(e);n.sourceInterval=[r.startIdx,r.endIdx]}return n}W.prototype.outputRecipe=Me("outputRecipe");Re.outputRecipe=function(t,e){return["any",Ke(this,e)]};Te.outputRecipe=function(t,e){return["end",Ke(this,e)]};ke.prototype.outputRecipe=function(t,e){return["terminal",Ke(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",Ke(this,e),this.from,this.to]};Le.prototype.outputRecipe=function(t,e){return["param",Ke(this,e),this.index]};ge.prototype.outputRecipe=function(t,e){return["alt",Ke(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};lr.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};dr.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),r=this.terms.slice(this.expansionPos+1);return["splice",Ke(this,e),n.map(s=>s.outputRecipe(t,e)),r.map(s=>s.outputRecipe(t,e))]};Se.prototype.outputRecipe=function(t,e){return["seq",Ke(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};jt.prototype.outputRecipe=Yt.prototype.outputRecipe=ht.prototype.outputRecipe=Ee.prototype.outputRecipe=$e.prototype.outputRecipe=qe.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Ke(this,e),this.expr.outputRecipe(t,e)]};Y.prototype.outputRecipe=function(t,e){return["app",Ke(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};xe.prototype.outputRecipe=function(t,e){return["unicodeChar",Ke(this,e),this.categoryOrProp]};W.prototype.introduceParams=Me("introduceParams");Re.introduceParams=Te.introduceParams=ke.prototype.introduceParams=Ne.prototype.introduceParams=Le.prototype.introduceParams=xe.prototype.introduceParams=function(t){return this};ge.prototype.introduceParams=function(t){return this.terms.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};Se.prototype.introduceParams=function(t){return this.factors.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};je.prototype.introduceParams=Ee.prototype.introduceParams=$e.prototype.introduceParams=qe.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};Y.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 Le(e).withSource(this.source)}else return this.args.forEach((n,r,s)=>{s[r]=n.introduceParams(t)}),this};W.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};W.prototype._isNullable=Me("_isNullable");Re._isNullable=Ne.prototype._isNullable=Le.prototype._isNullable=Yt.prototype._isNullable=xe.prototype._isNullable=function(t,e){return!1};Te._isNullable=function(t,e){return!0};ke.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};ge.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};Se.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};jt.prototype._isNullable=ht.prototype._isNullable=Ee.prototype._isNullable=$e.prototype._isNullable=function(t,e){return!0};qe.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};Y.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:r}=t.rules[this.ruleName],s=r.substituteParams(this.args);e[n]=!1,e[n]=s._isNullable(t,e)}return e[n]};W.prototype.substituteParams=Me("substituteParams");Re.substituteParams=Te.substituteParams=ke.prototype.substituteParams=Ne.prototype.substituteParams=xe.prototype.substituteParams=function(t){return this};Le.prototype.substituteParams=function(t){return va(t[this.index])};ge.prototype.substituteParams=function(t){return new ge(this.terms.map(e=>e.substituteParams(t)))};Se.prototype.substituteParams=function(t){return new Se(this.factors.map(e=>e.substituteParams(t)))};je.prototype.substituteParams=Ee.prototype.substituteParams=$e.prototype.substituteParams=qe.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};Y.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new Y(this.ruleName,e)}};function Gs(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function ws(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 r=1;t.forEach((s,i)=>{s===n&&(t[i]=s+"_"+r++)})})}W.prototype.toArgumentNameList=Me("toArgumentNameList");Re.toArgumentNameList=function(t,e){return["any"]};Te.toArgumentNameList=function(t,e){return["end"]};ke.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Ne.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return Gs(n)||(n="_"+n),Gs(n)||(n="$"+t),[n]};ge.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(i=>i.toArgumentNameList(t,!0)),r=[],s=n[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(n[c][i]);const o=pa(a);r.push(o.join("_or_"))}return e||ws(r),r};Se.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(r=>{const s=r.toArgumentNameList(t,!0);n=n.concat(s),t+=s.length}),e||ws(n),n};je.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(r=>r[r.length-1]==="s"?r+"es":r+"s");return e||ws(n),n};ht.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};Ee.prototype.toArgumentNameList=function(t,e){return[]};$e.prototype.toArgumentNameList=qe.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};Y.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};xe.prototype.toArgumentNameList=function(t,e){return["$"+t]};Le.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};W.prototype.toDisplayString=Me("toDisplayString");ge.prototype.toDisplayString=Se.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Re.toDisplayString=Te.toDisplayString=je.prototype.toDisplayString=Ee.prototype.toDisplayString=$e.prototype.toDisplayString=qe.prototype.toDisplayString=ke.prototype.toDisplayString=Ne.prototype.toDisplayString=Le.prototype.toDisplayString=function(){return this.toString()};Y.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};xe.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function Ec(t){return t==="description"||t==="string"||t==="code"}class Ue{constructor(e,n,r){if(!Ec(r))throw new Error("invalid Failure type: "+r);this.pexpr=e,this.text=n,this.type=r,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 Ue(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}W.prototype.toFailure=Me("toFailure");Re.toFailure=function(t){return new Ue(this,"any object","description")};Te.toFailure=function(t){return new Ue(this,"end of input","description")};ke.prototype.toFailure=function(t){return new Ue(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new Ue(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Ee.prototype.toFailure=function(t){const e=this.expr===Re?"nothing":"not "+this.expr.toFailure(t);return new Ue(this,e,"description")};$e.prototype.toFailure=function(t){return this.expr.toFailure(t)};Y.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Ue(this,e,"description")};xe.prototype.toFailure=function(t){return new Ue(this,"a Unicode ["+this.categoryOrProp+"] character","description")};ge.prototype.toFailure=function(t){const n="("+this.terms.map(r=>r.toFailure(t)).join(" or ")+")";return new Ue(this,n,"description")};Se.prototype.toFailure=function(t){const n="("+this.factors.map(r=>r.toFailure(t)).join(" ")+")";return new Ue(this,n,"description")};je.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Ue(this,e,"description")};W.prototype.toString=Me("toString");Re.toString=function(){return"any"};Te.toString=function(){return"end"};ke.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Le.prototype.toString=function(){return"$"+this.index};qe.prototype.toString=function(){return"#("+this.expr.toString()+")"};ge.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Se.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};je.prototype.toString=function(){return this.expr+this.operator};Ee.prototype.toString=function(){return"~"+this.expr};$e.prototype.toString=function(){return"&"+this.expr};Y.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};xe.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class Ss extends W{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return St(n instanceof ke,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=n.pos,s=this._getString(e);return n.matchString(s,!0)?(e.pushBinding(new $t(s.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new Ss(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Ue(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let Oa;Ia(t=>{Oa=t.rules.applySyntactic.body});const Sr=new Y("spaces");class xc{constructor(e,n,r){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new hr(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=[],r!==void 0&&(this.positionToRecordFailures=r,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 r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,r)}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(Sr),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Sr?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 pc),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const r=this.currentApplication();r&&(n=n.substituteParams(r.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(r=>{this.recordFailure(e[r],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 r=this.memoTable[e];if(r&&n instanceof Y){const s=r.memo[n.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(n);return i.isMemoized=!0,i}}return null}getTraceEntry(e,n,r,s){if(n instanceof Y){const i=this.currentApplication(),a=i?i.args:[];n=n.substituteParams(a)}return this.getMemoizedTraceEntry(e,n)||new mt(this.input,e,this.inputStream.pos,n,r,s,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 r=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&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,r=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=n.pos,o=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const f=this._bindings.slice(r),l=this.getTraceEntry(o,e,u,f);l.isImplicitSpaces=e===Sr,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(f=>{this.recordedFailures[f].makeFluffy()}):(n.pos=a,this.truncateBindings(r),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===Oa&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(r=>this.recordedFailures[r]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new Ea(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 kc{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,r){const s=this._input,i=this._memoTable;if(e<0||e>s.length||n<0||n>s.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=s.slice(0,e)+r+s.slice(n),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);const a=i.slice(n);i.length=e;for(let o=0;o<r.length;o++)i.push(void 0);for(const o of a)i.push(o);for(let o=0;o<e;o++){const c=i[o];c&&c.clearObsoleteEntries(o,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 r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!r.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw Zo(this.grammar);const s=new xc(this,e,r.positionToRecordFailures);return r.tracing?s.getTrace():s.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 r=this.grammar.parseApplication(n);return new Se([r,Te])}}const an=[],qr=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Ks{constructor(e,n,r){this._node=e,this.source=n,this._baseInterval=r,e.isNonterminal()&&St(n===r),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 r=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,r.matchLength),a=r.isNonterminal()?i:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(r,i,a)}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||[],r=n.map(a=>a._node),s=new ka(r,[],-1,!1),i=this._semantics.wrap(s,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 Pe{constructor(e,n){const r=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:Ks){constructor(s,i,a){super(s,i,a),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.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 s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:Hs(s)})}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(s){return s.super!==Pe.BuiltInSemantics._getSemantics()}let r=`(function(g) {
|
|
27
|
+
`;if(n(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let i=this.grammar;for(;i!==s;)r+=".superGrammar",i=i.superGrammar;r+=`);
|
|
28
|
+
`,r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const i=this[s.toLowerCase()+"s"];Object.keys(i).forEach(a=>{const{actionDict:o,formals:c,builtInDefault:u}=i[a];let f=a;c.length>0&&(f+="("+c.join(", ")+")");let l;n(this)&&this.super[s.toLowerCase()+"s"][a]?l="extend"+s:l="add"+s,r+=`
|
|
29
|
+
.`+l+"("+JSON.stringify(f)+", {";const p=[];Object.keys(o).forEach(y=>{if(o[y]!==u){let v=o[y].toString().trim();v=v.replace(/^.*\(/,"function("),p.push(`
|
|
30
|
+
`+JSON.stringify(y)+": "+v)}}),r+=p.join(",")+`
|
|
31
|
+
})`})}),r+=`;
|
|
32
|
+
})`,e||(r=`(function() {
|
|
33
|
+
var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
|
|
34
|
+
var semantics = `+r+`(grammar);
|
|
35
|
+
return semantics;
|
|
36
|
+
});
|
|
37
|
+
`),r}addOperationOrAttribute(e,n,r){const s=e+"s",i=Zs(n,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Oc(e,a,l),u={_default:c};Object.keys(r).forEach(p=>{u[p]=r[p]});const f=e==="operation"?new dn(a,o,u,c):new Ur(a,u,c);f.checkActionDict(this.grammar),this[s][a]=f;function l(...p){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const v=Object.create(null);for(const[T,R]of Object.entries(p)){const _=y.formals[T];v[_]=R}const b=this.args;this.args=v;const C=y.execute(this._semantics,this);return this.args=b,C}e==="operation"?(this.Wrapper.prototype[a]=l,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:l,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:Hs(a)}))}extendOperationOrAttribute(e,n,r){const s=e+"s";if(Zs(n,"attribute"),!(this.super&&n in this.super[s]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(qr(this[s],n))throw new Error("Cannot extend "+e+" '"+n+"' again");const i=this[s][n].formals,a=this[s][n].actionDict,o=Object.create(a);Object.keys(r).forEach(c=>{o[c]=r[c]}),this[s][n]=e==="operation"?new dn(n,i,o):new Ur(n,o),this[s][n].checkActionDict(this.grammar)}assertNewName(e,n){if(qr(Ks.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,r){const s=r||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,s)}}function Zs(t,e){if(!Pe.prototypeGrammar)return St(t.indexOf("(")===-1),{name:t,formals:[]};const n=Pe.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return Pe.prototypeGrammarSemantics(n).parse()}function Oc(t,e,n){return function(...r){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&r.length===1)return n.apply(r[0],i);throw oc(this.ctorName,e,t,an)}}Pe.createSemantics=function(t,e){const n=new Pe(t,e!==void 0?e:Pe.BuiltInSemantics._getSemantics()),r=function(i){if(!(i instanceof Ea))throw new TypeError("Semantics expected a MatchResult, but got "+gs(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());const a=i._cst;if(a.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+a.grammar.name+"' with a semantics for '"+t.name+"'");const o=new hr(i.input);return n.wrap(a,o.interval(i._cstOffset,i.input.length))};return r.addOperation=function(s,i){return n.addOperationOrAttribute("operation",s,i),r},r.extendOperation=function(s,i){return n.extendOperationOrAttribute("operation",s,i),r},r.addAttribute=function(s,i){return n.addOperationOrAttribute("attribute",s,i),r},r.extendAttribute=function(s,i){return n.extendOperationOrAttribute("attribute",s,i),r},r._getActionDict=function(s){const i=n.operations[s]||n.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},r._remove=function(s){let i;return s in n.operations?(i=n.operations[s],delete n.operations[s]):s in n.attributes&&(i=n.attributes[s],delete n.attributes[s]),delete n.Wrapper.prototype[s],i},r.getOperationNames=function(){return Object.keys(n.operations)},r.getAttributeNames=function(){return Object.keys(n.attributes)},r.getGrammar=function(){return n.grammar},r.toRecipe=function(s){return n.toRecipe(s)},r.toString=n.toString.bind(n),r._getSemantics=function(){return n},r};class dn{constructor(e,n,r,s){this.name=e,this.formals=n,this.actionDict=r,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{const{ctorName:r}=n._node;let s=this.actionDict[r];return s?(an.push([this,r]),s.apply(n,n._children())):n.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(an.push([this,"_nonterminal",r]),s.apply(n,n._children())):(an.push([this,"default action",r]),this.actionDict._default.apply(n,n._children()))}finally{an.pop()}}}dn.prototype.typeName="operation";class Ur extends dn{constructor(e,n,r){super(e,[],n,r)}execute(e,n){const r=n._node,s=e.attributeKeys[this.name];return qr(r,s)||(r[s]=dn.prototype.execute.call(this,e,n)),r[s]}}Ur.prototype.typeName="attribute";const Js=["_iter","_terminal","_nonterminal","_default"];function Qs(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const Cc=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let Ca,Ra;class De{constructor(e,n,r,s){if(this.name=e,this.superGrammar=n,this.rules=r,s){if(!(s in r))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new kc(this)}isBuiltIn(){return this===De.ProtoBuiltInRules||this===De.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=Qs(this),r=Qs(e);return n.length===r.length&&n.every((s,i)=>s.description===r[i].description&&s.formals.join(",")===r[i].formals.join(",")&&s.body.toString()===r[i].body.toString())}match(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.match(n)}trace(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(n)}createSemantics(){return Pe.createSemantics(this)}extendSemantics(e){return Pe.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,r){const s=[];for(const i in r){const a=r[i];if(!Js.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=a.length,u=this._topDownActionArity(i);if(c!==u){let f;i==="_iter"||i==="_nonterminal"?f=`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.`:f=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${f}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...i].join(`
|
|
38
|
+
`));throw a.problems=s,a}}_topDownActionArity(e){return Js.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 r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,f=!this.superGrammar||!this.superGrammar.rules[o];let l;f?l="define":l=u instanceof lr?"extend":"override";const p={};if(c.source&&this.source){const b=c.source.relativeTo(this.source);p.sourceInterval=[b.startIdx,b.endIdx]}const y=f?c.description:null,v=u.outputRecipe(c.formals,this.source);s[o]=[l,p,y,c.formals,v]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",n,this.name].map(JSON.stringify),i,...[r,s].map(JSON.stringify)];return Cc(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Mt;e.append("{");let n=!0;for(const r in this.rules){const{body:s}=this.rules[r];n?n=!1:e.append(","),e.append(`
|
|
39
|
+
`),e.append(" "),this.addSemanticActionTemplate(r,s,e)}return e.append(`
|
|
40
|
+
}`),e.contents()}addSemanticActionTemplate(e,n,r){r.append(e),r.append(": function(");const s=this._topDownActionArity(e);r.append(ur("_",s).join(", ")),r.append(`) {
|
|
41
|
+
`),r.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new Y(e);else{const s=Ca.match(e,"Base_application");n=Ra(s,{})}if(!(n.ruleName in this.rules))throw wa(n.ruleName,this.name);const{formals:r}=this.rules[n.ruleName];if(r.length!==n.args.length){const{source:s}=this.rules[n.ruleName];throw Sa(n.ruleName,r.length,n.args.length,s)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}De.ProtoBuiltInRules=new De("ProtoBuiltInRules",void 0,{any:{body:Re,formals:[],description:"any character",primitive:!0},end:{body:Te,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Ss(new Le(0)),formals:["str"],primitive:!0},lower:{body:new xe("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new xe("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new xe("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new jt(new Y("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});De.initApplicationParser=function(t,e){Ca=t,Ra=e};class Ys{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?De.ProtoBuiltInRules:De.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const r=this.ensureSuperGrammar().rules[e];if(!r)throw Jo(e,this.superGrammar.name,n);return r}installOverriddenOrExtendedRule(e,n,r,s){const i=Fr(n);if(i.length>0)throw zs(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(n.length!==c)throw Sa(e,c,n.length,s);return this.install(e,n,r,a.description,s)}install(e,n,r,s,i,a=!1){return this.rules[e]={body:r.introduceParams(n),formals:n,description:s,source:i,primitive:a},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 hr(e).interval(0,e.length),this}build(){const e=new De(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const n=[];let r=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){n.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){n.push(a),r=!0}}),r||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){n.push(a)}}),n.length>0&&cc(n),this.source&&(e.source=this.source),e}define(e,n,r,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Bs(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw Bs(e,this.name,this.name,i);const o=Fr(n);if(o.length>0)throw zs(e,o,i);return this.install(e,n,r,s,i,a)}override(e,n,r,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,n,r,i),this}extend(e,n,r,s,i){if(!this.ensureSuperGrammar().rules[e])throw Qo(e,this.superGrammar.name,i);const o=new lr(this.superGrammar,e,r);return o.source=r.source,this.installOverriddenOrExtendedRule(e,n,o,i),this}}class Tn{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new Ys(e)}grammar(e,n,r,s,i){const a=new Ys(n);return r&&a.withSuperGrammar(r instanceof De?r:this.fromRecipe(r)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],f=c[1],l=c[2],p=c[3],y=this.fromRecipe(c[4]);let v;a.source&&f&&f.sourceInterval&&(v=a.source.subInterval(f.sourceInterval[0],f.sourceInterval[1]-f.sourceInterval[0])),a[u](o,p,y,l,v)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new ke(e)}range(e,n){return new Ne(e,n)}param(e){return new Le(e)}alt(...e){let n=[];for(let r of e)r instanceof W||(r=this.fromRecipe(r)),r instanceof ge?n=n.concat(r.terms):n.push(r);return n.length===1?n[0]:new ge(n)}seq(...e){let n=[];for(let r of e)r instanceof W||(r=this.fromRecipe(r)),r instanceof Se?n=n.concat(r.factors):n.push(r);return n.length===1?n[0]:new Se(n)}star(e){return e instanceof W||(e=this.fromRecipe(e)),new jt(e)}plus(e){return e instanceof W||(e=this.fromRecipe(e)),new Yt(e)}opt(e){return e instanceof W||(e=this.fromRecipe(e)),new ht(e)}not(e){return e instanceof W||(e=this.fromRecipe(e)),new Ee(e)}lookahead(e){return e instanceof W||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new Ee(new Ee(e)):new $e(e)}lex(e){return e instanceof W||(e=this.fromRecipe(e)),new qe(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(r){return r instanceof W?r:this.fromRecipe(r)},this)),new Y(e,n)}splice(e,n){return new dr(this.currentDecl.superGrammar,this.currentRuleName,e.map(r=>this.fromRecipe(r)),n.map(r=>this.fromRecipe(r)))}fromRecipe(e){const n=e[0]==="grammar"?e.slice(1):e.slice(2),r=this[e[0]](...n),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&r.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),r}}function _s(t){return typeof t=="function"?t.call(new Tn):(typeof t=="string"&&(t=JSON.parse(t)),new Tn().fromRecipe(t))}const As=_s(["grammar",{source:`BuiltInRules {
|
|
42
|
+
|
|
43
|
+
alnum (an alpha-numeric character)
|
|
44
|
+
= letter
|
|
45
|
+
| digit
|
|
46
|
+
|
|
47
|
+
letter (a letter)
|
|
48
|
+
= lower
|
|
49
|
+
| upper
|
|
50
|
+
| unicodeLtmo
|
|
51
|
+
|
|
52
|
+
digit (a digit)
|
|
53
|
+
= "0".."9"
|
|
54
|
+
|
|
55
|
+
hexDigit (a hexadecimal digit)
|
|
56
|
+
= digit
|
|
57
|
+
| "a".."f"
|
|
58
|
+
| "A".."F"
|
|
59
|
+
|
|
60
|
+
ListOf<elem, sep>
|
|
61
|
+
= NonemptyListOf<elem, sep>
|
|
62
|
+
| EmptyListOf<elem, sep>
|
|
63
|
+
|
|
64
|
+
NonemptyListOf<elem, sep>
|
|
65
|
+
= elem (sep elem)*
|
|
66
|
+
|
|
67
|
+
EmptyListOf<elem, sep>
|
|
68
|
+
= /* nothing */
|
|
69
|
+
|
|
70
|
+
listOf<elem, sep>
|
|
71
|
+
= nonemptyListOf<elem, sep>
|
|
72
|
+
| emptyListOf<elem, sep>
|
|
73
|
+
|
|
74
|
+
nonemptyListOf<elem, sep>
|
|
75
|
+
= elem (sep elem)*
|
|
76
|
+
|
|
77
|
+
emptyListOf<elem, sep>
|
|
78
|
+
= /* nothing */
|
|
79
|
+
|
|
80
|
+
// Allows a syntactic rule application within a lexical context.
|
|
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]]}]);De.BuiltInRules=As;dc(De.BuiltInRules);const Is=_s(["grammar",{source:`Ohm {
|
|
83
|
+
|
|
84
|
+
Grammars
|
|
85
|
+
= Grammar*
|
|
86
|
+
|
|
87
|
+
Grammar
|
|
88
|
+
= ident SuperGrammar? "{" Rule* "}"
|
|
89
|
+
|
|
90
|
+
SuperGrammar
|
|
91
|
+
= "<:" ident
|
|
92
|
+
|
|
93
|
+
Rule
|
|
94
|
+
= ident Formals? ruleDescr? "=" RuleBody -- define
|
|
95
|
+
| ident Formals? ":=" OverrideRuleBody -- override
|
|
96
|
+
| ident Formals? "+=" RuleBody -- extend
|
|
97
|
+
|
|
98
|
+
RuleBody
|
|
99
|
+
= "|"? NonemptyListOf<TopLevelTerm, "|">
|
|
100
|
+
|
|
101
|
+
TopLevelTerm
|
|
102
|
+
= Seq caseName -- inline
|
|
103
|
+
| Seq
|
|
104
|
+
|
|
105
|
+
OverrideRuleBody
|
|
106
|
+
= "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
|
|
107
|
+
|
|
108
|
+
OverrideTopLevelTerm
|
|
109
|
+
= "..." -- superSplice
|
|
110
|
+
| TopLevelTerm
|
|
111
|
+
|
|
112
|
+
Formals
|
|
113
|
+
= "<" ListOf<ident, ","> ">"
|
|
114
|
+
|
|
115
|
+
Params
|
|
116
|
+
= "<" ListOf<Seq, ","> ">"
|
|
117
|
+
|
|
118
|
+
Alt
|
|
119
|
+
= NonemptyListOf<Seq, "|">
|
|
120
|
+
|
|
121
|
+
Seq
|
|
122
|
+
= Iter*
|
|
123
|
+
|
|
124
|
+
Iter
|
|
125
|
+
= Pred "*" -- star
|
|
126
|
+
| Pred "+" -- plus
|
|
127
|
+
| Pred "?" -- opt
|
|
128
|
+
| Pred
|
|
129
|
+
|
|
130
|
+
Pred
|
|
131
|
+
= "~" Lex -- not
|
|
132
|
+
| "&" Lex -- lookahead
|
|
133
|
+
| Lex
|
|
134
|
+
|
|
135
|
+
Lex
|
|
136
|
+
= "#" Base -- lex
|
|
137
|
+
| Base
|
|
138
|
+
|
|
139
|
+
Base
|
|
140
|
+
= ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
|
|
141
|
+
| oneCharTerminal ".." oneCharTerminal -- range
|
|
142
|
+
| terminal -- terminal
|
|
143
|
+
| "(" Alt ")" -- paren
|
|
144
|
+
|
|
145
|
+
ruleDescr (a rule description)
|
|
146
|
+
= "(" ruleDescrText ")"
|
|
147
|
+
|
|
148
|
+
ruleDescrText
|
|
149
|
+
= (~")" any)*
|
|
150
|
+
|
|
151
|
+
caseName
|
|
152
|
+
= "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
|
|
153
|
+
|
|
154
|
+
name (a name)
|
|
155
|
+
= nameFirst nameRest*
|
|
156
|
+
|
|
157
|
+
nameFirst
|
|
158
|
+
= "_"
|
|
159
|
+
| letter
|
|
160
|
+
|
|
161
|
+
nameRest
|
|
162
|
+
= "_"
|
|
163
|
+
| alnum
|
|
164
|
+
|
|
165
|
+
ident (an identifier)
|
|
166
|
+
= name
|
|
167
|
+
|
|
168
|
+
terminal
|
|
169
|
+
= "\\"" terminalChar* "\\""
|
|
170
|
+
|
|
171
|
+
oneCharTerminal
|
|
172
|
+
= "\\"" terminalChar "\\""
|
|
173
|
+
|
|
174
|
+
terminalChar
|
|
175
|
+
= escapeChar
|
|
176
|
+
| ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
|
|
177
|
+
|
|
178
|
+
escapeChar (an escape sequence)
|
|
179
|
+
= "\\\\\\\\" -- backslash
|
|
180
|
+
| "\\\\\\"" -- doubleQuote
|
|
181
|
+
| "\\\\\\'" -- singleQuote
|
|
182
|
+
| "\\\\b" -- backspace
|
|
183
|
+
| "\\\\n" -- lineFeed
|
|
184
|
+
| "\\\\r" -- carriageReturn
|
|
185
|
+
| "\\\\t" -- tab
|
|
186
|
+
| "\\\\u{" hexDigit hexDigit? hexDigit?
|
|
187
|
+
hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
|
|
188
|
+
| "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
|
|
189
|
+
| "\\\\x" hexDigit hexDigit -- hexEscape
|
|
190
|
+
|
|
191
|
+
space
|
|
192
|
+
+= comment
|
|
193
|
+
|
|
194
|
+
comment
|
|
195
|
+
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
196
|
+
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
197
|
+
|
|
198
|
+
tokens = token*
|
|
199
|
+
|
|
200
|
+
token = caseName | comment | ident | operator | punctuation | terminal | any
|
|
201
|
+
|
|
202
|
+
operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
|
|
203
|
+
|
|
204
|
+
punctuation = "<" | ">" | "," | "--"
|
|
205
|
+
}`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
|
|
206
|
+
`]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
|
|
207
|
+
`]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
|
|
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
|
+
`]],["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
|
+
`]],["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]},"--"]]]}]),_r=Object.create(W.prototype);function Xs(t,e){for(const n in t)if(n===e)return!0;return!1}function Ta(t,e,n,r){const s=new Tn(r);let i,a,o,c=!1;return(n||Is).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(p=>p.visit())},Grammar(l,p,y,v,b){const C=l.visit();i=s.newGrammar(C),p.child(0)&&p.child(0).visit(),v.children.map(R=>R.visit());const T=i.build();if(T.source=this.source.trimmed(),Xs(e,C))throw Ko(T);return e[C]=T,T},SuperGrammar(l,p){const y=p.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Xs(e,y))throw Go(y,e,p.source);i.withSuperGrammar(e[y])}},Rule_define(l,p,y,v,b){a=l.visit(),o=p.children.map(_=>_.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==De.ProtoBuiltInRules&&i.withDefaultStartRule(a);const C=b.visit(),T=y.children.map(_=>_.visit())[0],R=this.source.trimmed();return i.define(a,o,C,T,R)},Rule_override(l,p,y,v){a=l.visit(),o=p.children.map(T=>T.visit())[0]||[];const b=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,b),c=!0;const C=v.visit();return c=!1,i.override(a,o,C,null,b)},Rule_extend(l,p,y,v){a=l.visit(),o=p.children.map(T=>T.visit())[0]||[];const b=v.visit(),C=this.source.trimmed();return i.extend(a,o,b,null,C)},RuleBody(l,p){return s.alt(...p.visit()).withSource(this.source)},OverrideRuleBody(l,p){const y=p.visit(),v=y.indexOf(_r);if(v>=0){const b=y.slice(0,v),C=y.slice(v+1);return C.forEach(T=>{if(T===_r)throw sc(T)}),new dr(i.superGrammar,a,b,C).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,p,y){return p.visit()},Params(l,p,y){return p.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,p){const y=a+"_"+p.visit(),v=l.visit(),b=this.source.trimmed(),C=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!C?i.override(y,o,v,null,b):i.define(y,o,v,null,b);const T=o.map(R=>s.app(R));return s.app(y,T).withSource(v.source)},OverrideTopLevelTerm_superSplice(l){return _r},Seq(l){return s.seq(...l.children.map(p=>p.visit())).withSource(this.source)},Iter_star(l,p){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,p){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,p){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,p){return s.not(p.visit()).withSource(this.source)},Pred_lookahead(l,p){return s.lookahead(p.visit()).withSource(this.source)},Lex_lex(l,p){return s.lex(p.visit()).withSource(this.source)},Base_application(l,p){const y=p.children.map(v=>v.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,p,y){return s.range(l.visit(),y.visit()).withSource(this.source)},Base_terminal(l){return s.terminal(l.visit()).withSource(this.source)},Base_paren(l,p,y){return p.visit()},ruleDescr(l,p,y){return p.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,p,y,v,b){return y.visit()},name(l,p){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,p,y){return p.children.map(v=>v.visit()).join("")},oneCharTerminal(l,p,y){return p.visit()},escapeChar(l){try{return ya(this.sourceString)}catch(p){throw p instanceof RangeError&&p.message.startsWith("Invalid code point ")?ic(l):p}},NonemptyListOf(l,p,y){return[l.visit()].concat(y.children.map(v=>v.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const Rc=_s(["grammar",{source:`OperationsAndAttributes {
|
|
212
|
+
|
|
213
|
+
AttributeSignature =
|
|
214
|
+
name
|
|
215
|
+
|
|
216
|
+
OperationSignature =
|
|
217
|
+
name Formals?
|
|
218
|
+
|
|
219
|
+
Formals
|
|
220
|
+
= "(" ListOf<name, ","> ")"
|
|
221
|
+
|
|
222
|
+
name (a name)
|
|
223
|
+
= nameFirst nameRest*
|
|
224
|
+
|
|
225
|
+
nameFirst
|
|
226
|
+
= "_"
|
|
227
|
+
| letter
|
|
228
|
+
|
|
229
|
+
nameRest
|
|
230
|
+
= "_"
|
|
231
|
+
| alnum
|
|
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",[]]]]}]);Tc(De.BuiltInRules);Nc(Rc);function Tc(t){const e={empty(){return this.iteration()},nonEmpty(n,r,s){return this.iteration([n].concat(s.children))},self(...n){return this}};Pe.BuiltInSemantics=Pe.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function Nc(t){Pe.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(r=>r.parse())[0]||[]}},Formals(e,n,r){return n.asIteration().children.map(s=>s.parse())},name(e,n){return this.sourceString}}),Pe.prototypeGrammar=t}function Lc(t){let e=0;const n=[0],r=()=>n[n.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g;let a;for(;(a=i.exec(t))!=null;){const[o,c]=a;if(o.length===0)break;const u=c.length,f=r(),l=e+u;if(u>f)n.push(u),s[l]=1;else if(u<f){const p=n.length;for(;r()!==u;)n.pop();s[l]=-1*(p-n.length)}e+=o.length}return n.length>1&&(s[e]=1-n.length),s}const Na="an indented block",La="a dedent",ei=1114112;class Dc extends hr{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),ei):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),ei):super.nextCodePoint()}}class ti extends W{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=e.userData;e.doNotMemoize=!0;const s=n.pos,i=this.isIndent?1:-1;return(r[s]||0)*i>0?(e.userData=Object.create(r),e.userData[s]-=i,e.pushBinding(new $t(0),s),!0):(e.processFailure(s,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?Na:La;return new Ue(this,n,"description")}}const Fc=new Y("indent"),Mc=new Y("dedent"),jc=new dr(As,"any",[Fc,Mc],[]),$c=new Tn().newGrammar("IndentationSensitive").withSuperGrammar(As).define("indent",[],new ti(!0),Na,void 0,!0).define("dedent",[],new ti(!1),La,void 0,!0).extend("any",[],jc,"any character",void 0).build();Object.assign($c,{_matchStateInitializer(t){t.userData=Lc(t.input),t.inputStream=new Dc(t)},supportsIncrementalParsing:!1});De.initApplicationParser(Is,Ta);const Pc=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function qc(t,e,n){const r=Is.match(t,"Grammars");if(r.failed())throw Ho(r);return Ta(r,e,void 0,n)}function Uc(t,e,n){const r=Bc(t,e,n),s=Object.keys(r);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const a=r[s[1]].source;throw new Error(vs(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return r[s[0]]}function Bc(t,e,n){const r=Object.create({});if(typeof t!="string")if(Pc(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+gs(t));return qc(t,r,n),r}function zc(t,e){return Uc(t,e)}const Vc=`FirestoreRules {
|
|
234
|
+
// === Top-level ===
|
|
235
|
+
// Syntactic rules (capitalized) auto-skip spaces between terms.
|
|
236
|
+
// Lexical rules (lowercase) do NOT skip spaces.
|
|
237
|
+
|
|
238
|
+
// Two accepted orderings. Real \`firestore.rules\` files put
|
|
239
|
+
// \`rules_version\` at line 1 (Firebase convention), so the
|
|
240
|
+
// \`versionFirst\` branch matches that natural shape. The
|
|
241
|
+
// \`importsFirst\` branch keeps legacy samples that put \`import\`
|
|
242
|
+
// declarations above the version line working. The semantic
|
|
243
|
+
// action below normalizes both into the same AST shape, so
|
|
244
|
+
// downstream code doesn't have to care which path matched.
|
|
245
|
+
// Declaration order is STRICT: imports, then functions (#347 probe,
|
|
246
|
+
// 2026-07-17): the production Rules Test API rejects \`import\` after a
|
|
247
|
+
// \`function\` ("Unexpected 'import'") and any declaration before
|
|
248
|
+
// \`rules_version\` ("Unexpected 'rules_version'"), under both
|
|
249
|
+
// rules_version '2' and '2+modules'. Pinned by
|
|
250
|
+
// test/rules/corpus/invalid/009-/010-.
|
|
251
|
+
RulesFile = RulesVersion? ImportDecl* FunctionDef* ServiceBlock -- versionFirst
|
|
252
|
+
| ImportDecl* RulesVersion FunctionDef* ServiceBlock -- importsFirst
|
|
253
|
+
|
|
254
|
+
ImportDecl = "import" "{" ListOf<ident, ","> ","? "}" "from" string ";"
|
|
255
|
+
|
|
256
|
+
RulesVersion = "rules_version" "=" string ";"
|
|
257
|
+
|
|
258
|
+
ServiceBlock = "service" serviceName "{" FunctionDef* DocumentsMatch FunctionDef* "}"
|
|
259
|
+
|
|
260
|
+
DocumentsMatch = "match" matchPath "{" MatchBody "}"
|
|
261
|
+
|
|
262
|
+
MatchBody = MatchBodyItem*
|
|
263
|
+
|
|
264
|
+
MatchBodyItem
|
|
265
|
+
= FunctionDef
|
|
266
|
+
| MatchBlock
|
|
267
|
+
| AllowStatement
|
|
268
|
+
|
|
269
|
+
MatchBlock = "match" matchPath "{" MatchBody "}"
|
|
270
|
+
|
|
271
|
+
// === Statements ===
|
|
272
|
+
|
|
273
|
+
AllowStatement = "allow" OperationList ":" "if" Expr ";"
|
|
274
|
+
|
|
275
|
+
OperationList = Operation ("," Operation)*
|
|
276
|
+
|
|
277
|
+
FunctionDef = "export"? "function" ident "(" ParameterList ")" "{" FunctionBody "}"
|
|
278
|
+
|
|
279
|
+
ParameterList = ListOf<ident, ",">
|
|
280
|
+
|
|
281
|
+
FunctionBody = LetBinding* ReturnStatement
|
|
282
|
+
|
|
283
|
+
LetBinding = "let" ident "=" Expr ";"
|
|
284
|
+
|
|
285
|
+
ReturnStatement = "return" Expr ";"
|
|
286
|
+
|
|
287
|
+
// === Lexical: operations and service name ===
|
|
288
|
+
|
|
289
|
+
Operation
|
|
290
|
+
= "read" ~identChar
|
|
291
|
+
| "write" ~identChar
|
|
292
|
+
| "get" ~identChar
|
|
293
|
+
| "list" ~identChar
|
|
294
|
+
| "create" ~identChar
|
|
295
|
+
| "update" ~identChar
|
|
296
|
+
| "delete" ~identChar
|
|
297
|
+
|
|
298
|
+
serviceName = letter (letter | ".")*
|
|
299
|
+
|
|
300
|
+
// === Lexical: match paths ===
|
|
301
|
+
|
|
302
|
+
matchPath = "/" matchPathSegment ("/" matchPathSegment)*
|
|
303
|
+
|
|
304
|
+
matchPathSegment
|
|
305
|
+
= "{" matchWildcard "}" -- wildcard
|
|
306
|
+
| pathIdent -- literal
|
|
307
|
+
|
|
308
|
+
matchWildcard
|
|
309
|
+
= identStart identChar* "=" "**" -- recursive
|
|
310
|
+
| identStart identChar* -- single
|
|
311
|
+
|
|
312
|
+
pathIdent = (letter | digit | "_" | "-" | ".")+
|
|
313
|
+
|
|
314
|
+
// === Expressions ===
|
|
315
|
+
|
|
316
|
+
Expr = Ternary
|
|
317
|
+
|
|
318
|
+
Ternary
|
|
319
|
+
= LogicalOr "?" Ternary ":" Ternary -- ternary
|
|
320
|
+
| LogicalOr
|
|
321
|
+
|
|
322
|
+
LogicalOr
|
|
323
|
+
= LogicalOr "||" LogicalAnd -- or
|
|
324
|
+
| LogicalAnd
|
|
325
|
+
|
|
326
|
+
LogicalAnd
|
|
327
|
+
= LogicalAnd "&&" InIsExpr -- and
|
|
328
|
+
| InIsExpr
|
|
329
|
+
|
|
330
|
+
InIsExpr
|
|
331
|
+
= Equality in Equality -- in
|
|
332
|
+
| Equality is typeName -- is
|
|
333
|
+
| Equality
|
|
334
|
+
|
|
335
|
+
in = "in" ~identChar
|
|
336
|
+
is = "is" ~identChar
|
|
337
|
+
|
|
338
|
+
Equality
|
|
339
|
+
= Equality "==" Comparison -- eq
|
|
340
|
+
| Equality "!=" Comparison -- neq
|
|
341
|
+
| Comparison
|
|
342
|
+
|
|
343
|
+
Comparison
|
|
344
|
+
= Comparison ">=" Additive -- gte
|
|
345
|
+
| Comparison "<=" Additive -- lte
|
|
346
|
+
| Comparison ">" Additive -- gt
|
|
347
|
+
| Comparison "<" Additive -- lt
|
|
348
|
+
| Additive
|
|
349
|
+
|
|
350
|
+
Additive
|
|
351
|
+
= Additive "+" Multiplicative -- add
|
|
352
|
+
| Additive "-" Multiplicative -- sub
|
|
353
|
+
| Multiplicative
|
|
354
|
+
|
|
355
|
+
Multiplicative
|
|
356
|
+
= Multiplicative "*" UnaryExpr -- mul
|
|
357
|
+
| Multiplicative "/" UnaryExpr -- div
|
|
358
|
+
| Multiplicative "%" UnaryExpr -- mod
|
|
359
|
+
| UnaryExpr
|
|
360
|
+
|
|
361
|
+
UnaryExpr
|
|
362
|
+
= "!" UnaryExpr -- not
|
|
363
|
+
| "-" UnaryExpr -- neg
|
|
364
|
+
| PostfixExpr
|
|
365
|
+
|
|
366
|
+
PostfixExpr
|
|
367
|
+
= PostfixExpr "." memberName "(" ListOf<Expr, ","> ")" -- methodCall
|
|
368
|
+
| PostfixExpr "." memberName -- memberAccess
|
|
369
|
+
| PostfixExpr "[" Expr ":" Expr "]" -- sliceAccess
|
|
370
|
+
| PostfixExpr "[" Expr "]" -- bracketAccess
|
|
371
|
+
| Primary
|
|
372
|
+
|
|
373
|
+
memberName = identStart identChar*
|
|
374
|
+
|
|
375
|
+
Primary
|
|
376
|
+
= "(" Expr ")" -- paren
|
|
377
|
+
| PathLiteral -- path
|
|
378
|
+
| ListLiteral -- list
|
|
379
|
+
| MapLiteral -- map
|
|
380
|
+
| ident "(" ListOf<Expr, ","> ")" -- functionCall
|
|
381
|
+
| literal
|
|
382
|
+
| ident
|
|
383
|
+
|
|
384
|
+
// === Path literals ===
|
|
385
|
+
|
|
386
|
+
PathLiteral = "/" PathLitSegment ("/" PathLitSegment)*
|
|
387
|
+
|
|
388
|
+
PathLitSegment
|
|
389
|
+
= "$(" Expr ")" -- interpolation
|
|
390
|
+
| "{" ident "}" -- captureRef
|
|
391
|
+
| "(" pathIdent ")" -- parenLiteral
|
|
392
|
+
| pathIdent -- literal
|
|
393
|
+
|
|
394
|
+
// === Literals ===
|
|
395
|
+
|
|
396
|
+
literal
|
|
397
|
+
= number
|
|
398
|
+
| string
|
|
399
|
+
| bool
|
|
400
|
+
| null
|
|
401
|
+
|
|
402
|
+
number
|
|
403
|
+
= digit+ "." digit+ -- float
|
|
404
|
+
| digit+ -- int
|
|
405
|
+
|
|
406
|
+
string
|
|
407
|
+
= "'" singleStringChar* "'" -- single
|
|
408
|
+
| "\\"" doubleStringChar* "\\"" -- double
|
|
409
|
+
|
|
410
|
+
singleStringChar
|
|
411
|
+
= "\\\\" stringEscapeChar -- escape
|
|
412
|
+
| ~"\\\\" ~"'" any -- char
|
|
413
|
+
|
|
414
|
+
doubleStringChar
|
|
415
|
+
= "\\\\" stringEscapeChar -- escape
|
|
416
|
+
| ~"\\\\" ~"\\"" any -- char
|
|
417
|
+
|
|
418
|
+
// Valid escape characters following a backslash. Anything else is rejected
|
|
419
|
+
// at parse time to match production semantics — production Firestore Rules
|
|
420
|
+
// raises a syntax error on unknown escapes (e.g. \`\\d\`, \`\\.\`). Keeping the
|
|
421
|
+
// sim strict here prevents over-permissive acceptance that masks model
|
|
422
|
+
// output that would crash at deploy.
|
|
423
|
+
stringEscapeChar = "\\\\" | "'" | "\\"" | "n" | "r" | "t" | "/"
|
|
424
|
+
|
|
425
|
+
ListLiteral = "[" ListOf<Expr, ","> ","? "]"
|
|
426
|
+
|
|
427
|
+
MapLiteral = "{" ListOf<MapEntry, ","> ","? "}"
|
|
428
|
+
|
|
429
|
+
MapEntry = (string | ident) ":" Expr
|
|
430
|
+
|
|
431
|
+
bool
|
|
432
|
+
= "true" ~identChar -- true
|
|
433
|
+
| "false" ~identChar -- false
|
|
434
|
+
|
|
435
|
+
null = "null" ~identChar
|
|
436
|
+
|
|
437
|
+
typeName
|
|
438
|
+
= "string" ~identChar
|
|
439
|
+
| "int" ~identChar
|
|
440
|
+
| "float" ~identChar
|
|
441
|
+
| "number" ~identChar
|
|
442
|
+
| "bool" ~identChar
|
|
443
|
+
| "list" ~identChar
|
|
444
|
+
| "map" ~identChar
|
|
445
|
+
| "timestamp" ~identChar
|
|
446
|
+
| "path" ~identChar
|
|
447
|
+
| "bytes" ~identChar
|
|
448
|
+
| "duration" ~identChar
|
|
449
|
+
| "latlng" ~identChar
|
|
450
|
+
| "reference" ~identChar
|
|
451
|
+
|
|
452
|
+
ident = ~keyword identStart identChar*
|
|
453
|
+
|
|
454
|
+
keyword
|
|
455
|
+
= ("true" | "false" | "null" | "in" | "is" | "if" | "return" | "let") ~identChar
|
|
456
|
+
|
|
457
|
+
identStart = letter | "_"
|
|
458
|
+
|
|
459
|
+
identChar = alnum | "_"
|
|
460
|
+
|
|
461
|
+
// === Whitespace and comments ===
|
|
462
|
+
|
|
463
|
+
space += comment
|
|
464
|
+
|
|
465
|
+
comment
|
|
466
|
+
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
467
|
+
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
468
|
+
}
|
|
469
|
+
`,Da=zc(Vc),Fa=Da.createSemantics();Fa.addOperation("toAST",{RulesFile_versionFirst(t,e,n,r){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:n.children.map(s=>s.toAST()),service:r.toAST()}},RulesFile_importsFirst(t,e,n,r){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:n.children.map(s=>s.toAST()),service:r.toAST()}},ImportDecl(t,e,n,r,s,i,a,o){const{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{functions:n.asIteration().children.map(f=>f.sourceString),module:a.toAST().value,loc:{line:c,col:u}}},RulesVersion(t,e,n,r){return n.toAST().value},ServiceBlock(t,e,n,r,s,i,a){const{lineNum:o,colNum:c}=t.source.getLineAndColumn();return{name:e.sourceString,functions:[...r.children.map(u=>u.toAST()),...i.children.map(u=>u.toAST())],match:s.toAST(),loc:{line:o,col:c}}},DocumentsMatch(t,e,n,r,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...r.toAST(),path:ri(e.sourceString),loc:{line:i,col:a}}},MatchBody(t){const e=[],n=[],r=[];for(const s of t.children){const i=s.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?n.push(i):i._kind==="match"&&r.push(i)}return{functions:e,allows:n,children:r}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,r,s){const{functions:i,allows:a,children:o}=r.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:ri(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,n,r,s,i){const{lineNum:a,colNum:o}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:a,col:o}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(r=>r.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,r,s,i,a,o,c){const{lets:u,expr:f}=o.toAST(),{lineNum:l,colNum:p}=e.source.getLineAndColumn();let y=!1;return t.sourceString.trim()==="export"&&(y=!0),{_kind:"function",name:n.sourceString,parameters:s.toAST(),exported:y,lets:u,body:f,loc:{line:l,col:p}}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(n=>n.toAST()),expr:e.toAST()}},LetBinding(t,e,n,r,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{name:e.sourceString,value:r.toAST(),loc:{line:i,col:a}}},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,r,s){return{type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,n){return{type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()}},LogicalAnd_and(t,e,n){return{type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()}},InIsExpr_in(t,e,n){return{type:"inExpr",element:t.toAST(),collection:n.toAST()}},InIsExpr_is(t,e,n){return{type:"isExpr",value:t.toAST(),typeName:n.sourceString}},Equality_eq(t,e,n){return{type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()}},Equality_neq(t,e,n){return{type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()}},Comparison_gte(t,e,n){return{type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()}},Comparison_lte(t,e,n){return{type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()}},Comparison_gt(t,e,n){return{type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()}},Comparison_lt(t,e,n){return{type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()}},Additive_add(t,e,n){return{type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()}},Additive_sub(t,e,n){return{type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()}},Multiplicative_mul(t,e,n){return{type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()}},Multiplicative_div(t,e,n){return{type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST()}},Multiplicative_mod(t,e,n){return{type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,n,r,s,i){return{type:"methodCall",object:t.toAST(),method:n.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,n){return{type:"memberAccess",object:t.toAST(),property:n.sourceString}},PostfixExpr_bracketAccess(t,e,n,r){return{type:"bracketAccess",object:t.toAST(),index:n.toAST()}},PostfixExpr_sliceAccess(t,e,n,r,s,i){return{type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:s.toAST()}},Primary_paren(t,e,n){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,r){return{type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,n,r){const s=[e.toAST()];for(const i of r.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},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,r){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,n,r){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,n){return{type:"literal",value:ni(e.sourceString),raw:this.sourceString}},string_double(t,e,n){return{type:"literal",value:ni(e.sourceString),raw:this.sourceString}},bool_true(t){return{type:"literal",value:!0,raw:"true"}},bool_false(t){return{type:"literal",value:!1,raw:"false"}},null(t){return{type:"literal",value:null,raw:"null"}},ident(t,e){return{type:"identifier",name:this.sourceString}},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});function ni(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];if(r!=="\\"||n===t.length-1){e+=r;continue}switch(t[n+1]){case"\\":e+="\\",n++;break;case"'":e+="'",n++;break;case'"':e+='"',n++;break;case"n":e+=`
|
|
470
|
+
`,n++;break;case"r":e+="\r",n++;break;case"t":e+=" ",n++;break;case"/":e+="/",n++;break;default:e+=r}}return e}function ri(t){const e=[],n=t.split("/").filter(Boolean);for(const r of n)if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:r});return{raw:t,segments:e}}function Wc(t,e){const n=t.getRightmostFailurePosition?.()??0,r=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<n&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=n-i;let o=e.indexOf(`
|
|
471
|
+
`,n);o===-1&&(o=e.length);const c=e.slice(n,Math.min(o,n+40));return{line:s,column:a,offset:n,expected:r,actual:c,message:t.message??"Parse error"}}function Es(t){const e=Nn(t);return e.ok?e.ast:null}function Nn(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const n=Da.match(e);if(!n.succeeded())return{ok:!1,error:Wc(n,e)};const r=Fa(n).toAST(),s=t.length-t.trimStart().length;let i=0;for(let o=0;o<s;o++)t.charCodeAt(o)===10&&i++;return i>0&&Hc(r,i),{ok:!0,ast:r}}function Je(t,e){t!==void 0&&(t.line=t.line+e)}function xn(t,e){Je(t.loc,e);for(const n of t.lets)Je(n.loc,e),Je(n.value.loc,e);Je(t.body.loc,e)}function Hc(t,e){Je(t.loc,e);for(const a of t.imports)Je(a.loc,e);if(t.functions!==void 0)for(const a of t.functions)xn(a,e);if(Je(t.service.loc,e),t.service.functions!==void 0)for(const a of t.service.functions)xn(a,e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();Je(a.loc,e);for(const o of a.functions)xn(o,e);for(const o of a.allows)Je(o.loc,e),Je(o.condition.loc,e);for(const o of a.children)s.push(o);i=s.length}}function Gc(t,e){t.loc!==void 0&&(t.loc.file=e);for(const s of t.lets)s.loc!==void 0&&(s.loc.file=e),s.value.loc!==void 0&&(s.value.loc.file=e);t.body.loc!==void 0&&(t.body.loc.file=e)}function Kc(t,e){const n=`rules_version = '2';
|
|
472
|
+
service cloud.firestore {
|
|
473
|
+
match /databases/{db}/documents {
|
|
474
|
+
${t}
|
|
475
|
+
}
|
|
476
|
+
}`,r=Es(n);if(r===null)return null;const i=r.service.match.functions;for(const a of i)xn(a,-3),e!==void 0&&Gc(a,e);return i}const Ma={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function Zc(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Ma[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function Jc(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${Ve(t.object,10)}.${t.property}`;case"methodCall":return`${Ve(t.object,10)}.${t.method}(${t.args.map(e=>ye(e)).join(", ")})`;case"bracketAccess":return`${Ve(t.object,10)}[${ye(t.index)}]`;case"sliceAccess":return`${Ve(t.object,10)}[${ye(t.start)}:${ye(t.end)}]`;case"binaryOp":{const e=Ma[t.op]??0,n=Ve(t.left,e),r=Ve(t.right,e+1);return`${n} ${t.op} ${r}`}case"unaryOp":return`${t.op}${Ve(t.operand,9)}`;case"ternary":return`${Ve(t.condition,2)} ? ${ye(t.consequent)} : ${ye(t.alternate)}`;case"inExpr":return`${Ve(t.element,5)} in ${Ve(t.collection,5)}`;case"isExpr":return`${Ve(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>ye(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${ye(e.key)}: ${ye(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${ye(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>ye(e)).join(", ")})`}}function Ve(t,e){const n=Jc(t);return Zc(t)<e?`(${n})`:n}function ye(t){return Ve(t,0)}function Qc(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 Ln(t){return" ".repeat(t)}function Ht(t,e,n,r){if(t!==void 0){let i="firestore.rules";t.file!==void 0&&(i=t.file);const o={generatedLine:e,authoredLine:t.line,authoredCol:t.col,authoredFile:i};r!==void 0&&(o.expression=r),n.push(o)}}function Br(t,e,n,r){const s=Ln(e),i=Ln(e+2),a=t.parameters.join(", ");let o="";t.exported===!0&&(o="export ");const u=n.length+1;n.push(`${s}${o}function ${t.name}(${a}) {`),Ht(t.loc,u,r);for(const l of t.lets){const p=n.length+1;n.push(`${i}let ${l.name} = ${ye(l.value)};`),Ht(l.loc,p,r)}const f=n.length+1;n.push(`${i}return ${ye(t.body)};`),Ht(t.body.loc,f,r),n.push(`${s}}`)}function Yc(t,e,n,r){const s=Ln(e),i=t.operations.join(", "),a=ye(t.condition),o=n.length+1;n.push(`${s}allow ${i}: if ${a};`),Ht(t.loc,o,r,a)}function ja(t,e,n,r){const s=Ln(e),i=e+2,a=n.length+1;n.push(`${s}match ${Qc(t.path)} {`),Ht(t.loc,a,r);for(const o of t.functions)Br(o,i,n,r);for(const o of t.allows)Yc(o,i,n,r);for(const o of t.children)ja(o,i,n,r);n.push(`${s}}`)}function zr(t){const e=[],n=[];for(const o of t.imports)e.push(`import { ${o.functions.join(", ")} } from '${o.module}';`);if(e.push(`rules_version = '${t.version}';`),t.functions!==void 0)for(const o of t.functions)Br(o,0,e,n);const s=e.length+1;if(e.push(`service ${t.service.name} {`),Ht(t.service.loc,s,n),t.service.functions!==void 0)for(const o of t.service.functions)Br(o,2,e,n);const a=t.service.match;return ja(a,2,e,n),e.push("}"),e.push(""),{resolved:e.join(`
|
|
477
|
+
`),sourceMap:n}}function si(t){return zr(t).resolved}const kn=new Set(["get","exists","getAfter","debug"]),Xc=new Set(["get","exists","getAfter","existsAfter"]);function $a(t,e,n=new Set){let r=0;const s=i=>{switch(i.type){case"functionCall":if(Xc.has(i.name))r++;else{const a=e.get(i.name);if(a!==void 0&&!n.has(i.name)){n.add(i.name);for(const c of a.lets)s(c.value);s(a.body),n.delete(i.name)}}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"sliceAccess":s(i.object),s(i.start),s(i.end);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"pathLiteral":for(const a of i.segments)typeof a!="string"&&s(a);break}};return s(t),r}function Dn(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Dn(t.right,e)}function Vr(t){let e={op:"",depth:0};function n(s){if(s.type==="binaryOp"){const i=Dn(s,"&&"),a=Dn(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),n(s.left),n(s.right)}else r(s)}function r(s){switch(s.type){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"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(i=>{n(i.key),n(i.value)});break;case"functionCall":s.args.forEach(n);break}}return n(t),e}function ie(t){let e=1;switch(t.type){case"binaryOp":e+=ie(t.left)+ie(t.right);break;case"unaryOp":e+=ie(t.operand);break;case"methodCall":e+=ie(t.object);for(const n of t.args)e+=ie(n);break;case"memberAccess":e+=ie(t.object);break;case"bracketAccess":e+=ie(t.object)+ie(t.index);break;case"ternary":e+=ie(t.condition)+ie(t.consequent)+ie(t.alternate);break;case"inExpr":e+=ie(t.element)+ie(t.collection);break;case"isExpr":e+=ie(t.value);break;case"listLiteral":for(const n of t.elements)e+=ie(n);break;case"mapLiteral":for(const n of t.entries)e+=ie(n.key)+ie(n.value);break;case"functionCall":for(const n of t.args)e+=ie(n);break;case"pathLiteral":for(const n of t.segments)typeof n!="string"&&(e+=ie(n));break}return 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 Pa(t){return t.type==="binaryOp"&&t.op==="&&"?Pa(t.left):t}function qa(t){const e=new Map,n=new Set(t.map(s=>s.name));function r(s){const i=[],a=o=>{switch(o.type){case"functionCall":n.has(o.name)&&!kn.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...r(s.body));for(const a of s.lets)i.push(...r(a.value));e.set(s.name,[...new Set(i)])}return e}function xs(t,e,n=new Set){if(n.has(t))return 0;n.add(t);const r=e.get(t)||[];if(r.length===0)return 1;let s=0;for(const i of r)s=Math.max(s,xs(i,e,new Set(n)));return 1+s}function eu(t,e){const n=new Map,r=s=>{switch(s.type){case"functionCall":e.has(s.name)&&n.set(s.name,(n.get(s.name)??0)+1),s.args.forEach(r);break;case"binaryOp":r(s.left),r(s.right);break;case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break}};return r(t),n}function Ua(t,e,n=new Set){if(n.has(t))return!1;n.add(t);const r=e.get(t);if(!r)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?Ua(i.name,e,n):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(r.body)||r.lets.some(i=>s(i.value))}function Wr(t,e,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:r(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const i=e.get(s.name);if(Wr(i.body,e,n)||i.lets.some(a=>Wr(a.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(i=>r(i.key)||r(i.value));default:return!1}};return r(t)}function Ba(t){const e=[...t.functions];for(const n of t.children)e.push(...Ba(n));return e}function za(t){const e=[];for(const n of t.allows)e.push({rule:n,path:t.path.raw,matchFunctions:t.functions});for(const n of t.children){const r=za(n);for(const s of r)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...r)}return e}const Hr={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()`"},at={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`"},tu=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),nu=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{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:"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)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],ru=new Set(["email_verified"]),su=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),iu=[{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 au(t){const e=[],n=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const r of iu)r.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:r.message});return e}function Va(t,e,n){const r=t.path.raw,s=new Set(e);for(const i of t.functions)s.add(i.name);for(const i of t.functions){const a={matchPath:r,functionName:i.name};ue(i.body,a,s,n);for(const o of i.lets)ue(o.value,a,s,n)}for(let i=0;i<t.allows.length;i++)ue(t.allows[i].condition,{matchPath:r,ruleIndex:i},s,n);for(const i of t.children)Va(i,s,n)}function ue(t,e,n,r){switch(r(t,e,n),t.type){case"binaryOp":ue(t.left,e,n,r),ue(t.right,e,n,r);break;case"unaryOp":ue(t.operand,e,n,r);break;case"methodCall":ue(t.object,e,n,r),t.args.forEach(s=>ue(s,e,n,r));break;case"memberAccess":ue(t.object,e,n,r);break;case"bracketAccess":ue(t.object,e,n,r),ue(t.index,e,n,r);break;case"ternary":ue(t.condition,e,n,r),ue(t.consequent,e,n,r),ue(t.alternate,e,n,r);break;case"inExpr":ue(t.element,e,n,r),ue(t.collection,e,n,r);break;case"isExpr":ue(t.value,e,n,r);break;case"listLiteral":t.elements.forEach(s=>ue(s,e,n,r));break;case"mapLiteral":t.entries.forEach(s=>{ue(s.key,e,n,r),ue(s.value,e,n,r)});break;case"functionCall":t.args.forEach(s=>ue(s,e,n,r));break}}function ou(t,e,n){return n?!1:t.type==="functionCall"&&t.name==="debug"&&!e.has("debug")}function cu(t){return t.type==="methodCall"&&!!Hr[t.method]}function uu(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!tu.has(t.method)}function lu(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 du(t){return t.type!=="methodCall"||t.object.type!=="identifier"?!1:!!at[t.object.name]}function hu(t){return t.type==="functionCall"&&!!at[t.name]}function fu(t){return t.type==="identifier"&&!!at[t.name]}function pu(t){if(t.type!=="memberAccess"||t.object.type!=="identifier")return;const e=t.object.name,n=t.property;return nu.find(r=>r.receiver===e&&r.property===n)}function mu(t){if(t.type!=="memberAccess"||!ru.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 gu(t){if(!(t.type!=="binaryOp"||t.op!=="=="&&t.op!=="!="))for(const[e,n]of[[t.left,t.right],[t.right,t.left]]){const r=mu(e);if(r&&n.type==="literal"&&typeof n.value=="string")return{claim:r,op:t.op,literal:n.value}}}function yu(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function vu(t){return t.type!=="memberAccess"||!su.has(t.property)?!1: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 bu(t,e={}){const n=[],r=new Set;function s(a,o,c,u){const f=`${a}|${o}|${c.matchPath||""}|${c.functionName||""}|${c.ruleIndex??""}`;r.has(f)||(r.add(f),n.push(u))}const i=new Set;for(const a of t.functions??[])i.add(a.name);for(const a of t.service.functions??[])i.add(a.name);return Va(t.service.match,i,(a,o,c)=>{if(ou(a,c,e.allowDebug)&&s("HALLUCINATED_GLOBAL","debug",o,{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:o,fix:"Remove the debug() call and evaluate the inner expression directly."}),cu(a)&&a.type==="methodCall"&&s("HALLUCINATED_METHOD",a.method,o,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${a.method}()\` does not exist in Firestore rules. ${Hr[a.method]}`,location:o,fix:Hr[a.method]}),uu(a)&&a.type==="methodCall"&&s("HALLUCINATED_METHOD",`math.${a.method}`,o,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${a.method}()\` does not exist in production Firestore security rules.`,location:o,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),lu(a)&&a.type==="methodCall"&&s("HALLUCINATED_METHOD",`map.${a.method}`,o,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${a.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:o,fix:`Insert \`.keys()\`: e.g. \`data.keys().${a.method}(...)\`.`}),du(a)&&a.type==="methodCall"&&a.object.type==="identifier"){const l=a.object.name;s("HALLUCINATED_GLOBAL",`${l}.${a.method}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${l}.${a.method}()\` does not exist in Firestore rules. ${at[l]}`,location:o,fix:at[l]})}hu(a)&&a.type==="functionCall"&&s("HALLUCINATED_GLOBAL",a.name,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${a.name}()\` does not exist in Firestore rules. ${at[a.name]}`,location:o,fix:at[a.name]}),fu(a)&&a.type==="identifier"&&s("HALLUCINATED_GLOBAL",`ref:${a.name}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${a.name}\` is not a Firestore rules identifier. ${at[a.name]}`,location:o,fix:at[a.name]});const u=pu(a);if(u&&a.type==="memberAccess"&&a.object.type==="identifier"){const l=a.object.name,p=a.property;s("WRONG_CONTEXT_PATH",`${l}.${p}`,o,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${l}.${p}\` is not a valid Firestore rules path. ${u.suggestion}`,location:o,fix:u.suggestion})}const f=gu(a);if(f){const{claim:l,op:p,literal:y}=f;s("BOOL_TOKEN_CLAIM",`${l}|${p}|${y}`,o,{rule:"BOOL_TOKEN_CLAIM",severity:"error",message:`\`request.auth.token.${l}\` is a bool, but it is compared against the string "${y}", a cross-type comparison that is always ${p==="=="?"false (rule always denies)":"true (rule silently allows)"}. Compare against the boolean literal instead: \`request.auth.token.${l} ${p} true\`.`,location:o,fix:`Drop the quotes: \`request.auth.token.${l} ${p} ${y==="false"?"false":"true"}\`.`})}if(yu(a)&&s("LENGTH_PROPERTY","",o,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:o,fix:"Replace `.length` with `.size()`."}),a.type==="pathLiteral")for(const l of a.segments){if(typeof l!="string")continue;const p=l.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!p)continue;const y=p[1];s("INVALID_PATH_INTERPOLATION",`${a.raw}|${y}`,o,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${y}}\` 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 \`{${y}}\` with \`$(${y})\` in path \`${a.raw}\`.`,location:o,fix:`Replace \`{${y}}\` with \`$(${y})\` inside the path argument.`})}vu(a)&&a.type==="memberAccess"&&s("METHOD_MISSING_PARENS",a.property,o,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${a.property}\` looks like a built-in method called without parentheses. Use \`.${a.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:o,fix:`Add parentheses: \`.${a.property}()\`.`})}),n}const pe={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function wu(t,e){t.length>pe.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 Su(t,e){for(const n of t)n.lets.length>pe.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${pe.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function _u(t,e){for(const n of t){const r=Vr(n.body);for(const s of n.lets){const i=Vr(s.value);i.depth>r.depth&&(r.depth=i.depth,r.op=i.op)}r.depth>=pe.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):r.depth>=pe.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:n.name},fix:"Split the chain into nested groups to reduce depth."}):r.depth>=pe.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name}})}}function Au(t,e){const n=new Map;for(let r=0;r<t.length;r++){const s=t[r];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=se(Pa(s.rule.condition)),a=s.path;n.has(a)||n.set(a,[]),n.get(a).push({index:r,gate:i,ops:s.rule.operations})}for(const[r,s]of n){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${r}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:r},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function Iu(t,e){let n=ie(t);const r=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);n+=ie(a.body);for(const o of a.lets)n+=ie(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:n,callCount:r.size}}function Eu(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=Iu(t[s].rule.condition,r),o=Dn(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),f=a<=pe.RUNTIME_BUDGET.low.calls?pe.RUNTIME_BUDGET.low:a<=pe.RUNTIME_BUDGET.mid.calls?pe.RUNTIME_BUDGET.mid:pe.RUNTIME_BUDGET.high;u>=f.warn&&n.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function xu(t,e,n){const r=qa(e),s=new Map;for(const i of e)s.set(i.name,i);for(let i=0;i<t.length;i++){let a=0;const o=c=>{if(c.type==="functionCall"&&s.has(c.name)){const u=xs(c.name,r);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=pe.CALL_DEPTH_ERROR?n.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=pe.CALL_DEPTH_WARN&&n.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function ku(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const i=$a(t[s].rule.condition,r);i>pe.GET_COUNT_ERROR?n.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists()/getAfter()/existsAfter() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=pe.GET_COUNT_WARN&&n.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists()/getAfter()/existsAfter() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function Ou(t,e,n){const r=new Map;for(const i of e)r.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=eu(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&Ua(o,r)&&n.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function Cu(t,e,n,r){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)Wr(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),f=c.split("/").filter(Boolean);if(u.length!==f.length)return!1;for(let l=0;l<u.length;l++){const p=u[l];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==f[l])return!1}return!0}for(const o of n)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&r.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function cn(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=cn(t.left),n=cn(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=cn(t.operand);return e===null?null:!e}return null}const Ru=new Set(["write","create","update","delete"]);function Tu(t,e){for(let n=0;n<t.length;n++){const r=t[n];if(cn(r.rule.condition)!==!0||!r.rule.operations.some(a=>Ru.has(a)))continue;const i=r.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${r.path} resolves to a constant true predicate — this disables write security for 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:n,matchPath:r.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Wa(t,e){if(t.path.segments.some(r=>r.type==="recursive"))for(let r=0;r<t.allows.length;r++)cn(t.allows[r].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:r,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const r of t.children)Wa(r,e)}function Nu(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function Lu(t){return t.map(Nu).join("/")}function Gr(t,e){const n=Lu(t.path.segments),r=e?`${e}/${n}`:n,s=[{block:t,normalizedPath:r}];for(const i of t.children)s.push(...Gr(i,r));return s}function re(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${re(t.object)}.${t.property}`;case"methodCall":return`${re(t.object)}.${t.method}(${t.args.map(re).join(",")})`;case"bracketAccess":return`${re(t.object)}[${re(t.index)}]`;case"sliceAccess":return`${re(t.object)}[${re(t.start)}:${re(t.end)}]`;case"binaryOp":return`(${re(t.left)}${t.op}${re(t.right)})`;case"unaryOp":return`(${t.op}${re(t.operand)})`;case"ternary":return`(${re(t.condition)}?${re(t.consequent)}:${re(t.alternate)})`;case"inExpr":return`(${re(t.element)} in ${re(t.collection)})`;case"isExpr":return`(${re(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(re).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${re(e.key)}:${re(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(re).join(",")})`}}function Fn(t){return t.type==="binaryOp"&&t.op==="&&"?[...Fn(t.left),...Fn(t.right)]:[t]}function Du(t,e,n){const r=Gr(t,""),s=Gr(e,""),i=new Map;for(const{block:a,normalizedPath:o}of r)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const f=[...u.operations].sort().join(","),l=c.allows.find(b=>[...b.operations].sort().join(",")===f),p=u.operations.join(", ");if(!l){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${p}`,location:{matchPath:o}});continue}const y=Fn(u.condition).map(re),v=new Set(Fn(l.condition).map(re));for(const b of y)v.has(b)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${p}: ${b}`,location:{matchPath:o}})}}}function Kr(t,e={}){const n=[];n.push(...au(t)),wu(t,n);const r=Nn(t);if(!r.ok)return{warnings:n,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:r.error};const s=r.ast,i=Ba(s.service.match),a=za(s.service.match);if(_u(i,n),Su(i,n),Au(a,n),Eu(a,i,n),xu(a,i,n),ku(a,i,n),Ou(a,i,n),n.push(...bu(s,{allowDebug:e.allowDebug})),Tu(a,n),Wa(s.service.match,n),e.testCases&&e.testCases.length>0&&Cu(a,i,e.testCases,n),e.previousSource){const v=Nn(e.previousSource);v.ok&&Du(s.service.match,v.ast.service.match,n)}let o={depth:0,op:""},c={count:0,fn:""};for(const v of i){const b=Vr(v.body);b.depth>o.depth&&(o={depth:b.depth,op:b.op}),v.lets.length>c.count&&(c={count:v.lets.length,fn:v.name})}const u=qa(i);let f=0;for(const v of i){const b=xs(v.name,u);b>f&&(f=b)}const l=new Map;for(const v of i)l.set(v.name,v);let p=0,y=0;for(const v of a){const b=$a(v.rule.condition,l);b>y&&(y=b)}return{warnings:n,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:f,maxEstimatedExpressions:p,getCallCount:y}}}const Ha={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],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(Ha).sort());const Fu={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],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:[]},Ga=["exists","existsAfter","get","getAfter"],Mu=["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"],ju={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"]},Ka={cast:["float","int","path","string"],duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},$u=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.size","request.time","resource","resource.bucket","resource.contentType","resource.generation","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Pu=["get","hasAll","keys","matches","size","split"],qu={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},Za={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Uu=new Set($u),Bu=["request.auth.token","request.resource.metadata","resource.metadata"];function zu(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const n=e.join(".");return Uu.has(n)||Bu.some(r=>n.startsWith(`${r}.`))}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")}function Mn(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 Vu(t,e){if(!e||e==="unknown-ambient")return null;const n=e.join(".");return 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.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 ii(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";if(t.object.name==="cast"){if(t.method==="string")return"string";if(t.method==="path")return"path";if(t.method==="int"||t.method==="float")return"number"}}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","removeAll","split","values"].includes(t.method)?"list":["keys","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 Wu=new Set(Ga),Hu=Object.fromEntries(Object.entries(Ka).map(([t,e])=>[t,new Set(e)])),Gu=Object.fromEntries(Object.entries(Za).map(([t,e])=>[t,new Set(e)]));function rt(t,e){return t.some(n=>we(n,e)!==null)?"unknown-ambient":null}function Ja(t,e,n){const r=n.declarations?.get(t),s=new Map(r?.aliases),i=new Map(r?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:r?.functions??n.functions,service:n.service,stack:new Set([...n.stack,t.name]),declarations:n.declarations}}function Gt(t,e){return{expression:t,provenance:we(t,e),receiverType:le(t,e)}}function we(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=we(t.object,e);return n==="unknown-ambient"?n:n?[...n,t.property]:null}if(t.type==="bracketAccess"){const n=we(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=we(t.consequent,e),r=we(t.alternate,e);return!n&&!r?null:Array.isArray(n)&&Array.isArray(r)&&n.join(".")===r.join(".")?n:"unknown-ambient"}if(t.type==="functionCall"){const n=e.functions.get(t.name),r=t.args.map(i=>Gt(i,e));if(!n&&Wu.has(t.name))return null;if(!n||e.stack.has(n.name))return r.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=Ja(n,r,e);for(const i of n.lets){const a=Gt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return we(n.body,s)}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 rt([t.object,...t.args],e);case"sliceAccess":return rt([t.object,t.start,t.end],e);case"binaryOp":return rt([t.left,t.right],e);case"unaryOp":return rt([t.operand],e);case"inExpr":return rt([t.element,t.collection],e);case"isExpr":return rt([t.value],e);case"listLiteral":return rt(t.elements,e);case"mapLiteral":return rt(t.entries.flatMap(({key:n,value:r})=>[n,r]),e);case"pathLiteral":return rt(t.segments.filter(n=>typeof n!="string"),e);default:return null}}function le(t,e){const n=Vu(e.service,we(t,e));if(n)return n;switch(t.type){case"identifier":{const r=e.receiverTypes.get(t.name);return r||((e.service==="cloud.firestore"?Hu:Gu)[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":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const r=le(t.object,e);if(r==="mixed")return"mixed";if(t.property==="data"&&r==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?le(s.value,e):null}return null}case"bracketAccess":{const r=le(t.object,e);if(r==="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?le(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?le(a.value,e):null}if(r==="string")return"string";const s=we(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const r=le(t.object,e);return r==="mixed"?"mixed":r==="list"||r==="string"?r:null}case"methodCall":{const r=ii(t);if(t.object.type==="identifier"&&r)return r;if(t.method==="get"){const s=we(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?le(o.value,e):i?le(i,e):null}return i&&le(i,e)?"mixed":null}return ii(t)}case"binaryOp":{const r=le(t.left,e),s=le(t.right,e);return t.op==="+"&&(r==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&r==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&le(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const r=le(t.consequent,e),s=le(t.alternate,e);return!r&&!s?null:r===s?r:"mixed"}case"functionCall":{const r=e.functions.get(t.name);if(!r&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!r||e.stack.has(r.name))return null;const s=Ja(r,t.args.map(i=>Gt(i,e)),e);for(const i of r.lets){const a=Gt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return le(r.body,s)}default:return null}}function Ku(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Zu(t,e,n){const r=Ku(e),s=Ha[r];return s?s.includes(t)?null:`Function '${n}' from module '${e}' is not compatible with service '${t}'`:null}function Ju(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Qu=new Set(Ga),Yu=new Set(Mu),Xu=Object.fromEntries(Object.entries(Ka).map(([t,e])=>[t,new Set(e)])),el=new Set(Pu),tl=Object.fromEntries(Object.entries(Za).map(([t,e])=>[t,new Set(e)]));function jn(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!zu(e,t)?`binding '${t.join(".")}'`:null}function nl(t,e,n,r,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=we(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=n[0];if(a?.type==="literal"&&typeof a.value=="string")return jn([...i,a.value],r);if(!Mn(r,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!Mn(r,i)?`binding '${i.join(".")}.${e}()'`:null}function rl(t,e,n,r){const s=we(t,r),i=le(t,r);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=le(c,r);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(n==="cloud.firestore"?ju:qu)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function sl(t,e,n,r){const s=we(e,r);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?jn([...s,t.value],n):Mn(n,s)?null:`binding '<value> in ${s.join(".")}'`:null}function ai(t,e,n){const r=s=>{switch(s.type){case"memberAccess":{const i=jn(we(s,n),e);return i||r(s.object)}case"functionCall":{const i=n.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!Qu.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=r(a);if(o)return o}if(i&&!n.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,f)=>{const l=s.args[f];a.set(u,l?we(l,n):null),o.set(u,l?le(l,n):null)});const c=Qa(i,e,{aliases:a,receiverTypes:o,functions:n.functions,service:e,stack:new Set([...n.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!n.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?Xu:tl)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const f of s.args){const l=r(f);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Yu:el).has(s.method))return`method '.${s.method}()'`;const a=rl(s.object,s.method,e,n);if(a)return a;const o=nl(s.object,s.method,s.args,e,n);return o||(r(s.object)??s.args.map(r).find(Boolean)??null)}case"binaryOp":return r(s.left)??r(s.right);case"unaryOp":return r(s.operand);case"bracketAccess":{const i=we(s.object,n);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return Mn(e,i)?r(s.object)??r(s.index):`binding '${i.join(".")}[...]'`;const o=jn(we(s,n),e);return o||(r(s.object)??r(s.index))}case"sliceAccess":return r(s.object)??r(s.start)??r(s.end);case"ternary":return r(s.condition)??r(s.consequent)??r(s.alternate);case"inExpr":return sl(s.element,s.collection,e,n)??r(s.element)??r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.map(r).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=r(i.key)??r(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=r(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||n.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Ju(s)}};return r(t)}function Qa(t,e,n){const r=new Map(n.aliases),s=new Map(n.receiverTypes),i={...n,aliases:r,receiverTypes:s};for(const a of t.lets){const o=ai(a.value,e,i);if(o)return o;r.set(a.name,we(a.value,i)),s.set(a.name,le(a.value,i))}return ai(t.body,e,i)}function il(t,e,n=new Map([[t.name,t]]),r=[]){const s={aliases:new Map,receiverTypes:new Map,functions:n,service:e,stack:new Set([t.name])};return Qa(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<r.length?r[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,r[a]?le(r[a].expression,s)??r[a].receiverType??null:null])),functions:n,service:e,stack:new Set([t.name])})}function al(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function ol(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function ne(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,r=t.args.map(s=>ne(s,e));return n===t.name&&r.every((s,i)=>s===t.args[i])?t:{...t,name:n,args:r}}case"binaryOp":{const n=ne(t.left,e),r=ne(t.right,e);return n===t.left&&r===t.right?t:{...t,left:n,right:r}}case"unaryOp":{const n=ne(t.operand,e);return n===t.operand?t:{...t,operand:n}}case"methodCall":{const n=ne(t.object,e),r=t.args.map(s=>ne(s,e));return n===t.object&&r.every((s,i)=>s===t.args[i])?t:{...t,object:n,args:r}}case"memberAccess":{const n=ne(t.object,e);return n===t.object?t:{...t,object:n}}case"bracketAccess":{const n=ne(t.object,e),r=ne(t.index,e);return n===t.object&&r===t.index?t:{...t,object:n,index:r}}case"sliceAccess":{const n=ne(t.object,e),r=ne(t.start,e),s=ne(t.end,e);return n===t.object&&r===t.start&&s===t.end?t:{...t,object:n,start:r,end:s}}case"ternary":{const n=ne(t.condition,e),r=ne(t.consequent,e),s=ne(t.alternate,e);return n===t.condition&&r===t.consequent&&s===t.alternate?t:{...t,condition:n,consequent:r,alternate:s}}case"inExpr":{const n=ne(t.element,e),r=ne(t.collection,e);return n===t.element&&r===t.collection?t:{...t,element:n,collection:r}}case"isExpr":{const n=ne(t.value,e);return n===t.value?t:{...t,value:n}}case"listLiteral":{const n=t.elements.map(r=>ne(r,e));return n.every((r,s)=>r===t.elements[s])?t:{...t,elements:n}}case"mapLiteral":{const n=t.entries.map(r=>{const s=ne(r.key,e),i=ne(r.value,e);return s===r.key&&i===r.value?r:{key:s,value:i}});return n.every((r,s)=>r===t.entries[s])?t:{...t,entries:n}}case"pathLiteral":{const n=t.segments.map(r=>typeof r=="string"?r:ne(r,e));return n.every((r,s)=>r===t.segments[s])?t:{...t,segments:n}}case"literal":case"identifier":return t;default:return al(t)}}function cl(t,e){const n=ol(e),r=new Map;for(const s of t)s.exported||r.set(s.name,`${n}__${s.name}`);return r.size===0?t:t.map(s=>{const i=ne(s.body,r),a=s.lets.map(c=>{const u=ne(c.value,r);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:r.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function ul(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function ks(t){const e=[],n=r=>{switch(r.type){case"functionCall":e.push(r),r.args.forEach(n);break;case"binaryOp":n(r.left),n(r.right);break;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"sliceAccess":n(r.object),n(r.start),n(r.end);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(({key:s,value:i})=>{n(s),n(i)});break;case"pathLiteral":r.segments.forEach(s=>{typeof s!="string"&&n(s)});break;case"literal":case"identifier":break;default:ul(r)}};return n(t),e}function ll(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function dl(t,e){const n=[],r=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,p=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:p,declarations:r}),a=(l,p,y)=>{if(y.has(l.name))return;const v=r.get(l);if(!v)return;const b=new Map(v.aliases),C=new Map(v.receiverTypes);l.parameters.forEach((R,_)=>{b.set(R,p[_]?.provenance??null),C.set(R,p[_]?.receiverType??null)});const T=i({aliases:b,receiverTypes:C,functions:v.functions},new Set([...y,l.name]));for(const R of l.lets){o(R.value,T);const _=Gt(R.value,T);T.aliases.set(R.name,_.provenance),T.receiverTypes.set(R.name,_.receiverType)}o(l.body,T)},o=(l,p)=>{for(const y of ks(l)){const v=y.args.map(C=>Gt(C,p));y.name===e&&n.push({arguments:v.map(ll)});const b=p.functions.get(y.name);b&&a(b,v,p.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])r.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])r.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const f=(l,p)=>{const y=new Map(p.receiverTypes);for(const T of l.path.segments)T.type==="wildcard"&&y.set(T.name,"string"),T.type==="recursive"&&y.set(T.name,"path");const v=new Map(p.functions),b={aliases:p.aliases,receiverTypes:y,functions:v};for(const T of l.functions)v.set(T.name,T),r.set(T,b);const C=i(b);for(const{condition:T}of l.allows)o(T,C);l.children.forEach(T=>f(T,b))};return f(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),n}function At(t){return ks(t).map(({name:e})=>e)}function hl(t,e){return[...t.values()].flatMap(r=>[...r.lets.map(({value:s})=>s),r.body]).flatMap(ks).filter(({name:r})=>r===e).map(({args:r})=>r)}function fl(t,e,n){const r=Kc(t,e);return r===null?{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}:{success:!0,functions:r,bundled:n}}function oi(t){return t.startsWith("./")||t.startsWith("../")}function Zr(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function pl(t,e,n,r=new Set){if(n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e))return fl(n.modules[e],e,r.has(e));if(oi(e)&&n?.basePath){const i=`${n.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Zr(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Zr(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:oi(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 dp(t,e,n,r=new Set){const s=Nn(e);if(!s.ok){const{line:F,column:z,message:ee}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${F}, col ${z}: ${ee}`}}}const i=s.ast,a=i.version==="2+modules",o=i.service.name==="firebase.storage";let c=o?"storage.rules":"firestore.rules";if(a&&(c=o?"storage.modules.rules":"firestore.modules.rules"),n!==void 0&&n.sourceFile!==void 0&&n.sourceFile!==""&&(c=n.sourceFile),ml(i,c),a===!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}'`}};if(i.imports.length===0){i.version="2";const F=zr(i),z=JSON.stringify(F.sourceMap);return{success:!0,data:{resolved:`${F.resolved}// @pyric-source-map: ${z}
|
|
478
|
+
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:F.sourceMap}}}const p=i.imports.find(F=>F.functions.length===0);if(p)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${p.module}' must request at least one function`}};const y=new Map,v=new Map,b=new Map,C=new Map,T=[],R=[],_=new Map;for(const F of i.imports){const z=pl(t,F.module,n,r);if(!z.success)return{success:!1,error:z.error};T.includes(F.module)||T.push(F.module),z.bundled&&!R.includes(F.module)&&R.push(F.module);const ee=new Set,Oe=z.functions.find(Z=>ee.has(Z.name)?!0:(ee.add(Z.name),!1));if(Oe)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${F.module}' defines duplicate function '${Oe.name}'`}};const Q=z.functions.find(Z=>kn.has(Z.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${F.module}' conflicts with a Rules builtin`}};const ze=new Set;for(const Z of z.functions)Z.exported||ze.add(Z.name);_.set(F.module,ze);const vr=cl(z.functions,F.module),$s=new Set;for(const Z of vr){if($s.has(Z.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${F.module}' defines conflicting function name '${Z.name}'`}};$s.add(Z.name)}const Uo=new Set(vr.filter(Z=>Z.exported).map(Z=>Z.name));for(const Z of vr){const _t=C.get(Z.name);if(_t&&_t!==F.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' from module '${F.module}' conflicts with module '${_t}'`}};if(C.set(Z.name,F.module),v.set(Z.name,Z),Z.exported){if(y.has(Z.name)&&b.get(Z.name)!==F.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' exported by both '${b.get(Z.name)}' and '${F.module}'`}};y.set(Z.name,Z),b.set(Z.name,F.module)}}for(const Z of F.functions){if(!Uo.has(Z))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:_.get(F.module)?.has(Z)?`Function '${Z}' in module '${F.module}' is not exported`:`Function '${Z}' not found in module '${F.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const _t=z.bundled?Zu(i.service.name,F.module,Z):null;if(_t)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:_t}}}}}const D=new Set(i.imports.flatMap(F=>F.functions)),q=[],S=new Set,x=[],A={cycle:null};function w(F){if(A.cycle)return;const z=x.indexOf(F);if(z>=0){A.cycle=[...x.slice(z),F];return}if(S.has(F))return;const ee=v.get(F);if(!ee)return;x.push(F);const Oe=At(ee.body);for(const Q of ee.lets)Oe.push(...At(Q.value));for(const Q of Oe)v.has(Q)&&!kn.has(Q)&&w(Q);x.pop(),!A.cycle&&(S.add(F),q.push({...ee,exported:!1}))}for(const F of i.imports)for(const z of F.functions)w(z);if(A.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${A.cycle.join(" -> ")}`}};for(const F of q){const z=C.get(F.name),Oe=[...F.lets.flatMap(({value:Q})=>At(Q)),...At(F.body)].find(Q=>{const ze=C.get(Q);return ze&&ze!==z&&!D.has(Q)});if(Oe)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${F.name}' in module '${z}' cannot call '${Oe}' from another module`}}}const I=new Set(q.map(F=>F.name)),E=new Map((i.functions??[]).map(F=>[F.name,F])),h=new Set((i.service.functions??[]).map(F=>F.name)),d=(F,z)=>F.flatMap(At).find(ee=>y.has(ee)&&!I.has(ee)&&!z.has(ee))??null,g=F=>F.flatMap(z=>[...z.lets.map(({value:ee})=>ee),z.body]),m=new Set(E.keys());let M=d(g(i.functions??[]),m);const k=new Set([...m,...h]);M??=d(g(i.service.functions??[]),k);const O=(F,z)=>{const ee=new Set([...z,...F.functions.map(Q=>Q.name)]),Oe=[...g(F.functions),...F.allows.map(({condition:Q})=>Q)];return d(Oe,ee)??F.children.map(Q=>O(Q,ee)).find(Boolean)??null};if(M??=O(i.service.match,k),M)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${M}' from module '${b.get(M)}' without importing it`}};const N=(F,z)=>{if(z.has(F.name))return!1;const ee=new Set([...z,F.name]);return[...F.lets.flatMap(({value:Q})=>At(Q)),...At(F.body)].some(Q=>{const ze=E.get(Q);return ze?N(ze,ee):I.has(Q)||h.has(Q)})},X=[...E.values()].find(F=>N(F,new Set));if(X)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${X.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const F=new Map(q.map(z=>[z.name,z]));for(const z of q){const ee=[...dl(i,z.name),...hl(F,z.name).map(Q=>({arguments:Q.map(ze=>({expression:ze,provenance:null,receiverType:"unknown"}))}))],Oe=ee.length>0?ee:[{arguments:[]}];for(const{arguments:Q}of Oe){const ze=il(z,i.service.name,v,Q);if(ze)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${z.name}' requires unsupported ${ze} for service '${i.service.name}'`}}}}}const Ae=new Set([...(i.functions??[]).map(F=>F.name),...(i.service.functions??[]).map(F=>F.name)]),Be=F=>{F.functions.forEach(z=>Ae.add(z.name)),F.children.forEach(Be)};Be(i.service.match);const ft=[...Ae].find(F=>kn.has(F));if(ft)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${ft}' conflicts with a Rules builtin`}};for(const F of q)if(Ae.has(F.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${F.name}' conflicts with a function defined in the source`}};i.service.functions=[...q,...i.service.functions??[]],i.version="2",i.imports=[];const qt=new Set,Ut=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const F of R){const z=Zr(F)??F,ee=Fu[z]??[];for(const Oe of ee)Oe.startsWith(Ut)&&qt.add(Oe)}const yr=zr(i),qo=JSON.stringify(yr.sourceMap);return{success:!0,data:{resolved:`${yr.resolved}// @pyric-source-map: ${qo}
|
|
479
|
+
`,modules:T,bundledModules:R,evidenceIds:[...qt].sort(),sourceMap:yr.sourceMap}}}function ml(t,e){if(t.functions!==void 0)for(const a of t.functions)a.loc!==void 0&&(a.loc.file=e);if(t.service.functions!==void 0)for(const a of t.service.functions)a.loc!==void 0&&(a.loc.file=e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();a.loc!==void 0&&(a.loc.file=e);for(const c of a.allows)c.loc!==void 0&&(c.loc.file=e);for(const c of a.functions)c.loc!==void 0&&(c.loc.file=e);for(const c of a.children)s.push(c);i=s.length}}function Ya(t,e,n,r,s){if(e===void 0)return;let a=e,o=1;n!==void 0&&(o=n);let u="firestore.rules";r!==void 0&&r!==""&&(u=r);let l;s!==void 0&&(l=s);const y="// @pyric-source-map: ",v=t.indexOf(y);if(v!==-1){const _=v+y.length,D=t.indexOf(`
|
|
480
|
+
`,_);let q="";D!==-1?q=t.slice(_,D).trim():q=t.slice(_).trim();try{const x=JSON.parse(q);if(Array.isArray(x)){for(const w of x)if(w.generatedLine===a){a=w.authoredLine,o=w.authoredCol,u=w.authoredFile,w.expression!==void 0&&(l=w.expression);break}}}catch{}}const C=`${u}:${a}:${o}`,T={line:a,col:o,file:u,citation:C};return l!==void 0&&(T.expression=l),T}const oe=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,n){return oe}binaryOp(e,n){return oe}}function me(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof de||e instanceof de)return t instanceof de&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>me(s,e[i]));if(!ci(t)||!ci(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&me(t[s],e[s]))}function ci(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class de{items;constructor(e){this.items=[];for(const n of e)this.items.some(r=>me(r,n))||this.items.push(n)}hasOnly(e){const n=e instanceof de?e.toArray():e;return this.items.every(r=>n.some(s=>me(r,s)))}equals(e){return!(e instanceof de)||e.items.length!==this.items.length?!1:this.items.every(n=>e.items.some(r=>me(n,r)))}hasAll(e){const n=e instanceof de?e.toArray():e;for(const r of n)if(!this.items.some(s=>me(s,r)))return!1;return!0}hasAny(e){const n=e instanceof de?e.toArray():e;for(const r of n)if(this.items.some(s=>me(s,r)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const n=e.toArray(),r=[];for(const s of this.items)n.some(i=>me(s,i))||r.push(s);return new de(r)}union(e){const n=e.toArray();return new de([...this.items,...n])}intersection(e){const n=e.toArray(),r=[];for(const s of this.items)n.some(i=>me(s,i))&&r.push(s);return new de(r)}}class un{before;after;constructor(e,n){this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before||e.push(n);return new de(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after||e.push(n);return new de(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before&&!me(this.before[n],this.after[n])&&e.push(n);return new de(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const r of n)(!(r in this.before)||!(r in this.after)||!me(this.before[r],this.after[r]))&&e.push(r);return new de(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after&&me(this.before[n],this.after[n])&&e.push(n);return new de(e)}}const gl=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Xe extends te{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 Xe([]):new Xe(n.split("/"))}bind(e){const n=[],r={...this.bindings};for(const s of this.segments){const i=s.match(gl);if(!i){n.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);n.push(c),r[a]=c}else n.push(s)}return new Xe(n,r)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Xe)||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}field(e){if(/^\d+$/.test(e)){const n=Number(e);return n<0||n>=this.segments.length?null:this.segments[n]}return e in this.bindings?this.bindings[e]:null}callMethod(e,n){switch(e){case"bind":{const r=n[0];if(r==null||typeof r!="object"||Array.isArray(r)||r instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${r===null?"null":typeof r}`);return this.bind(r)}default:return oe}}}class ae extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof ae?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,n){const r=n instanceof ae?n.value:typeof n=="number"?n:void 0;if(r===void 0)return oe;const s=this.value;switch(e){case"+":return new ae(s+r);case"-":return new ae(s-r);case"*":return new ae(s*r);case"/":return new ae(s/r);case"%":return new ae(s%r);case"<":return s<r;case"<=":return s<=r;case">":return s>r;case">=":return s>=r;default:return oe}}}class V extends Error{expr;constructor(e,n){super(e),this.expr=n,this.name="EvalError"}}class $n extends V{constructor(e,n){super(e,n),this.name="ResourceLimitError"}}class yt extends V{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class yl{entries=[];parents=[];frames=[];capture(e,n){const r=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:ye(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(r);try{const a=n();return this.entries[r].value=a,a}catch(a){throw this.entries[r].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,r={source:ye(e),kind:e.type,parent:n,skipped:!0};this.stampFrame(r),this.entries.push(r)}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 vl(t,e,n,r){const i=p=>p*Math.PI/180,a=i(t),o=i(n),c=i(n-t),u=i(r-e),f=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))}class lt extends te{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 lt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,n){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const r=n[0];if(!(r instanceof lt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof r}`);return vl(this.lat,this.lng,r.lat,r.lng)}default:return oe}}}const zt=1e9,ui={w:10080*60,d:1440*60,h:3600,m:60,s:1};function bl(t,e){let n=t+Math.trunc(e/zt),r=e%zt;return n>0&&r<0?(n-=1,r+=zt):n<0&&r>0&&(n+=1,r-=zt),{seconds:n,nanos:r}}class ve extends te{typeName="duration";seconds;nanos;constructor(e,n){super();const r=bl(e,n);this.seconds=r.seconds,this.nanos=r.nanos}static fromValue(e,n){if(n in ui)return new ve(e*ui[n],0);if(n==="ms"){const r=Math.trunc(e/1e3),s=e-r*1e3;return new ve(r,s*1e6)}if(n==="ns"){const r=Math.trunc(e/zt),s=e-r*zt;return new ve(r,s)}throw new Error(`Unknown duration unit '${n}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,n,r,s){return new ve(e*3600+n*60+r,s)}static abs(e){return new ve(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),r=Math.abs(this.nanos);return`${e?"-":""}${n}.${r.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ve&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return oe}}binaryOp(e,n){if(!(n instanceof ve))return oe;switch(e){case"+":return new ve(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new ve(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 oe}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const li=1e9,wl=864e5,Ar=86400;function Sl(t,e){const n=Math.floor(e/li);return{seconds:t+n,nanos:e-n*li}}let _e=class st extends te{typeName="timestamp";seconds;nanos;constructor(e,n){super();const r=Sl(e,n);this.seconds=r.seconds,this.nanos=r.nanos}static fromMillis(e){const n=Math.floor(e/1e3),r=e-n*1e3;return new st(n,r*1e6)}static fromYMD(e,n,r){return st.fromMillis(Date.UTC(e,n-1,r))}static fromIsoString(e){return st.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 st&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const r=this.asDate().getUTCDay();return r===0?7:r}case"dayOfYear":{const r=this.asDate(),s=Date.UTC(r.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/wl)+1}case"date":return st.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const r=(this.seconds%Ar+Ar)%Ar,s=Math.floor(r/3600),i=Math.floor(r%3600/60),a=r%60;return ve.fromTime(s,i,a,this.nanos)}default:return oe}}asDate(){return new Date(this.toMillis())}binaryOp(e,n){if(n instanceof st)switch(e){case"-":return new ve(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 oe}if(n instanceof ve)switch(e){case"+":return new st(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new st(this.seconds-n.seconds,this.nanos-n.nanos);default:return oe}return oe}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const di="0123456789ABCDEF";function _l(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=di[r>>>4]+di[r&15]}return e}function Al(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function Il(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}class Ie extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Ie(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 r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return new Ie(n)}size(){return this.data.length}toBase64(){return Al(this.data)}toHexString(){return _l(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Ie)||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":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return oe}binaryOp(e,n){if(!(n instanceof Ie))return oe;const r=Il(this.data,n.data);switch(e){case"<":return r<0;case"<=":return r<=0;case">":return r>0;case">=":return r>=0}return oe}}function hn(t){const e=typeof t=="string"?t.split("/").filter(Boolean):t;return e.length>0&&e.length%2===0}function fn(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 r=e.split("/").filter(i=>i.length>0&&i!=="."),s=[];for(const i of r)i===".."?s.length>1&&s.pop():s.push(i);return s.join("/")}function Jr(t,e){const n=t.split("/").filter(Boolean);return{data:e,id:n.at(-1)??"",__name__:new Xe(["databases","(default)","documents",...n])}}function hi(t,e){const n=fn(t),r=n.split("/").filter(Boolean);if(!hn(r))throw new V(`get() requires a path pointing to a document (even segment count), got '${n}'`);let s=e.mockDocuments.get(n);if(!s&&e.getDoc){const i=e.getDoc(n);i&&(e.mockDocuments.set(n,i),s=i)}if(s)return e.identitylessFunctionMocks?.has(n)?{data:s}:Jr(n,s);throw new V(`get() of non-existent document '${n}' (guard with exists() first)`)}function fi(t,e){const n=fn(t),r=n.split("/").filter(Boolean);if(!hn(r))return!1;if(e.mockDocuments.has(n))return!0;if(e.getDoc){const s=e.getDoc(n);if(s)return e.mockDocuments.set(n,s),!0}return!1}const pi=10;class El extends $n{constructor(e){super(e),this.name="LookupBudgetError"}}class xl{accessed=new Set;charge(e,n){const r=`${e}:${n}`;if(!this.accessed.has(r)){if(this.accessed.size>=pi)throw new El(`document access limit exceeded: this request already read ${pi} distinct documents via get()/exists()/getAfter()/existsAfter() (production allows 10 per request; the 11th distinct access fails the evaluation)`);this.accessed.add(r)}}}function An(t,e,n){if(!t.lookupBudget)return;const r=fn(n);hn(r)&&t.lookupBudget.charge(e,r)}var Ir={exports:{}};const kl={},Ol=Object.freeze(Object.defineProperty({__proto__:null,default:kl},Symbol.toStringTag,{value:"Module"})),Pn=Bo(Ol);/**
|
|
481
|
+
* [js-md5]{@link https://github.com/emn178/js-md5}
|
|
482
|
+
*
|
|
483
|
+
* @namespace md5
|
|
484
|
+
* @version 0.8.3
|
|
485
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
486
|
+
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
487
|
+
* @license MIT
|
|
488
|
+
*/var mi;function Cl(){return mi||(mi=1,(function(t){(function(){var e="input is invalid type",n="finalize already called",r=typeof window=="object",s=r?window:{};s.JS_MD5_NO_WINDOW&&(r=!1);var i=!r&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=da:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),f=[128,32768,8388608,-2147483648],l=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),v=[],b;if(c){var C=new ArrayBuffer(68);b=new Uint8Array(C),v=new Uint32Array(C)}var T=Array.isArray;(s.JS_MD5_NO_NODE_JS||!T)&&(T=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var R=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!R)&&(R=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var _=function(h){var d=typeof h;if(d==="string")return[h,!0];if(d!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!T(h)&&!R(h))throw new Error(e);return[h,!1]},D=function(h){return function(d){return new w(!0).update(d)[h]()}},q=function(){var h=D("hex");a&&(h=S(h)),h.create=function(){return new w},h.update=function(m){return h.create().update(m)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=D(g)}return h},S=function(h){var d=Pn,g=Pn.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(k){return new g(k)};var M=function(k){if(typeof k=="string")return d.createHash("md5").update(k,"utf8").digest("hex");if(k==null)throw new Error(e);return k.constructor===ArrayBuffer&&(k=new Uint8Array(k)),T(k)||R(k)||k.constructor===g?d.createHash("md5").update(m(k)).digest("hex"):h(k)};return M},x=function(h){return function(d,g){return new I(d,!0).update(g)[h]()}},A=function(){var h=x("hex");h.create=function(m){return new I(m)},h.update=function(m,M){return h.create(m).update(M)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=x(g)}return h};function w(h){if(h)v[0]=v[16]=v[1]=v[2]=v[3]=v[4]=v[5]=v[6]=v[7]=v[8]=v[9]=v[10]=v[11]=v[12]=v[13]=v[14]=v[15]=0,this.blocks=v,this.buffer8=b;else if(c){var d=new ArrayBuffer(68);this.buffer8=new Uint8Array(d),this.blocks=new Uint32Array(d)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}w.prototype.update=function(h){if(this.finalized)throw new Error(n);var d=_(h);h=d[0];for(var g=d[1],m,M=0,k,O=h.length,N=this.blocks,X=this.buffer8;M<O;){if(this.hashed&&(this.hashed=!1,N[0]=N[16],N[16]=N[1]=N[2]=N[3]=N[4]=N[5]=N[6]=N[7]=N[8]=N[9]=N[10]=N[11]=N[12]=N[13]=N[14]=N[15]=0),g)if(c)for(k=this.start;M<O&&k<64;++M)m=h.charCodeAt(M),m<128?X[k++]=m:m<2048?(X[k++]=192|m>>>6,X[k++]=128|m&63):m<55296||m>=57344?(X[k++]=224|m>>>12,X[k++]=128|m>>>6&63,X[k++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++M)&1023),X[k++]=240|m>>>18,X[k++]=128|m>>>12&63,X[k++]=128|m>>>6&63,X[k++]=128|m&63);else for(k=this.start;M<O&&k<64;++M)m=h.charCodeAt(M),m<128?N[k>>>2]|=m<<l[k++&3]:m<2048?(N[k>>>2]|=(192|m>>>6)<<l[k++&3],N[k>>>2]|=(128|m&63)<<l[k++&3]):m<55296||m>=57344?(N[k>>>2]|=(224|m>>>12)<<l[k++&3],N[k>>>2]|=(128|m>>>6&63)<<l[k++&3],N[k>>>2]|=(128|m&63)<<l[k++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++M)&1023),N[k>>>2]|=(240|m>>>18)<<l[k++&3],N[k>>>2]|=(128|m>>>12&63)<<l[k++&3],N[k>>>2]|=(128|m>>>6&63)<<l[k++&3],N[k>>>2]|=(128|m&63)<<l[k++&3]);else if(c)for(k=this.start;M<O&&k<64;++M)X[k++]=h[M];else for(k=this.start;M<O&&k<64;++M)N[k>>>2]|=h[M]<<l[k++&3];this.lastByteIndex=k,this.bytes+=k-this.start,k>=64?(this.start=k-64,this.hash(),this.hashed=!0):this.start=k}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},w.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,d=this.lastByteIndex;h[d>>>2]|=f[d&3],d>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},w.prototype.hash=function(){var h,d,g,m,M,k,O=this.blocks;this.first?(h=O[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+O[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+O[2]-1126478375,g=(g<<17|g>>>15)+m<<0,d=(h^g&(m^h))+O[3]-1316259209,d=(d<<22|d>>>10)+g<<0):(h=this.h0,d=this.h1,g=this.h2,m=this.h3,h+=(m^d&(g^m))+O[0]-680876936,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[2]+606105819,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[3]-1044525330,d=(d<<22|d>>>10)+g<<0),h+=(m^d&(g^m))+O[4]-176418897,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[6]-1473231341,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[7]-45705983,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[8]+1770035416,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[10]-42063,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[11]-1990404162,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[12]+1804603682,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[14]-1502002290,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[15]+1236535329,d=(d<<22|d>>>10)+g<<0,h+=(g^m&(d^g))+O[1]-165796510,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[11]+643717713,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[0]-373897302,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[5]-701558691,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[15]-660478335,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[4]-405537848,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[9]+568446438,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[3]-187363961,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[8]+1163531501,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[13]-1444681467,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[7]+1735328473,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[12]-1926607734,d=(d<<20|d>>>12)+g<<0,M=d^g,h+=(M^m)+O[5]-378558,h=(h<<4|h>>>28)+d<<0,m+=(M^h)+O[8]-2022574463,m=(m<<11|m>>>21)+h<<0,k=m^h,g+=(k^d)+O[11]+1839030562,g=(g<<16|g>>>16)+m<<0,d+=(k^g)+O[14]-35309556,d=(d<<23|d>>>9)+g<<0,M=d^g,h+=(M^m)+O[1]-1530992060,h=(h<<4|h>>>28)+d<<0,m+=(M^h)+O[4]+1272893353,m=(m<<11|m>>>21)+h<<0,k=m^h,g+=(k^d)+O[7]-155497632,g=(g<<16|g>>>16)+m<<0,d+=(k^g)+O[10]-1094730640,d=(d<<23|d>>>9)+g<<0,M=d^g,h+=(M^m)+O[13]+681279174,h=(h<<4|h>>>28)+d<<0,m+=(M^h)+O[0]-358537222,m=(m<<11|m>>>21)+h<<0,k=m^h,g+=(k^d)+O[3]-722521979,g=(g<<16|g>>>16)+m<<0,d+=(k^g)+O[6]+76029189,d=(d<<23|d>>>9)+g<<0,M=d^g,h+=(M^m)+O[9]-640364487,h=(h<<4|h>>>28)+d<<0,m+=(M^h)+O[12]-421815835,m=(m<<11|m>>>21)+h<<0,k=m^h,g+=(k^d)+O[15]+530742520,g=(g<<16|g>>>16)+m<<0,d+=(k^g)+O[2]-995338651,d=(d<<23|d>>>9)+g<<0,h+=(g^(d|~m))+O[0]-198630844,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[14]-1416354905,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[5]-57434055,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[12]+1700485571,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[10]-1051523,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[1]-2054922799,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[8]+1873313359,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[6]-1560198380,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[13]+1309151649,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[4]-145523070,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[2]+718787259,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[9]-343485551,d=(d<<21|d>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=d-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+d<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},w.prototype.hex=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[d>>>4&15]+u[d&15]+u[d>>>12&15]+u[d>>>8&15]+u[d>>>20&15]+u[d>>>16&15]+u[d>>>28&15]+u[d>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},w.prototype.toString=w.prototype.hex,w.prototype.digest=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,d&255,d>>>8&255,d>>>16&255,d>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},w.prototype.array=w.prototype.digest,w.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),d=new Uint32Array(h);return d[0]=this.h0,d[1]=this.h1,d[2]=this.h2,d[3]=this.h3,h},w.prototype.buffer=w.prototype.arrayBuffer,w.prototype.base64=function(){for(var h,d,g,m="",M=this.array(),k=0;k<15;)h=M[k++],d=M[k++],g=M[k++],m+=y[h>>>2]+y[(h<<4|d>>>4)&63]+y[(d<<2|g>>>6)&63]+y[g&63];return h=M[k],m+=y[h>>>2]+y[h<<4&63]+"==",m};function I(h,d){var g,m=_(h);if(h=m[0],m[1]){var M=[],k=h.length,O=0,N;for(g=0;g<k;++g)N=h.charCodeAt(g),N<128?M[O++]=N:N<2048?(M[O++]=192|N>>>6,M[O++]=128|N&63):N<55296||N>=57344?(M[O++]=224|N>>>12,M[O++]=128|N>>>6&63,M[O++]=128|N&63):(N=65536+((N&1023)<<10|h.charCodeAt(++g)&1023),M[O++]=240|N>>>18,M[O++]=128|N>>>12&63,M[O++]=128|N>>>6&63,M[O++]=128|N&63);h=M}h.length>64&&(h=new w(!0).update(h).array());var X=[],Ae=[];for(g=0;g<64;++g){var Be=h[g]||0;X[g]=92^Be,Ae[g]=54^Be}w.call(this,d),this.update(Ae),this.oKeyPad=X,this.inner=!0,this.sharedMemory=d}I.prototype=new w,I.prototype.finalize=function(){if(w.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();w.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),w.prototype.finalize.call(this)}};var E=q();E.md5=E,E.md5.hmac=A(),o?t.exports=E:s.md5=E})()})(Ir)),Ir.exports}var Rl=Cl(),Er={exports:{}};/**
|
|
489
|
+
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
490
|
+
*
|
|
491
|
+
* @version 0.11.1
|
|
492
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
493
|
+
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
494
|
+
* @license MIT
|
|
495
|
+
*/var gi;function Tl(){return gi||(gi=1,(function(t){(function(){var e="input is invalid type",n=typeof window=="object",r=n?window:{};r.JS_SHA256_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",i=!r.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?r=da:s&&(r=self);var a=!r.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!r.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],f=[24,16,8,0],l=[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],p=["hex","array","digest","arrayBuffer"],y=[];(r.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(S){return Object.prototype.toString.call(S)==="[object Array]"}),o&&(r.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(S){return typeof S=="object"&&S.buffer&&S.buffer.constructor===ArrayBuffer});var v=function(S,x){return function(A){return new _(x,!0).update(A)[S]()}},b=function(S){var x=v("hex",S);i&&(x=C(x,S)),x.create=function(){return new _(S)},x.update=function(I){return x.create().update(I)};for(var A=0;A<p.length;++A){var w=p[A];x[w]=v(w,S)}return x},C=function(S,x){var A=Pn,w=Pn.Buffer,I=x?"sha224":"sha256",E;w.from&&!r.JS_SHA256_NO_BUFFER_FROM?E=w.from:E=function(d){return new w(d)};var h=function(d){if(typeof d=="string")return A.createHash(I).update(d,"utf8").digest("hex");if(d==null)throw new Error(e);return d.constructor===ArrayBuffer&&(d=new Uint8Array(d)),Array.isArray(d)||ArrayBuffer.isView(d)||d.constructor===w?A.createHash(I).update(E(d)).digest("hex"):S(d)};return h},T=function(S,x){return function(A,w){return new D(A,x,!0).update(w)[S]()}},R=function(S){var x=T("hex",S);x.create=function(I){return new D(I,S)},x.update=function(I,E){return x.create(I).update(E)};for(var A=0;A<p.length;++A){var w=p[A];x[w]=T(w,S)}return x};function _(S,x){x?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],S?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=S}_.prototype.update=function(S){if(!this.finalized){var x,A=typeof S;if(A!=="string"){if(A==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);x=!0}for(var w,I=0,E,h=S.length,d=this.blocks;I<h;){if(this.hashed&&(this.hashed=!1,d[0]=this.block,this.block=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0),x)for(E=this.start;I<h&&E<64;++I)d[E>>>2]|=S[I]<<f[E++&3];else for(E=this.start;I<h&&E<64;++I)w=S.charCodeAt(I),w<128?d[E>>>2]|=w<<f[E++&3]:w<2048?(d[E>>>2]|=(192|w>>>6)<<f[E++&3],d[E>>>2]|=(128|w&63)<<f[E++&3]):w<55296||w>=57344?(d[E>>>2]|=(224|w>>>12)<<f[E++&3],d[E>>>2]|=(128|w>>>6&63)<<f[E++&3],d[E>>>2]|=(128|w&63)<<f[E++&3]):(w=65536+((w&1023)<<10|S.charCodeAt(++I)&1023),d[E>>>2]|=(240|w>>>18)<<f[E++&3],d[E>>>2]|=(128|w>>>12&63)<<f[E++&3],d[E>>>2]|=(128|w>>>6&63)<<f[E++&3],d[E>>>2]|=(128|w&63)<<f[E++&3]);this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.block=d[16],this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},_.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var S=this.blocks,x=this.lastByteIndex;S[16]=this.block,S[x>>>2]|=u[x&3],this.block=S[16],x>=56&&(this.hashed||this.hash(),S[0]=this.block,S[16]=S[1]=S[2]=S[3]=S[4]=S[5]=S[6]=S[7]=S[8]=S[9]=S[10]=S[11]=S[12]=S[13]=S[14]=S[15]=0),S[14]=this.hBytes<<3|this.bytes>>>29,S[15]=this.bytes<<3,this.hash()}},_.prototype.hash=function(){var S=this.h0,x=this.h1,A=this.h2,w=this.h3,I=this.h4,E=this.h5,h=this.h6,d=this.h7,g=this.blocks,m,M,k,O,N,X,Ae,Be,ft,qt,Ut;for(m=16;m<64;++m)N=g[m-15],M=(N>>>7|N<<25)^(N>>>18|N<<14)^N>>>3,N=g[m-2],k=(N>>>17|N<<15)^(N>>>19|N<<13)^N>>>10,g[m]=g[m-16]+M+g[m-7]+k<<0;for(Ut=x&A,m=0;m<64;m+=4)this.first?(this.is224?(Be=300032,N=g[0]-1413257819,d=N-150054599<<0,w=N+24177077<<0):(Be=704751109,N=g[0]-210244248,d=N-1521486534<<0,w=N+143694565<<0),this.first=!1):(M=(S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10),k=(I>>>6|I<<26)^(I>>>11|I<<21)^(I>>>25|I<<7),Be=S&x,O=Be^S&A^Ut,Ae=I&E^~I&h,N=d+k+Ae+l[m]+g[m],X=M+O,d=w+N<<0,w=N+X<<0),M=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),k=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),ft=w&S,O=ft^w&x^Be,Ae=d&I^~d&E,N=h+k+Ae+l[m+1]+g[m+1],X=M+O,h=A+N<<0,A=N+X<<0,M=(A>>>2|A<<30)^(A>>>13|A<<19)^(A>>>22|A<<10),k=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),qt=A&w,O=qt^A&S^ft,Ae=h&d^~h&I,N=E+k+Ae+l[m+2]+g[m+2],X=M+O,E=x+N<<0,x=N+X<<0,M=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),k=(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7),Ut=x&A,O=Ut^x&w^qt,Ae=E&h^~E&d,N=I+k+Ae+l[m+3]+g[m+3],X=M+O,I=S+N<<0,S=N+X<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+S<<0,this.h1=this.h1+x<<0,this.h2=this.h2+A<<0,this.h3=this.h3+w<<0,this.h4=this.h4+I<<0,this.h5=this.h5+E<<0,this.h6=this.h6+h<<0,this.h7=this.h7+d<<0},_.prototype.hex=function(){this.finalize();var S=this.h0,x=this.h1,A=this.h2,w=this.h3,I=this.h4,E=this.h5,h=this.h6,d=this.h7,g=c[S>>>28&15]+c[S>>>24&15]+c[S>>>20&15]+c[S>>>16&15]+c[S>>>12&15]+c[S>>>8&15]+c[S>>>4&15]+c[S&15]+c[x>>>28&15]+c[x>>>24&15]+c[x>>>20&15]+c[x>>>16&15]+c[x>>>12&15]+c[x>>>8&15]+c[x>>>4&15]+c[x&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[w>>>28&15]+c[w>>>24&15]+c[w>>>20&15]+c[w>>>16&15]+c[w>>>12&15]+c[w>>>8&15]+c[w>>>4&15]+c[w&15]+c[I>>>28&15]+c[I>>>24&15]+c[I>>>20&15]+c[I>>>16&15]+c[I>>>12&15]+c[I>>>8&15]+c[I>>>4&15]+c[I&15]+c[E>>>28&15]+c[E>>>24&15]+c[E>>>20&15]+c[E>>>16&15]+c[E>>>12&15]+c[E>>>8&15]+c[E>>>4&15]+c[E&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[d>>>28&15]+c[d>>>24&15]+c[d>>>20&15]+c[d>>>16&15]+c[d>>>12&15]+c[d>>>8&15]+c[d>>>4&15]+c[d&15]),g},_.prototype.toString=_.prototype.hex,_.prototype.digest=function(){this.finalize();var S=this.h0,x=this.h1,A=this.h2,w=this.h3,I=this.h4,E=this.h5,h=this.h6,d=this.h7,g=[S>>>24&255,S>>>16&255,S>>>8&255,S&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,w>>>24&255,w>>>16&255,w>>>8&255,w&255,I>>>24&255,I>>>16&255,I>>>8&255,I&255,E>>>24&255,E>>>16&255,E>>>8&255,E&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(d>>>24&255,d>>>16&255,d>>>8&255,d&255),g},_.prototype.array=_.prototype.digest,_.prototype.arrayBuffer=function(){this.finalize();var S=new ArrayBuffer(this.is224?28:32),x=new DataView(S);return x.setUint32(0,this.h0),x.setUint32(4,this.h1),x.setUint32(8,this.h2),x.setUint32(12,this.h3),x.setUint32(16,this.h4),x.setUint32(20,this.h5),x.setUint32(24,this.h6),this.is224||x.setUint32(28,this.h7),S};function D(S,x,A){var w,I=typeof S;if(I==="string"){var E=[],h=S.length,d=0,g;for(w=0;w<h;++w)g=S.charCodeAt(w),g<128?E[d++]=g:g<2048?(E[d++]=192|g>>>6,E[d++]=128|g&63):g<55296||g>=57344?(E[d++]=224|g>>>12,E[d++]=128|g>>>6&63,E[d++]=128|g&63):(g=65536+((g&1023)<<10|S.charCodeAt(++w)&1023),E[d++]=240|g>>>18,E[d++]=128|g>>>12&63,E[d++]=128|g>>>6&63,E[d++]=128|g&63);S=E}else if(I==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);S.length>64&&(S=new _(x,!0).update(S).array());var m=[],M=[];for(w=0;w<64;++w){var k=S[w]||0;m[w]=92^k,M[w]=54^k}_.call(this,x,A),this.update(M),this.oKeyPad=m,this.inner=!0,this.sharedMemory=A}D.prototype=new _,D.prototype.finalize=function(){if(_.prototype.finalize.call(this),this.inner){this.inner=!1;var S=this.array();_.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(S),_.prototype.finalize.call(this)}};var q=b();q.sha256=q,q.sha224=b(!0),q.sha256.hmac=R(),q.sha224.hmac=R(!0),a?t.exports=q:(r.sha256=q.sha256,r.sha224=q.sha224)})()})(Er)),Er.exports}var Nl=Tl();function Ll(t){if(t instanceof Ie)return t;if(typeof t=="string")return Ie.fromUtf8(t);throw new V(`hashing.* requires Bytes or String, got ${typeof t}`)}function Dl(t,e){const n=Ll(e[0]);switch(t){case"md5":return new Ie(new Uint8Array(Rl.md5.arrayBuffer(n.data)));case"sha256":return new Ie(new Uint8Array(Nl.sha256.arrayBuffer(n.data)));case"crc32":{const r=Ml(n.data);return new Ie(yi(r))}case"crc32c":{const r=$l(n.data);return new Ie(yi(r))}}throw new yt(`Unknown hashing method '${t}'`)}function yi(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const Fl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Ml(t){let e=4294967295;for(let n=0;n<t.length;n++)e=Fl[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const jl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function $l(t){let e=4294967295;for(let n=0;n<t.length;n++)e=jl[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function Pl(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof ae)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new V(`int() cannot convert string '${t}' to an integer`)}throw new V(`int() cannot convert ${typeof t} to an integer`)}function ql(t){if(t instanceof ae)return t;if(typeof t=="number")return new ae(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new ae(parseFloat(e));throw new V(`float() cannot convert string '${t}' to a float`)}throw new V(`float() cannot convert ${typeof t} to a float`)}function Ul(t,e,n,r){switch(t){case"get":{const a=String(G(e[0],n,r));return An(n,"doc",a),hi(a,n)}case"exists":{const a=String(G(e[0],n,r));return An(n,"doc",a),fi(a,n)}case"getAfter":{const a=G(e[0],n,r),o=String(a),c=fn(o),u=c.split("/").filter(Boolean);if(!hn(u))throw new V(`getAfter() requires a path pointing to a document (even segment count), got '${c}'`);if(An(n,"after",c),o===n.afterStatePath.toString()){if(n.afterState===null)throw new V(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Jr(c,n.afterState)}if(n.batchProjection?.has(c)){const f=n.batchProjection.get(c);if(f===null)throw new V(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Jr(c,f)}return hi(o,n)}case"existsAfter":{const a=G(e[0],n,r),o=String(a),c=fn(o),u=c.split("/").filter(Boolean);return hn(u)?(An(n,"after",c),o===n.afterStatePath.toString()?n.existsAfter:n.batchProjection?.has(c)?n.batchProjection.get(c)!==null:fi(o,n)):!1}case"string":return String(G(e[0],n,r));case"int":return Pl(G(e[0],n,r));case"float":return ql(G(e[0],n,r));case"path":{const a=G(e[0],n,r);if(typeof a=="string")return Xe.fromString(a);throw new V(`path() requires a string argument, got ${typeof a}`)}}const s=n.functions.get(t);if(!s)throw new V(`Unknown function: ${t}`);const i={...r};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=G(e[a],n,r);n.trace?.enterFrame(t);try{for(const a of s.lets){const o=n.trace?n.trace.entries.length:-1;i[a.name]=G(a.value,n,i),o>=0&&n.trace?.markEntryAsLetBinding(o,a.name)}return G(s.body,n,i)}finally{n.trace?.exitFrame()}}function Bl(t,e,n,r,s){if(t.type==="identifier"){const o=t.name;if(vi(o)&&!(o in s)&&!(o in r.pathVariables)){const c=n.map(u=>G(u,r,s));return Vl(o,e,c)}if(!vi(o)&&!(o in s)&&!(o in r.pathVariables)&&!Ql(o))throw new yt(`Unknown namespace or method '${o}.${e}()'`)}const i=G(t,r,s),a=n.map(o=>G(o,r,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===oe)throw new yt(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new un(o,i);throw new V("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof de)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof de))throw new V(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof un)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"diff":{const c=a[0];return new un(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const p of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(p);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const f=String(c);return Object.hasOwn(o,f)?o[f]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>me(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>me(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>me(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new V(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new V(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>me(c,u)))}case"toSet":return new de(i);case"difference":case"union":case"intersection":throw new V(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(xr(String(a[0]),"g"));case"matches":return xr(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(xr(String(a[0]),"g"),String(a[1]));case"toUtf8":return Ie.fromUtf8(i)}throw new V(`Unknown method '${e}' on ${typeof i}`)}function xr(t,e=""){try{return new RegExp(t,e)}catch(n){throw new V(`Invalid regex '${t}': ${n.message}`)}}const zl=new Set(["math","timestamp","duration","latlng","hashing"]);function vi(t){return zl.has(t)}function Vl(t,e,n){const r=t==="hashing"?n:n.map(Wl);switch(t){case"math":return Gl(e,r);case"timestamp":return Kl(e,r);case"duration":return Zl(e,r);case"latlng":return Hl(e,r);case"hashing":return Dl(e,n)}throw new yt(`Unknown namespace '${t}'`)}function Wl(t){return t instanceof ae?t.value:t}function Hl(t,e){switch(t){case"value":{const[n,r]=e;return new lt(n,r)}}throw new yt(`Unknown latlng method '${t}'`)}function Gl(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isNaN":return Number.isNaN(e[0])}throw new V(`Unknown math method '${t}'`)}function Kl(t,e){switch(t){case"date":{const[n,r,s]=e;return _e.fromYMD(n,r,s)}case"value":return _e.fromMillis(e[0])}throw new yt(`Unknown timestamp method '${t}'`)}function Zl(t,e){switch(t){case"value":try{return ve.fromValue(e[0],e[1])}catch(n){throw new V(n.message)}case"time":{const[n,r,s,i]=e;return ve.fromTime(n,r,s,i)}case"abs":{const n=e[0];if(!(n instanceof ve))throw new V(`duration.abs() requires a Duration argument, got ${typeof n}`);return ve.abs(n)}}throw new yt(`Unknown duration method '${t}'`)}function G(t,e,n={}){return e.trace?e.trace.capture(t,()=>bi(t,e,n)):bi(t,e,n)}function bi(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new ae(t.value):t.value;case"identifier":return Jl(t.name,e,n);case"binaryOp":return Yl(t.op,t.left,t.right,e,n);case"unaryOp":{if(t.op==="!")return!Vt(G(t.operand,e,n),t.operand);if(t.op==="-"){const r=G(t.operand,e,n);return r instanceof ae?new ae(-r.value):-r}throw new V(`Unknown unary op: ${t.op}`,t)}case"ternary":{const r=Vt(G(t.condition,e,n),t.condition);return G(r?t.consequent:t.alternate,e,n)}case"memberAccess":{const r=G(t.object,e,n);if(r==null)throw new V(`Property '${t.property}' accessed on ${r===null?"null":"undefined"} value`,t);if(r instanceof te)return r.field(t.property);if(r instanceof un)switch(t.property){case"addedKeys":return()=>r.addedKeys();case"removedKeys":return()=>r.removedKeys();case"changedKeys":return()=>r.changedKeys();case"affectedKeys":return()=>r.affectedKeys();case"unchangedKeys":return()=>r.unchangedKeys()}if(r instanceof de)switch(t.property){case"size":return()=>r.size()}if(Object.hasOwn(r,t.property))return r[t.property];throw new V(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const r=G(t.object,e,n),s=G(t.index,e,n);if(r==null)throw new V(`Index access on ${r===null?"null":"undefined"} value`,t);if(r instanceof te)return r.field(String(s));const i=String(s);return Object.hasOwn(r,i)?r[i]:null}case"sliceAccess":{const r=G(t.object,e,n),s=G(t.start,e,n),i=G(t.end,e,n);if(r==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new V(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new V(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new V(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof r=="string"||Array.isArray(r)){if(i>r.length)throw new V(`Slice end ${i} exceeds length ${r.length}`);return r.slice(s,i)}throw new V(`Slice not supported on ${typeof r}`)}case"inExpr":{const r=G(t.element,e,n),s=G(t.collection,e,n);return s==null?!1:Array.isArray(s)?s.some(i=>me(i,r)):typeof s=="object"?Object.hasOwn(s,String(r)):!1}case"isExpr":{const r=G(t.value,e,n);switch(t.typeName){case"string":return typeof r=="string";case"int":return r instanceof te?!1:typeof r=="number";case"float":return r instanceof ae;case"number":return r instanceof ae?!0:r instanceof te?!1:typeof r=="number";case"bool":return typeof r=="boolean";case"null":return r===null;case"list":return Array.isArray(r);case"map":return r instanceof te||r instanceof un||r instanceof de?!1:typeof r=="object"&&r!==null&&!Array.isArray(r);default:return r instanceof te?r.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(r=>G(r,e,n));case"mapLiteral":{const r={};for(const s of t.entries){const i=String(G(s.key,e,n));r[i]=G(s.value,e,n)}return r}case"functionCall":return Ul(t.name,t.args,e,n);case"methodCall":return Bl(t.object,t.method,t.args,e,n);case"pathLiteral":{const r=[];for(const s of t.segments)typeof s=="string"?r.push(s):r.push(String(G(s,e,n)));return new Xe(r)}default:throw new V(`Unknown expression type: ${t.type}`,t)}}function Jl(t,e,n){if(t in n)return n[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new V("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new V(`Undefined variable '${t}'`)}function Ql(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function Yl(t,e,n,r,s){if(t==="&&"){let o,c;try{o=Vt(G(e,r,s),e)}catch(l){c=l}if(c instanceof $n)throw c;if(c===void 0&&o===!1)return r.trace?.skip(n),!1;let u,f;try{u=Vt(G(n,r,s),n)}catch(l){f=l}if(f===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}if(t==="||"){let o,c;try{o=Vt(G(e,r,s),e)}catch(l){c=l}if(c instanceof $n)throw c;if(c===void 0&&o===!0)return r.trace?.skip(n),!0;let u,f;try{u=Vt(G(n,r,s),n)}catch(l){f=l}if(f===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}const i=G(e,r,s),a=G(n,r,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==oe)return o}if(typeof i=="number"&&a instanceof ae){const o=new ae(i).binaryOp(t,a);if(o!==oe)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==oe)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new V(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new V(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||me(i,a);case"!=":return!(i===a||me(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new V(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new V("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new V("Modulo by zero");return i%a;default:throw new V(`Unknown binary op: ${t}`)}}function Vt(t,e){if(typeof t=="boolean")return t;throw new V(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const Xl=new Set(["__proto__","prototype","constructor"]);function qn(t){if(Xl.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 Xa(t,e){const n={...t};for(const[r,s]of Object.entries(e)){qn(r);const i=Object.hasOwn(n,r)?n[r]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]=Xa(i,s):n[r]=s}return n}function ed(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){const a=e[i];qn(a);const o=Object.hasOwn(r,a)?r[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(r[a]={}),r=r[a]}const s=e[e.length-1];qn(s),r[s]=n}function td(t,e){const n={...t};for(const[r,s]of Object.entries(e))r.includes(".")?ed(n,r.split("."),s):(qn(r),n[r]=s);return n}function nd(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?Xa(e??{},n):n;case"update":return td(e??{},n);case"delete":return null}}function eo(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function rd(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function to(t,e){const n={};for(const[r,s]of Object.entries(t))rd(s)?n[r]=e:eo(s)?n[r]=to(s,e):n[r]=s;return n}function Et(t){return typeof t=="number"&&!Number.isInteger(t)?new ae(t):Array.isArray(t)?t.map(Et):eo(t)?t.__type==="float"&&typeof t.value=="number"?new ae(t.value):Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Et(n)])):t}function wi(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function On(t){return`/${t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}`}function Un(t,e,n,r){const s=[...n,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const p of i)if(p.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==p.value){u="literal-mismatch";break}c++}else if(p.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[p.name]=e[c],c===e.length-1&&o.push(p.name),c++}else a[p.name]=e.slice(c).join("/"),c<e.length&&o.push(p.name),c=e.length;if(u!==void 0)return r?.push({...t.loc?{line:t.loc.line}:{},blockPath:On(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const f=e.slice(c);if(f.length===0)return r?.push({...t.loc?{line:t.loc.line}:{},blockPath:On(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const p of t.children)for(const y of Un(p,f,s,r))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return r?.push({...t.loc?{line:t.loc.line}:{},blockPath:On(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class sd{attempts=[];push(e){this.attempts.push(e)}}function id(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 ad(t,e,n,r){const s=id(e),i=[],a=[],o=[];for(let p=0;p<t.allows.length;p++){const y=t.allows[p];y.operations.some(b=>s.includes(b))&&o.push({rule:y,index:p})}if(o.length===0)return a.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:a};let u=!1;const f=n.trace;for(const{rule:p,index:y}of o){const v=od(p,y,r),b=new yl;n.trace=b;try{const C=G(p.condition,n);if(v.expressionTrace=b.entries,!!C)return v.verdict="ALLOW",i.push(v),n.trace=f,{decision:"ALLOW",trace:i,notes:a};v.verdict="DENY",i.push(v)}catch(C){if(v.expressionTrace=b.entries,C instanceof $n)return v.verdict="ERROR",v.message=C.message,i.push(v),n.trace=f,a.push(`Request denied by a rules resource limit: ${C.message}. The limit is per request, so no other allow rule or match block was evaluated.`),{decision:"DENY",trace:i,notes:a,resourceLimit:C.message};C instanceof yt?(u=!0,v.verdict="UNSUPPORTED",v.message=C.message):(v.verdict="ERROR",C instanceof Error?v.message=C.message:v.message=String(C)),i.push(v)}}n.trace=f;let l="DENY";return u&&(l="UNSUPPORTED"),{decision:l,trace:i,notes:a}}function od(t,e,n){const r=ye(t.condition),s={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:r};if(t.loc!==void 0){const a=t.loc;if(s.line=a.line,s.col=a.col,s.column=a.col,a.file!==void 0?(s.file=a.file,s.citation=`${a.file}:${a.line}:${a.col}`):(s.file="firestore.rules",s.citation=`firestore.rules:${a.line}:${a.col}`),n!==void 0){const u=Ya(n,a.line,a.col,a.file,r);u!==void 0&&(s.line=u.line,s.col=u.col,s.column=u.col,s.file=u.file,s.citation=u.citation,u.expression!==void 0&&(s.conditionText=u.expression))}}return s}function cd(t,e,n,r,s,i){const a=new Map;for(const _ of e)a.set(_.name,_);const o=new Map,c=new Set;if(t.functionMocks)for(const _ of t.functionMocks)_.function==="get"&&typeof _.result=="object"&&_.result!==null?(o.set(_.path,Et(_.result)),c.add(_.path)):_.function==="exists"&&_.result===!0&&(o.set(_.path,{}),c.add(_.path));const u=t.requestTime?_e.fromIsoString(t.requestTime):_e.fromMillis(Date.now()),l=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],p=new Xe(l,n),y=Et(t.data??{}),v=t.resource===void 0||t.resource===null?null:Et(t.resource);let b,C;if(t.writeMode)b=nd(t.writeMode,v,y),C=b!==null;else switch(t.method){case"create":case"update":b=y,C=!0;break;case"delete":b=null,C=!1;break;case"get":case"list":default:b=v,C=v!==null;break}const T=b!==null?Et(to(b,u)):null,R=T??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:R},method:t.method,path:p,...wi(t)?{query:wi(t)}:{},time:u},resource:t.method==="create"||v===null?null:{data:Et(v)},mockDocuments:o,identitylessFunctionMocks:c,getDoc:r,pathVariables:n,functions:a,database:"(default)",afterStatePath:p,afterState:T,existsAfter:C,...s?{batchProjection:s}:{},lookupBudget:i}}class ud{simulate(e,n,r){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 s=Es(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const f of s.service.match.path.segments)f.type==="wildcard"&&(u[f.name]="(default)");for(const f of n){const l=f.path.split("/").filter(Boolean),p=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const v=new sd;for(const m of s.service.match.children)y.push(...Un(m,l,p,v));let b=!1;const C=y.length===0,T=f.method==="list";if(C&&T){const m=[...l,"__hypothetical_doc__"];for(const k of s.service.match.children)y.push(...Un(k,m,p,v));y.length>0&&(b=!0)}const R={requestPath:f.path,attempts:v.attempts};if(y.length===0){const m=f.expectation==="DENY"?"PASSED":"FAILED";m==="PASSED"?a++:o++,i.push({description:f.description,expectation:f.expectation,state:m,decision:"DENY",trace:[],notes:[`No match block found for path '${f.path}'`],pathResolution:R});continue}let D="DENY";const q=[],S=[];let x=!1,A,w=!1;const I=new xl;for(const m of y){const M={...u,...m.pathVariables},k=cd(f,m.functions,M,r?.getDoc,r?.batchProjection,I),O=On(m.block),N=ad(m.block,f.method,k,e);for(const ft of N.trace)ft.matchPath=O;if(q.push(...N.trace),S.push(...N.notes),N.resourceLimit!==void 0){D="DENY",w=!0;break}if(N.decision==="ALLOW"){D="ALLOW",A=O;break}N.decision==="UNSUPPORTED"&&(x=!0)}D!=="ALLOW"&&!w&&x&&(D="UNSUPPORTED"),D==="ALLOW"&&A!==void 0&&S.push(`Allowed by match block '${A}'`),b===!0&&S.push(`list on collection path '${f.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let g;D==="UNSUPPORTED"?(g="UNSUPPORTED",c++):D===f.expectation?(g="PASSED",a++):(g="FAILED",o++),i.push({description:f.description,expectation:f.expectation,state:g,decision:D,trace:q,notes:S,pathResolution:R})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function ld(t,e,n=new Map,r){if(Bn(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=hd(t,n,r);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(p=>p.field===u.field&&p.op==="=="&&gd(p.value,u.value)))continue;const l=a.find(p=>p.field===u.field&&p.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:dd(o,c),residual:{missing:o,mismatched:c}}}function dd(t,e){const n=[];if(t.length>0){const r=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");n.push(`the query has no matching where(...) equality for [${r}]`)}if(e.length>0){const r=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");n.push(`the query where(...) value does not match [${r}]`)}return`${n.join("; ")} — prod rejects the query ("rules are not filters")`}function Bn(t,e=new Map,n=new Set){const r=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return r(s.object);case"bracketAccess":return r(s.object)&&r(s.index);case"sliceAccess":return r(s.object)&&r(s.start)&&r(s.end);case"binaryOp":return r(s.left)&&r(s.right);case"unaryOp":return r(s.operand);case"ternary":return r(s.condition)&&r(s.consequent)&&r(s.alternate);case"inExpr":return r(s.element)&&r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.every(r);case"mapLiteral":return s.entries.every(i=>r(i.key)&&r(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||r(i));case"methodCall":return r(s.object)&&s.args.every(r);case"functionCall":{if(!s.args.every(r))return!1;const i=e.get(s.name);if(!i)return!0;if(n.has(s.name))return!1;const a=new Set(n).add(s.name);return Bn(i.body,e,a)&&i.lets.every(o=>Bn(o.value,e,a))}default:return!1}};return r(t)}function hd(t,e,n){const r=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((p,y)=>{const v=i.args[y];v&&u.set(p,v)});for(const p of c.lets)u.set(p.name,Si(p.value,u));const f=Si(c.body,u),l=new Set(a).add(i.name);return s(f,l)}const o=fd(i,n);return o?(r.push(o),!0):Bn(i,e)};return s(t,new Set)?{ok:!0,required:r}:{ok:!1}}function fd(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const n=(r,s)=>{const i=md(r);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&pd(s)?{field:i,value:e,fromAuthUid:!0}:null};return n(t.left,t.right)??n(t.right,t.left)}function pd(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function Si(t,e){const n=r=>{switch(r.type){case"identifier":return e.get(r.name)??r;case"literal":return r;case"memberAccess":return{...r,object:n(r.object)};case"methodCall":return{...r,object:n(r.object),args:r.args.map(n)};case"bracketAccess":return{...r,object:n(r.object),index:n(r.index)};case"sliceAccess":return{...r,object:n(r.object),start:n(r.start),end:n(r.end)};case"binaryOp":return{...r,left:n(r.left),right:n(r.right)};case"unaryOp":return{...r,operand:n(r.operand)};case"ternary":return{...r,condition:n(r.condition),consequent:n(r.consequent),alternate:n(r.alternate)};case"inExpr":return{...r,element:n(r.element),collection:n(r.collection)};case"isExpr":return{...r,value:n(r.value)};case"listLiteral":return{...r,elements:r.elements.map(n)};case"mapLiteral":return{...r,entries:r.entries.map(s=>({key:n(s.key),value:n(s.value)}))};case"pathLiteral":return{...r,segments:r.segments.map(s=>typeof s=="string"?s:n(s))};case"functionCall":return{...r,args:r.args.map(n)}}};return n(t)}function md(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function gd(t,e){return t===e}class Rt extends te{typeName="reference";path;constructor(e){super(),this.path=yd(e)}static fromResourceName(e){return new Rt(no(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 Rt?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 oe}}function yd(t){let e=no(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function no(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class Xt extends te{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 Xt)||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 oe}}var J;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var _i;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(_i||(_i={}));const $=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}},L=J.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=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let o=r,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}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,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}dt.create=t=>new dt(t);const Qr=(t,e)=>{let n;switch(t.code){case L.invalid_type:t.received===$.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:n=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case L.invalid_union:n="Invalid input";break;case L.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case L.invalid_enum_value:n=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:n="Invalid function arguments";break;case L.invalid_return_type:n="Invalid function return type";break;case L.invalid_date:n="Invalid date";break;case L.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}"`:J.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case L.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 L.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 L.custom:n="Invalid input";break;case L.invalid_intersection_types:n="Intersection results could not be merged";break;case L.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:n="Number must be finite";break;default:n=e.defaultError,J.assertNever(t)}return{message:n}};let vd=Qr;function bd(){return vd}const wd=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function j(t,e){const n=bd(),r=wd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Qr?void 0:Qr].filter(s=>!!s)});t.common.issues.push(r)}class Fe{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return Fe.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const U=Object.freeze({status:"aborted"}),on=t=>({status:"dirty",value:t}),We=t=>({status:"valid",value:t}),Ai=t=>t.status==="aborted",Ii=t=>t.status==="dirty",Kt=t=>t.status==="valid",zn=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class nt{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}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 Ei=(t,e)=>{if(Kt(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 H(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Fe,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(zn(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 r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ei(r,s)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return Kt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Kt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(zn(s)?s:Promise.resolve(s));return Ei(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:L.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Lt({schema:this,typeName:B.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 ut.create(this,this._def)}nullable(){return Dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return Jn.create(this,this._def)}or(e){return Hn.create([this,e],this._def)}and(e){return Gn.create(this,e,this._def)}transform(e){return new Lt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Qn({...H(this._def),innerType:this,defaultValue:n,typeName:B.ZodDefault})}brand(){return new ao({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Yn({...H(this._def),innerType:this,catchValue:n,typeName:B.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Cs.create(this,e)}readonly(){return Xn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Sd=/^c[^\s-]{8,}$/i,_d=/^[0-9a-z]+$/,Ad=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Id=/^[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,Ed=/^[a-z0-9_-]{21}$/i,xd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kd=/^[-+]?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)?)??$/,Od=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Cd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let kr;const Rd=/^(?:(?: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])$/,Td=/^(?:(?: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])$/,Nd=/^(([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]))$/,Ld=/^(([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])$/,Dd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ro="((\\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])))",Md=new RegExp(`^${ro}$`);function so(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 jd(t){return new RegExp(`^${so(t)}$`)}function $d(t){let e=`${ro}T${so(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 Pd(t,e){return!!((e==="v4"||!e)&&Rd.test(t)||(e==="v6"||!e)&&Nd.test(t))}function qd(t,e){if(!xd.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Ud(t,e){return!!((e==="v4"||!e)&&Td.test(t)||(e==="v6"||!e)&&Ld.test(t))}class ot extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){const i=this._getOrReturnCtx(e);return j(i,{code:L.invalid_type,expected:$.string,received:i.parsedType}),U}const r=new Fe;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?j(s,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&j(s,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Od.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")kr||(kr=new RegExp(Cd,"u")),kr.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Id.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ed.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Sd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")_d.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ad.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:L.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:L.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.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)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?$d(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Md.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?jd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:L.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?kd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Pd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?qd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Ud(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Dd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Fd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:L.invalid_string,message:i.message}),r.dirty()):J.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:L.invalid_string,...P.errToObj(r)})}_addCheck(e){return new ot({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.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,...P.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,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...P.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...P.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...P.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...P.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...P.errToObj(n)})}nonempty(e){return this.min(1,P.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:B.ZodString,coerce:t?.coerce??!1,...H(t)});function Bd(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class Zt extends K{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)!==$.number){const i=this._getOrReturnCtx(e);return j(i,{code:L.invalid_type,expected:$.number,received:i.parsedType}),U}let r;const s=new Fe;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Bd(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:L.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,P.toString(n))}gt(e,n){return this.setLimit("min",e,!1,P.toString(n))}lte(e,n){return this.setLimit("max",e,!0,P.toString(n))}lt(e,n){return this.setLimit("max",e,!1,P.toString(n))}setLimit(e,n,r,s){return new Zt({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:P.toString(s)}]})}_addCheck(e){return new Zt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.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"&&J.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Zt.create=t=>new Zt({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class pn extends K{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)!==$.bigint)return this._getInvalidInput(e);let r;const s=new Fe;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),j(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return j(n,{code:L.invalid_type,expected:$.bigint,received:n.parsedType}),U}gte(e,n){return this.setLimit("min",e,!0,P.toString(n))}gt(e,n){return this.setLimit("min",e,!1,P.toString(n))}lte(e,n){return this.setLimit("max",e,!0,P.toString(n))}lt(e,n){return this.setLimit("max",e,!1,P.toString(n))}setLimit(e,n,r,s){return new pn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:P.toString(s)}]})}_addCheck(e){return new pn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:P.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}}pn.create=t=>new pn({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class Yr extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.boolean,received:r.parsedType}),U}return We(e.data)}}Yr.create=t=>new Yr({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class Vn extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){const i=this._getOrReturnCtx(e);return j(i,{code:L.invalid_type,expected:$.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return j(i,{code:L.invalid_date}),U}const r=new Fe;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):J.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Vn({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:P.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}}Vn.create=t=>new Vn({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class xi extends K{_parse(e){if(this._getType(e)!==$.symbol){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.symbol,received:r.parsedType}),U}return We(e.data)}}xi.create=t=>new xi({typeName:B.ZodSymbol,...H(t)});class Xr extends K{_parse(e){if(this._getType(e)!==$.undefined){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.undefined,received:r.parsedType}),U}return We(e.data)}}Xr.create=t=>new Xr({typeName:B.ZodUndefined,...H(t)});class Wn extends K{_parse(e){if(this._getType(e)!==$.null){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.null,received:r.parsedType}),U}return We(e.data)}}Wn.create=t=>new Wn({typeName:B.ZodNull,...H(t)});class ki extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return We(e.data)}}ki.create=t=>new ki({typeName:B.ZodAny,...H(t)});class es extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return We(e.data)}}es.create=t=>new es({typeName:B.ZodUnknown,...H(t)});class vt extends K{_parse(e){const n=this._getOrReturnCtx(e);return j(n,{code:L.invalid_type,expected:$.never,received:n.parsedType}),U}}vt.create=t=>new vt({typeName:B.ZodNever,...H(t)});class Oi extends K{_parse(e){if(this._getType(e)!==$.undefined){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.void,received:r.parsedType}),U}return We(e.data)}}Oi.create=t=>new Oi({typeName:B.ZodVoid,...H(t)});class et extends K{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==$.array)return j(n,{code:L.invalid_type,expected:$.array,received:n.parsedType}),U;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(a||o)&&(j(n,{code:a?L.too_big:L.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(j(n,{code:L.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(j(n,{code:L.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>s.type._parseAsync(new nt(n,a,n.path,o)))).then(a=>Fe.mergeArray(r,a));const i=[...n.data].map((a,o)=>s.type._parseSync(new nt(n,a,n.path,o)));return Fe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new et({...this._def,minLength:{value:e,message:P.toString(n)}})}max(e,n){return new et({...this._def,maxLength:{value:e,message:P.toString(n)}})}length(e,n){return new et({...this._def,exactLength:{value:e,message:P.toString(n)}})}nonempty(e){return this.min(1,e)}}et.create=(t,e)=>new et({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Bt(t){if(t instanceof fe){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=ut.create(Bt(r))}return new fe({...t._def,shape:()=>e})}else return t instanceof et?new et({...t._def,type:Bt(t.element)}):t instanceof ut?ut.create(Bt(t.unwrap())):t instanceof Dt?Dt.create(Bt(t.unwrap())):t instanceof Tt?Tt.create(t.items.map(e=>Bt(e))):t}class fe extends K{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=J.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==$.object){const u=this._getOrReturnCtx(e);return j(u,{code:L.invalid_type,expected:$.object,received:u.parsedType}),U}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof vt&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new nt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof vt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(j(s,{code:L.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const l=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new nt(s,l,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,p=await f.value;u.push({key:l,value:p,alwaysSet:f.alwaysSet})}return u}).then(u=>Fe.mergeObjectSync(r,u)):Fe.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{const s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const n={};for(const r of J.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new fe({...this._def,shape:()=>n})}omit(e){const n={};for(const r of J.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new fe({...this._def,shape:()=>n})}deepPartial(){return Bt(this)}partial(e){const n={};for(const r of J.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new fe({...this._def,shape:()=>n})}required(e){const n={};for(const r of J.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ut;)i=i._def.innerType;n[r]=i}return new fe({...this._def,shape:()=>n})}keyof(){return io(J.objectKeys(this.shape))}}fe.create=(t,e)=>new fe({shape:()=>t,unknownKeys:"strip",catchall:vt.create(),typeName:B.ZodObject,...H(e)});fe.strictCreate=(t,e)=>new fe({shape:()=>t,unknownKeys:"strict",catchall:vt.create(),typeName:B.ZodObject,...H(e)});fe.lazycreate=(t,e)=>new fe({shape:t,unknownKeys:"strip",catchall:vt.create(),typeName:B.ZodObject,...H(e)});class Hn extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new dt(o.ctx.common.issues));return j(n,{code:L.invalid_union,unionErrors:a}),U}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},f=c._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new dt(c));return j(n,{code:L.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}Hn.create=(t,e)=>new Hn({options:t,typeName:B.ZodUnion,...H(e)});const it=t=>t instanceof ns?it(t.schema):t instanceof Lt?it(t.innerType()):t instanceof Zn?[t.value]:t instanceof Nt?t.options:t instanceof rs?J.objectValues(t.enum):t instanceof Qn?it(t._def.innerType):t instanceof Xr?[void 0]:t instanceof Wn?[null]:t instanceof ut?[void 0,...it(t.unwrap())]:t instanceof Dt?[null,...it(t.unwrap())]:t instanceof ao||t instanceof Xn?it(t.unwrap()):t instanceof Yn?it(t._def.innerType):[];class Os extends K{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return j(n,{code:L.invalid_type,expected:$.object,received:n.parsedType}),U;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);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}):(j(n,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const a=it(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new Os({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...H(r)})}}function ts(t,e){const n=pt(t),r=pt(e);if(t===e)return{valid:!0,data:t};if(n===$.object&&r===$.object){const s=J.objectKeys(e),i=J.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=ts(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(n===$.array&&r===$.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=ts(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===$.date&&r===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Gn extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(Ai(i)||Ai(a))return U;const o=ts(i.value,a.value);return o.valid?((Ii(i)||Ii(a))&&n.dirty(),{status:n.value,value:o.data}):(j(r,{code:L.invalid_intersection_types}),U)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Gn.create=(t,e,n)=>new Gn({left:t,right:e,typeName:B.ZodIntersection,...H(n)});class Tt extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.array)return j(r,{code:L.invalid_type,expected:$.array,received:r.parsedType}),U;if(r.data.length<this._def.items.length)return j(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new nt(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Fe.mergeArray(n,a)):Fe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Tt({...this._def,rest:e})}}Tt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class Kn extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return j(r,{code:L.invalid_type,expected:$.object,received:r.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in r.data)s.push({key:i._parse(new nt(r,o,r.path,o)),value:a._parse(new nt(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Fe.mergeObjectAsync(n,s):Fe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof K?new Kn({keyType:e,valueType:n,typeName:B.ZodRecord,...H(r)}):new Kn({keyType:ot.create(),valueType:e,typeName:B.ZodRecord,...H(n)})}}class Ci extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.map)return j(r,{code:L.invalid_type,expected:$.map,received:r.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new nt(r,o,r.path,[u,"key"])),value:i._parse(new nt(r,c,r.path,[u,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),o.set(u.value,f.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),o.set(u.value,f.value)}return{status:n.value,value:o}}}}Ci.create=(t,e,n)=>new Ci({valueType:e,keyType:t,typeName:B.ZodMap,...H(n)});class mn extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.set)return j(r,{code:L.invalid_type,expected:$.set,received:r.parsedType}),U;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:L.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:L.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return U;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}const o=[...r.data.values()].map((c,u)=>i._parse(new nt(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,n){return new mn({...this._def,minSize:{value:e,message:P.toString(n)}})}max(e,n){return new mn({...this._def,maxSize:{value:e,message:P.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}mn.create=(t,e)=>new mn({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class ns extends K{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})}}ns.create=(t,e)=>new ns({getter:t,typeName:B.ZodLazy,...H(e)});class Zn extends K{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return j(n,{received:n.data,code:L.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Zn.create=(t,e)=>new Zn({value:t,typeName:B.ZodLiteral,...H(e)});function io(t,e){return new Nt({values:t,typeName:B.ZodEnum,...H(e)})}class Nt extends K{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return j(n,{expected:J.joinValues(r),received:n.parsedType,code:L.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return j(n,{received:n.data,code:L.invalid_enum_value,options:r}),U}return We(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 Nt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Nt.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}Nt.create=io;class rs extends K{_parse(e){const n=J.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.string&&r.parsedType!==$.number){const s=J.objectValues(n);return j(r,{expected:J.joinValues(s),received:r.parsedType,code:L.invalid_type}),U}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=J.objectValues(n);return j(r,{received:r.data,code:L.invalid_enum_value,options:s}),U}return We(e.data)}get enum(){return this._def.values}}rs.create=(t,e)=>new rs({values:t,typeName:B.ZodNativeEnum,...H(e)});class Jn extends K{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.promise&&n.common.async===!1)return j(n,{code:L.invalid_type,expected:$.promise,received:n.parsedType}),U;const r=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return We(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Jn.create=(t,e)=>new Jn({type:t,typeName:B.ZodPromise,...H(e)});class Lt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?U:c.status==="dirty"||n.value==="dirty"?on(c.value):c});{if(n.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?U:o.status==="dirty"||n.value==="dirty"?on(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?U:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Kt(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Kt(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:n.value,value:o})):U);J.assertNever(s)}}Lt.create=(t,e,n)=>new Lt({schema:t,typeName:B.ZodEffects,effect:e,...H(n)});Lt.createWithPreprocess=(t,e,n)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(n)});class ut extends K{_parse(e){return this._getType(e)===$.undefined?We(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:B.ZodOptional,...H(e)});class Dt extends K{_parse(e){return this._getType(e)===$.null?We(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Dt.create=(t,e)=>new Dt({innerType:t,typeName:B.ZodNullable,...H(e)});class Qn extends K{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===$.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Qn.create=(t,e)=>new Qn({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class Yn extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return zn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new dt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new dt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Yn.create=(t,e)=>new Yn({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class Ri extends K{_parse(e){if(this._getType(e)!==$.nan){const r=this._getOrReturnCtx(e);return j(r,{code:L.invalid_type,expected:$.nan,received:r.parsedType}),U}return{status:"valid",value:e.data}}}Ri.create=t=>new Ri({typeName:B.ZodNaN,...H(t)});class ao extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Cs extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?U:i.status==="dirty"?(n.dirty(),on(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?U:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new Cs({in:e,out:n,typeName:B.ZodPipeline})}}class Xn extends K{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Kt(s)&&(s.value=Object.freeze(s.value)),s);return zn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Xn.create=(t,e)=>new Xn({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(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"})(B||(B={}));const Ot=ot.create,Ti=Zt.create,Rs=Yr.create,zd=Wn.create,gn=es.create;vt.create;const Vd=et.create,ct=fe.create,Ts=Hn.create,Wd=Os.create;Gn.create;Tt.create;const yn=Kn.create,In=Zn.create,er=Nt.create;Jn.create;ut.create;Dt.create;const Hd=["get","list","create","update","delete"],Gd=ct({uid:Ot(),token:yn(gn()).optional()}),Kd=ct({function:er(["get","exists"]).describe("Firestore function to mock"),path:Ot().describe('Document path, e.g. "users/alice"'),result:Ts([yn(gn()),Rs()]).describe("Document data for get, boolean for exists")}),Zd=Wd("kind",[ct({kind:In("create")}),ct({kind:In("set"),merge:Rs()}),ct({kind:In("update")}),ct({kind:In("delete")})]),Jd=ct({limit:Ti().optional(),offset:Ti().optional(),orderBy:Ot().optional()});ct({description:Ot().describe("Human-readable description of what this test verifies"),expectation:er(["ALLOW","DENY"]).describe("Expected outcome"),method:er(Hd).describe("Firestore method to test"),path:Ot().describe('Document path, e.g. "users/alice"'),auth:Ts([Gd,zd()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:yn(gn()).optional().describe("request.resource.data for write operations"),resource:yn(gn()).optional().describe("Existing document data (resource.data)"),functionMocks:Vd(Kd).optional().describe("Mock get()/exists() calls in rules"),query:Jd.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Ot().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:Zd.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Ft(t){if(t.decision==="UNSUPPORTED")return;const n=t.decision==="ALLOW";let r="deny",s;if(n)r="allow",s=t.trace.find(T=>T.verdict==="ALLOW");else if(r="deny",s=t.trace.find(R=>R.verdict==="DENY"?!0:R.verdict==="ERROR"),s===void 0){const R=t.trace.length;R>0&&(s=t.trace[R-1])}if(s===void 0)return;const a={verdict:r};s.line!==void 0&&(a.line=s.line),s.col!==void 0&&(a.col=s.col,a.column=s.col),s.column!==void 0&&(a.col=s.column,a.column=s.column),s.file!==void 0&&(a.file=s.file),s.citation!==void 0&&(a.citation=s.citation),s.conditionText!==void 0&&(a.expression=s.conditionText),s.expressionTrace!==void 0&&(a.expressionTrace=s.expressionTrace);const v=a.line!==void 0,b=a.expression!==void 0,C=a.expressionTrace!==void 0;if(v||b||C)return a}function be(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const r=n.operations.join(","),s=`Rule #${n.ruleIndex} (${r})`;n.verdict==="ALLOW"?e.push(`${s} → ALLOW`):n.verdict==="DENY"?e.push(`${s} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${n.message??""}`):e.push(`${s} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}ct({function:er(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Ot().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Ts([yn(gn()),Rs()]).describe("Document fields for get, boolean for exists")});function Qd(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const Yd={name:"date-to-timestamp",convert(t){return t instanceof Date?_e.fromMillis(t.getTime()):He}},Xd={name:"server-timestamp-sentinel",convert(t,e){return Qd(t)?e.serverTime instanceof _e?e.serverTime:_e.fromMillis(Date.now()):He}};function eh(t){if(t===null||typeof t!="object"||t instanceof _e)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const th={name:"user-timestamp-to-rules-timestamp",convert(t){return eh(t)?new _e(t.seconds,t.nanoseconds):He}};function Ni(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function ss(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Li(t){if(typeof t!="object"||t===null||ss(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 Qe(t,e){if(Object.is(t,e))return!0;const n=Li(t),r=Li(e);if(n!==void 0||r!==void 0){if(n===void 0||r===void 0||n.kind!==r.kind)return!1;switch(n.kind){case"timestamp":return r.kind==="timestamp"&&n.seconds===r.seconds&&n.nanoseconds===r.nanoseconds;case"bytes":return r.kind==="bytes"&&n.values.length===r.values.length&&n.values.every((a,o)=>a===r.values[o]);case"vector":return r.kind==="vector"&&n.values.length===r.values.length&&n.values.every((a,o)=>a===r.values[o]);case"geo-point":return r.kind==="geo-point"&&n.latitude===r.latitude&&n.longitude===r.longitude;case"reference":return r.kind==="reference"&&n.path===r.path}}if(Ni(t))return t.isEqual(e);if(Ni(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((a,o)=>Qe(a,e[o]));if(!ss(t)||!ss(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Qe(t[a],e[a]))}function nh(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function rh(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function sh(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function ih(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Ns(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const n of t.fieldPath.split(".")){const r=/^([^\[]*)/.exec(n),s=r?r[1]:n;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(n))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const ah={name:"increment-sentinel",convert(t,e){if(!nh(t))return He;const n=Ns(e);return(typeof n=="number"?n:0)+t.value}},oh={name:"array-union-sentinel",convert(t,e){if(!rh(t))return He;const n=Ns(e),r=Array.isArray(n)?n.slice():[];for(const s of t.values)r.some(a=>Qe(a,s))||r.push(s);return r}},ch={name:"array-remove-sentinel",convert(t,e){if(!sh(t))return He;const n=Ns(e);return Array.isArray(n)?n.filter(r=>!t.values.some(s=>Qe(r,s))):[]}},uh={name:"delete-field-sentinel",convert(t){return ih(t)?tt:He}},Di=Symbol.for("pyric.firestore.query-value-registry"),Fi=globalThis,vn=Fi[Di]??(Fi[Di]=new WeakMap),Mi=Symbol.for("pyric.firestore.query-value-execution-registry"),ji=globalThis,tr=ji[Mi]??(ji[Mi]=new WeakMap),$i=Symbol.for("pyric.firestore.query-value-owner-registry"),Pi=globalThis,nr=Pi[$i]??(Pi[$i]=new WeakMap);function Ls(t,e,n=()=>t){vn.set(t,e),tr.set(t,n)}function lh(t){return vn.get(t)}function hp(t){return nr.get(t)}function fp(t){return tr.get(t)?.()??t}function pp(t,e){const n=vn.get(t),r=tr.get(t);n!==void 0&&vn.set(e,n),r!==void 0&&tr.set(e,r);const s=nr.get(t);s!==void 0&&nr.set(e,s)}const is=Symbol.for("pyric.firestore.reference-query-value");class dh{path;[is]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&is in e&&e.path===this.path}}function hh(t){const e=vn.get(t);if(typeof e!="object"||e===null||!(is in e))return;const n=e.path;return typeof n=="string"?n:void 0}function mp(t,e,n,r=t){Ls(t,new dh(e),()=>r),nr.set(t,n)}function fh(t){if(t===null||typeof t!="object"||t instanceof Rt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const ph={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=hh(t);if(e!==void 0)return new Rt(e)}return fh(t)?new Rt(t.path):He}};function mh(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function gh(t){if(t===null||typeof t!="object"||t instanceof Xt)return null;const e=t;return mh(e._values)&&typeof e.toArray=="function"?e._values:null}const yh={name:"vector-value",convert(t){const e=gh(t);return e===null?He:new Xt(e)}};function vh(t){if(t===null||typeof t!="object"||t instanceof Ie)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function bh(t){if(t===null||typeof t!="object"||t instanceof lt)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const wh={name:"fb-bytes-to-rules-bytes",convert(t){return vh(t)?new Ie(t.toUint8Array()):He}},Sh={name:"fb-geopoint-to-rules-latlng",convert(t){return bh(t)?new lt(t.latitude,t.longitude):He}},He=Symbol("value-resolver:KEEP"),tt=Symbol("value-resolver:DELETE_MARKER"),as=[];function Ge(t){as.some(e=>e.name===t.name)||as.push(t)}function Ze(t,e){const n={};for(const[r,s]of Object.entries(t))n[r]=os(s,{...e,fieldPath:r});return n}function os(t,e){for(const n of as){const r=n.convert(t,e);if(r!==He)return r}if(Array.isArray(t))return t.map((n,r)=>os(n,{...e,fieldPath:`${e.fieldPath}[${r}]`}));if(Pt(t)){const n={};for(const[r,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${r}`:r;n[r]=os(s,{...e,fieldPath:i})}return n}return t}function Pt(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xt(t){const e={},n=[];for(const[r,s]of Object.entries(t)){if(s===tt){n.push(r);continue}e[r]=rr(s)}return{writes:e,deletedKeys:n}}function rr(t){if(t!==tt){if(Array.isArray(t))return t.filter(e=>e!==tt).map(rr);if(Pt(t)){const e={};for(const[n,r]of Object.entries(t))r!==tt&&(e[n]=rr(r));return e}return t}}function _h(){Ge(Yd),Ge(Xd),Ge(th),Ge(ah),Ge(oh),Ge(ch),Ge(uh),Ge(ph),Ge(yh),Ge(wh),Ge(Sh)}function oo(t){return t.split(".")}const Ah=new Set(["__proto__","prototype","constructor"]);function qi(t){if(Ah.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 Ds(t){const e={};for(const[n,r]of Object.entries(t))e[n]=co(r);return e}function co(t){return Array.isArray(t)?t.map(co):Pt(t)?Ds(t):t}function uo(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){const a=e[i];qi(a);const o=Object.hasOwn(r,a)?r[a]:void 0;Pt(o)||(r[a]={}),r=r[a]}const s=e[e.length-1];qi(s),n===tt?delete r[s]:r[s]=rr(n)}function Ui(t,e){const n=Ds(t);for(const[r,s]of Object.entries(e)){if(s!==tt&&sr(s))throw new lo;uo(n,oo(r),s)}return n}class lo extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function sr(t){return t===tt?!0:Array.isArray(t)?t.some(sr):Pt(t)?Object.values(t).some(sr):!1}function Ih(t){for(const e of Object.values(t))if(e!==tt&&sr(e))throw new lo}function cs(t,e,n){const r=Ds(t),s=[];if(n!==void 0)for(const i of n){const a=oo(i),o=Eh(e,a);o!==ho&&s.push({segments:a,value:o})}else fo(e,[],s);for(const{segments:i,value:a}of s)uo(r,i,a);return r}const ho=Symbol("field-merge:ABSENT");function Eh(t,e){let n=t;for(const r of e){if(!Pt(n)||!Object.hasOwn(n,r))return ho;n=n[r]}return n}function fo(t,e,n){const r=Object.keys(t);if(r.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const s of r){const i=t[s],a=[...e,s];Pt(i)&&i!==tt?fo(i,a,n):n.push({segments:a,value:i})}}function xh(t,e){const n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}class Or{documents;versions=new Map;nextVersion=1;constructor(e={},n){this.documents=n??new Map;for(const[r,s]of Object.entries(e)){const i=Ze({...s},{path:r,method:"seed",prior:null}),{writes:a}=xt(i);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+"/",s=n.projection?c=>xh(c,n.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(r!==""&&!c.startsWith(r))continue;if(!n.directOnly){i.push({path:c,data:s(u)});continue}const f=c.slice(r.length),l=f.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(f);else if(n.phantoms){const p=f.slice(0,l);p.length>0&&!o.includes(p)&&o.push(p)}}if(n.directOnly&&n.phantoms)for(const c of o)a.has(c)||i.push({path:r+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const r of this.documents.keys()){const s=r.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),n.push(s)))}return n}listSubcollections(e){const n=e.endsWith("/")?e:e+"/",r=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(n))continue;const o=i.slice(n.length).split("/",1)[0];o.length!==0&&(r.has(o)||(r.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[n,r]of this.documents)e[n]={...r};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 s=Ze({...n},{path:e,method:"create",prior:null});r=xt(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,r),this.bumpVersion(e),{success:!0}}update(e,n){const r=this.documents.get(e);if(!r)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=Ze({...n},{path:e,method:"update",prior:r});s=Ui(r,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...r}}}setMerge(e,n,r){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=Ze({...n},{path:e,method:"set",prior:s}),a=cs(s??{},i,r);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,n){const r=this.documents.has(e)?{...this.documents.get(e)}:null,s=Ze({...n},{path:e,method:"set",prior:r}),{writes:i}=xt(s);return this.documents.set(e,i),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){const n=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&n.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||n.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(n.length>0)return{success:!1,errors:n};const r=new Map;for(const s of e)r.has(s.path)||r.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e){switch(s.method){case"create":{const i=Ze({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=xt(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=Ze({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,Ui(i,a));break}case"set":{const i=r.get(s.path)??null,a=Ze({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=xt(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:r}}restore(e){const n=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[r,s]of Object.entries(e))this.documents.set(r,{...s});for(const r of n)this.bumpVersion(r)}restorePaths(e){for(const[n,r]of Object.entries(e))r===null?this.documents.delete(n):this.documents.set(n,{...r}),this.bumpVersion(n)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class kh{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,r]of this.overlay)e.has(n)||(yield[n,r])}}class Oh{events=[];nextId=1;undoneEvents=[];append(e,n=!1){const r={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(r),n||(this.undoneEvents=[]),r}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(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Ch(t){return new Date(t.toMillis()).toISOString()}class bn extends Error{method;path;debugMessages;constructor(e,n,r,s){super(e),this.method=n,this.path=r,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function wn(t,e,n){const r=n.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=r?` Reason(s): ${r}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function Rh(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const Th=`rules_version = '2';
|
|
496
|
+
service cloud.firestore {
|
|
497
|
+
match /databases/{database}/documents {
|
|
498
|
+
match /{document=**} {
|
|
499
|
+
allow read, write: if true;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
`;class It{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 r=n(...e);this.swallowAsyncRejections&&r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Nh{denial=new It;request=new It(!0);write=new It(!0);delivery=new It;suppressed=new It;lifecycle=new It;snapshotError=new It;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class Lh{currentTrigger;run(e,n){const r=this.currentTrigger;this.currentTrigger=e;try{return n()}finally{this.currentTrigger=r}}current(){return this.currentTrigger}}class ir extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Bi=Symbol.for("pyric.firestore.activity-value-registry"),zi=globalThis,po=zi[Bi]??(zi[Bi]=new WeakMap);function mo(){let t=2166136261,e=2654435769,n=2246822507,r=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),n=Math.imul(n^i,3266489909),r=Math.imul(r^i,668265263)};return{update:i=>{if(typeof i=="string")for(let a=0;a<i.length;a+=1){const o=i.charCodeAt(a);s(o&255),s(o>>>8)}else for(const a of i)s(a)},finish:()=>[t,e,n,r].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Fs(...t){const e=mo();for(const n of t)e.update(n);return e.finish()}function gp(t){return{type:"string-digest",length:t.length,digest:Fs("string\0",t)}}function Dh(t,...e){return{type:`${t}-digest`,digest:Fs(`${t}\0`,...e)}}function yp(t){return{type:"bytes-digest",length:t.byteLength,digest:Fs("bytes\0",t)}}function Vi(t){const e=mo(),n=(...s)=>{for(const i of s)e.update(i)},r=s=>{if(s===null){n("null;");return}switch(typeof s){case"string":n(`s${s.length}:`,s,";");return;case"number":n(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":n(s?"b1;":"b0;");return;case"undefined":n("u;");return;case"bigint":n(`i${s.toString()};`);return;case"object":break;default:n(`x${typeof s};`);return}if(Array.isArray(s)){n(`a${s.length}[`);for(const o of s)r(o);n("];");return}const i=s,a=Object.keys(i).sort();n(`o${a.length}{`);for(const o of a)n(`k${o.length}:`,o,"="),r(i[o]);n("};")};return r(t),{type:"wire-value-digest",digest:e.finish()}}function us(t,e){po.set(t,e)}function vp(t){return po.get(t)}class bp{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class Wt{seconds;nanoseconds;constructor(e,n){this.seconds=e,this.nanoseconds=n,us(this,Dh("timestamp",String(e),"\0",String(n))),Ls(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:n}),()=>new Wt(e,n))}static now(){return Wt.fromMillis(Date.now())}static fromDate(e){return Wt.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),r=Math.floor((e-n*1e3)*1e6);return new Wt(n,r)}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 n=this.seconds- -62135596800,r=String(n).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${r}.${s}`}}function ls(t){return t instanceof _e?new Wt(t.seconds,t.nanos):t instanceof Ie||t instanceof lt||t instanceof Xt?t:Array.isArray(t)?t.map(ls):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,ls(n)])):t}function go(t){return ls(t)}const Fh=/[*~/[\]]/,Mh=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ar{_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,r)=>{if(typeof n!="string")throw new Error(`Element at index ${r} is not a valid string.`);if(n.length===0)throw new Error(`Element at index ${r} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new ar("__name__");static documentId(){return ar.DOCUMENT_ID}isEqual(e){const n=yo(e),r=this._internalPath.segments;return r.length===n.length&&r.every((s,i)=>s===n[i])}toString(){return this._internalPath.segments.map(e=>Mh.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function tn(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function yo(t){if(t instanceof ar)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(n=>typeof n=="string"))return[...e.segments]}if(t===void 0)throw tn("The path cannot be omitted.");if(typeof t!="string")throw tn("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw tn('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw tn('Paths must not start or end with ".".');if(t.length===0||Fh.test(t))throw tn(`Paths can't be empty and must not contain
|
|
504
|
+
"*~/[]".`);return t.split(".")}function jh(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function vo(t,e){const n=yo(e);let r=t;for(const s of n){if(!jh(r))return;r=Object.prototype.hasOwnProperty.call(r,s)?r[s]:void 0}return r}const Jt=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Wi=Object.freeze({hasPendingWrites:!0,fromCache:!1});function bo(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function nn(t,e,n=Jt){const r={id:bo(t),path:t},s=e!==null,i=s?go(e):void 0;return{id:r.id,ref:r,metadata:n,exists:()=>s,data:()=>i,get:a=>vo(i,a)}}function wo(t,e,n=Jt){const r={id:bo(t),path:t},s=go(e);return{id:r.id,ref:r,metadata:n,exists:()=>!0,data:()=>s,get:i=>vo(s,i)}}function rn(t,e,n,r,s=Jt){const i=e.map(u=>wo(u.path,u.data,s)),a=r?$h(r,e,i,s):i.map((u,f)=>({type:"added",doc:u,oldIndex:-1,newIndex:f}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const f of i)u(f)},docChanges(u){const f=!!u?.includeMetadataChanges;if(f&&n.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return f?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function $h(t,e,n,r=Jt){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:wo(c.path,c.data,r),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:n[o],oldIndex:-1,newIndex:o});else{const f=t[u].data;JSON.stringify(f)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:n[o],oldIndex:u,newIndex:o})}}return a}function Hi(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function Ph(t,e){const n=`${e}/`;for(const r of t){if(!r.startsWith(n))continue;const s=r.slice(n.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let Cr=0;function ln(){return Cr=Cr+1>>>0,`req-${Cr.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function qh(t,e){const n=e==="allow";let r;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(n&&i[3]==="ALLOW")return a;r=a}return r}function fr(t){const e={kind:"request",id:ln(),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.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const n=qh(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}class Uh{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,n,r){this.events=e,this.triggerScope=n,this.host=r}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const n={kind:"snapshot_delivery",id:ln().replace(/^req-/,"snd-"),at:Date.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}:{}};this.events.delivery.emit(n)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const n={kind:"snapshot_suppressed",id:ln().replace(/^req-/,"sup-"),at:Date.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:ln().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(n)}emitSnapshotError(e,n,r){this.events.snapshotError.emit(e,n,r)}addSnapshotListener(e,n,r={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),f={id:u,target:e,callback:n,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:r,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,f),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(f)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=nn(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const r=rn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(s=>({path:s.path,data:s.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){if(e.size===0||this.snapshotListeners.size===0)return;const n=this.triggerScope.current(),r=Array.from(this.snapshotListeners.values());for(const s of r)this.scheduleTriggeredDelivery(n,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,n){if(e.target.kind!=="doc"||!n.has(e.target.path))return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.currentDocData??null;if(Hi(s,r.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 i=e.target.path,a=nn(i,r.data,Wi);e.currentSnapshot=a,e.currentDocData=r.data;const o=s!==null,c=r.data!==null,u=!o&&c?1:0,f=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:f,size:c?1:0,sample:{docs:[{path:i,data:r.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,r.data)}scheduleDocMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=nn(n,r,Jt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r!==null?1:0,sample:{docs:[{path:n,data:r}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query"||!Ph(n,e.target.collection))return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.target.collection,i=e.currentDocs??[],a=rn({path:s},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Wi),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,r.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=r.docs;let c=0,u=0,f=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&f++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:f,size:r.docs.length,sample:{docs:r.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,r.docs)}scheduleQueryMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=rn({path:n},r,{excludesMetadataChanges:!1},r,Jt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r.length,sample:{docs:r.map(i=>({path:i.path,data:i.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 r=Array.from(this.snapshotListeners.values());for(const s of r)s.followsCurrentUser&&s.authScope===n&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const i=nn(e.target.path,n.data);e.currentSnapshot=i,e.currentDocData=n.data;try{e.callback(i)}catch{}return}const r=e.currentDocData??null;if(Hi(r,n.data))return;const s=nn(e.target.path,n.data);e.currentSnapshot=s,e.currentDocData=n.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const a=rn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}return}const r=e.currentDocs??[],s=rn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},r);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class Bh{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(o=>o.path):e.path?[e.path]:[],r=!!e.snapshot,s=r?void 0:this.host.capturePriors(n),i=r?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class zh{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:Es(this.currentSource)}),this.parsedCache.ast}}function he(t,e,n){const r={code:t,message:e};return n!==void 0&&(n.request!==void 0&&(r.request=n.request),n.resource!==void 0&&(r.resource=n.resource),n.remediation!==void 0&&(r.remediation=n.remediation),n.query!==void 0&&(r.query=n.query),n.rule!==void 0&&(r.rule=n.rule)),r}function pr(t,e,n){const r=t.get(e.path),s=e.method==="set"?r!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&r&&e.data){const{writes:a,deletedKeys:o}=xt(e.data),c={...r,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=xt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:r??void 0,...n?{requestTime:Ch(n)}:{}}}function So(t,e,n,r,s,i){if(s){const a=r.map(o=>Rh(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return n.simulate(e.source,r,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class Vh{events;rules;simulator;host;eventLog;constructor(e,n,r,s,i){this.events=e,this.rules=n,this.simulator=r,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(fr(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:n,path:r,auth:s,bypassRules:i}=e;let a;i===!0&&(a={admin:!0});const c=_e.fromMillis(Date.now()),u=pr(this.state,e,c),f=Date.now(),l=performance.now(),p=So(this.state,this.rules,this.simulator,[u],i),y=performance.now()-l;let v=null;if(s!==void 0&&s!==null&&(v={uid:s.uid}),p.success===!0===!1){const d=this.eventLog.append({type:"single",method:n,path:r,auth:v,allowed:!1,debugMessages:[`Simulation error: ${p.error.message}`]}),g={at:f,evalMs:y,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${p.error.message}`],origin:"user"};return a!==void 0&&(g.detail=a),this.emitRequest(g),{allowed:!1,debugMessages:[p.error.message],event:d}}const R=p.data.results[0];if(R.state==="UNSUPPORTED"){const d={at:f,evalMs:y,method:n,path:r,auth:s,result:"unsupported",debugMessages:be(R),origin:"user"};throw a!==void 0&&(d.detail=a),this.emitRequest(d),new bn(wn(n,r,be(R)),n,r,be(R))}const D=R.state==="PASSED";let q;D&&(n==="get"?q=this.state.get(r):q=this.state.list(r));const S=this.eventLog.append({type:"single",method:n,path:r,auth:v,allowed:D,debugMessages:be(R)}),x={allowed:D,debugMessages:be(R),event:S};D&&(x.data=q);const A=Ft(R);if(D===!1){const g={request:{method:n,path:r,auth:s}};if(n==="get"){const k=this.state.get(r),O=k!==null;g.resource={data:k,exists:O}}A!==void 0&&(g.rule=A),x.error=he("permission-denied",`${n} ${r} denied by rules`,g),this.emitDenial(x.error)}let w="deny";D&&(w="allow");const I={at:f,evalMs:y,method:n,path:r,auth:s,result:w,debugMessages:be(R),evaluatedRule:A,origin:"user"};if(n==="get"){const d=this.state.get(r),g=d!==null;I.resourceBefore={data:d,exists:g}}return a!==void 0&&(I.detail=a),this.emitRequest(I),x}}function _o(t){const e=new Map,n=new Set;for(const r of t)e.has(r.name)&&n.add(r.name),e.set(r.name,r);return{functions:e,ambiguousNames:n}}function Ao(t,e,n,r=Wh){const s=new Set;return{pathInvariant:!Cn(t,e,n,r,new Set,new Set,s),requiredFunctions:s}}function Cn(t,e,n,r,s,i,a){const o=c=>Cn(c,e,n,r,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Gi.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"&&Gi.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(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||r.has(t.name))return!0;const c=n.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),f=new Set(c.parameters);for(const l of c.lets){if(Cn(l.value,e,n,r,f,u,a))return!0;f.add(l.name)}return Cn(c.body,e,n,r,f,u,a)}}}const Gi=new Set(["auth","method","query","time"]),Wh=new Set;function Hh(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],n=new Set,r=t.service.match.children.flatMap(i=>{const a=Gh(i,e,n);return a?[a]:[]});if(r.length===0)return null;const s=i=>i?.filter(a=>n.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:r}}}}function Gh(t,e,n){const r=t.path.segments[0];if(t.path.segments.length!==1||r?.type!=="recursive")return null;const s=_o([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=Ao(a.condition,new Set([r.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)n.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>n.has(a.name)),allows:i,children:[]}}function Kh(t,e,n,r,s){if(t!==null===!1)return{kind:"no-rule"};const a=e.split("/").filter(b=>b.length>0),o=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const b of t.service.match.children)c.push(...Un(b,a,o));if(c.length===0)return{kind:"no-rule"};const f=[],l=new Set;let p=0;for(const b of c){const C=_o(b.functions),T=C.functions;for(const R of b.block.allows){if(R.operations.some(A=>A==="list"?!0:A==="read")===!1)continue;if(p++,Ao(R.condition,new Set(b.candidateVariables),T,C.ambiguousNames).pathInvariant===!0===!1){f.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:R});continue}const S=ld(R.condition,r,T,n?.uid);S.provable===!0?l.add(R):f.push({reason:S.reason,residual:S.residual,rule:R})}}if(p===0)return{kind:"no-rule"};if(l.size===0){const b=f[0];let C="list rule depends on per-document data the query cannot guarantee",T={missing:[],mismatched:[]},R;if(b!==void 0&&(C=b.reason,T=b.residual,b.rule!==void 0)){const x=b.rule,A=ye(x.condition);if(R={verdict:"deny",expression:A},x.loc!==void 0){const I=x.loc;let E="";s!==void 0&&(E=s);const d=Ya(E,I.line,I.col,I.file,A);d!==void 0?(R.line=d.line,R.col=d.col,R.column=d.col,R.file=d.file,R.citation=d.citation,d.expression!==void 0&&(R.expression=d.expression)):(R.line=I.line,R.col=I.col,R.column=I.col,I.file!==void 0?(R.file=I.file,R.citation=`${I.file}:${I.line}:${I.col}`):(R.file="firestore.rules",R.citation=`firestore.rules:${I.line}:${I.col}`))}}const D={kind:"unprovable",reason:C,residual:T};return R!==void 0&&(D.rule=R),D}return{kind:"provable",evaluationAst:Zh(t,l),syntheticResource:Jh(r)}}function Zh(t,e){const n=r=>({...r,allows:r.allows.filter(s=>e.has(s)),children:r.children.map(n)});return{...t,service:{...t.service,match:n(t.service.match)}}}function Jh(t){const e={};for(const n of t.where??[])n.op==="=="&&(e[n.field]=n.value);return e}function Qh(t){const e=[];for(const r of t.missing)r.fromAuthUid?e.push(` .where('${r.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(r.expectedValue)}`):e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)})`);for(const r of t.mismatched)e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)}) // the query pins ${JSON.stringify(r.actualValue)}, but the rule requires ${JSON.stringify(r.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:
|
|
505
|
+
${e.join(`
|
|
506
|
+
`)}`}function Yh(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class Xh{events;rules;simulator;host;constructor(e,n,r,s){this.events=e,this.rules=n,this.simulator=r,this.host=s}authorize(e){const{path:n,auth:r,constraints:s,origin:i,triggeredBy:a}=e,o=Yh(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,f=e.timing?.requestTime??(e.bypassRules?void 0:_e.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:n,auth:r,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const p=this.rules.ast(),y=e.collectionGroup?Hh(p):p;if(e.collectionGroup&&!y){const w=`list ${n} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:n,auth:r,result:"deny",debugMessages:[w],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const I=he("permission-denied",w,{request:{method:"list",path:n,auth:r},query:s});return this.emitUserDenial(i,I),{allowed:!1,error:I}}const v=`${n}/__listPlaceholder__`,b=performance.now(),C=Kh(y,v,r,s,this.rules.source);if(C.kind==="unprovable"){const w=`list ${n} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${C.reason}`,I=Qh(C.residual),E={at:l,evalMs:performance.now()-b,method:"list",path:n,auth:r,result:"deny",debugMessages:[w],origin:i};u!==void 0&&(E.detail=u),a!==void 0&&(E.triggeredBy=a),this.emitRequest(E);const g={request:{method:"list",path:n,auth:r},query:s};I!==void 0&&I!==""&&(g.remediation=I),C.rule!==void 0&&(g.rule=C.rule);const k=he("permission-denied",w,g);return this.emitUserDenial(i,k),{allowed:!1,error:k}}const R=C.kind==="provable"?si(C.evaluationAst):e.collectionGroup?si(y):this.rules.source,_=pr(this.host.state,{method:"list",path:v,auth:r},f);this.applyProof(_,C,s);const D=this.simulator.simulate(R,[_],{getDoc:w=>this.host.state.get(w)}),q=performance.now()-b;if(!D.success)return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:[`Simulation error: ${D.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:he("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:r}})};const S=D.data.results[0],x=be(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"unsupported",debugMessages:x,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new bn(wn("list",n,x),"list",n,x);if(S.state!=="PASSED"){const w=Ft(S),I={at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:x,evaluatedRule:w,origin:i};u!==void 0&&(I.detail=u),a!==void 0&&(I.triggeredBy=a),this.emitRequest(I);const d={request:{method:"list",path:n,auth:r}};w!==void 0&&(d.rule=w);const m=he("permission-denied",`list ${n} denied by rules`,d);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"allow",debugMessages:x,evaluatedRule:Ft(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,n,r){n.kind==="provable"&&(e.resource=n.syntheticResource),(r.limit!=null||r.offset!=null||r.orderBy!=null)&&(e.query={...r.limit!=null?{limit:r.limit}:{},...r.offset!=null?{offset:r.offset}:{},...r.orderBy!=null?{orderBy:r.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(fr(e))}emitUserDenial(e,n){e==="user"&&this.events.denial.emit(n)}}function ef(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?Ki(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),Ki(r,s,n));return r}function Ki(t,e,n){let r=0,s=t.length;for(;r<s;){const i=r+s>>1;n(e,t[i])<0?s=i:r=i+1}t.splice(r,0,e)}function tf(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function nf(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function rf(t){return t.data instanceof Uint8Array}function sf(t){return typeof t.path=="string"}function or(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 tf(n)?3:rf(n)?5:nf(n)?7:sf(n)?6:9}return 9}function Zi(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function af(t,e){const n=Number.isNaN(t),r=Number.isNaN(e);return n&&r?0:n?-1:r?1:t<e?-1:t>e?1:0}function Ji(t,e){return t<e?-1:t>e?1:0}function bt(t,e){const n=or(t),r=or(e);if(n!==r)return n<r?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return af(Number(t),Number(e));case 3:{const[s,i]=Zi(t),[a,o]=Zi(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Ji(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Ji(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=bt(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const f=bt(s[a[u]],i[o[u]]);if(f!==0)return f}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function of(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 ir({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Qi(t){const e=u=>{const f=u.kind;if(f==="where"){const p=u.field,y=u.op,v=u.value;return Object.freeze({kind:f,field:p,op:y,value:v})}if(f!=="and"&&f!=="or")throw new ir({code:"invalid-argument",message:`Unknown query filter kind: ${String(f)}`});const l=u.filters;return Object.freeze({kind:f,filters:Object.freeze(Array.from(l,e))})},n=u=>{if(u===void 0)return;const f=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(f)),inclusive:l,fromSnapshot:p})},r=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(r,e)),orders:Object.freeze(Array.from(s,u=>{const f=u.field,l=u.direction;return Object.freeze({field:f,direction:l})})),limitCount:i,limitFromEnd:a,start:n(o),end:n(c)})}function Yi(t){const e=[],n=r=>{if(r.kind==="where"){if(r.field===gt)return;const s=r.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:r.field,op:r.op,value:s}));return}r.kind==="and"&&r.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 cf(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const n=[];for(const[r,s]of Object.entries(t.snapshot())){const i=r.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&n.push({path:r,data:s})}return n}const gt="__name__",uf=new Set(["<","<=",">",">=","!=","not-in"]);function ds(t,e){return e===gt?{path:t.path}:t.data[e]}function Ms(t){return t.kind==="where"?uf.has(t.op)?[t.field]:[]:t.filters.flatMap(Ms)}function lf(t){return Ms(t).length>0}function mr(t,e){return or(t)===or(e)}function df(t,e){return mr(t,e)&&bt(t,e)<0}function hf(t,e){return mr(t,e)&&bt(t,e)<=0}function ff(t,e){return mr(t,e)&&bt(t,e)>0}function pf(t,e){return mr(t,e)&&bt(t,e)>=0}function mf(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Qe(t,n);case"!=":return r&&t!==null&&!Qe(t,n);case"<":return r&&df(t,n);case"<=":return r&&hf(t,n);case">":return r&&ff(t,n);case">=":return r&&pf(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Qe(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Qe(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Qe(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(i=>Qe(i,s)))}}function gf(t,e){if(e===gt){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function Io(t){if(Array.isArray(t))return t.map(Io);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 hs(t,e){if(e.kind==="where"){const n=gf(t,e.field),r=e.field===gt?Io(e.value):e.value;return mf(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>hs(t,n)):e.filters.some(n=>hs(t,n))}function yf(t,e){return t.filter(n=>e.every(r=>hs(n,r)))}function Xi(t,e,n){for(let r=0;r<e.length;r++){const s=bt(ds(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function vf(t,e,n,r){return t.filter(s=>{if(n){const i=Xi(s,n.values,e);if(n.inclusive?i<0:i<=0)return!1}if(r){const i=Xi(s,r.values,e);if(r.inclusive?i>0:i>=0)return!1}return!0})}function Eo(t,e){return t.filter(n=>e.every(r=>r.field===gt||n.data[r.field]!==void 0))}function xo(t){return(e,n)=>{for(const r of t){const s=bt(ds(e,r.field),ds(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function bf(t,e){return e.length===0?t:Eo(t,e).sort(xo(e))}function wf(t){const e=[...t.orders],n=new Set(e.map(s=>s.field)),r=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ms(s))i!==gt&&!n.has(i)&&(n.add(i),e.push({field:i,direction:r}));return n.has(gt)||e.push({field:gt,direction:r}),e}function Rr(t,e){let n=yf(t,[...e.filters]);const r=wf(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(lf);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return ef(Eo(n,r),e.limitCount,xo(r));if(s&&(n=bf(n,r)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ir({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=vf(n,r,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ir({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});n=n.slice(-e.limitCount)}else n=n.slice(0,e.limitCount);return n}class Sf{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,n,r,s,i,a){this.events=e,this.triggerScope=n,this.rules=r,this.simulator=s,this.host=i,this.operationReader=new Vh(e,r,s,i,a),this.listAuthorizer=new Xh(e,r,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(fr(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,n,r=!1){if(r){const _=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:_,exists:_!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:_}}const s=_e.fromMillis(Date.now()),i=pr(this.state,{method:"get",path:e,auth:n},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:_=>this.state.get(_)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,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:he("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const f=c.data.results[0];if(f.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:n,result:"unsupported",debugMessages:be(f),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new bn(wn("get",e,be(f)),"get",e,be(f));const l=f.state==="PASSED",p=this.state.get(e),y=Ft(f);let v="deny";l&&(v="allow");const b=p!==null,C={at:a,evalMs:u,method:"get",path:e,auth:n,result:v,debugMessages:be(f),evaluatedRule:y,origin:"listener",resourceBefore:{data:p,exists:b}},T=this.triggerScope.current();if(T!==void 0&&(C.triggeredBy=T),this.emitRequest(C),l===!1){const _={request:{method:"get",path:e,auth:n},resource:{data:p,exists:b}};return y!==void 0&&(_.rule=y),{allowed:!1,error:he("permission-denied",`get ${e} denied by rules`,_)}}return{allowed:!0,data:p}}silentReadCollection(e,n,r,s=!1){if(typeof r=="function")return{allowed:!1,error:he("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=r?Qi(r.execution):void 0,a=i?Yi(i):{},o={requestTime:_e.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const p=this.state.list(e).filter(b=>!b.phantom).map(b=>({path:b.path,data:b.data})),y=i?Rr(p,i):p,v=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,bypassRules:s,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return v.allowed?{allowed:!0,docs:y}:v}const u=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const f=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?Rr(f,i):f}}runQuery(e){const n=of(e.scope),r=Qi(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=cf(this.state,n),c=n.kind==="collection"?n.path:n.collectionId,u=Yi(r),f=this.listAuthorizer.authorize({path:c,collectionGroup:n.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return f.allowed?{allowed:!0,docs:Rr(o,r)}:f}}const ea="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ta=20;function _f(){const t=new Uint8Array(ta);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<ta;n++)e+=ea[t[n]%ea.length];return e}function ko(t,e=""){const n=[],r=new WeakSet;return s(t,e),n;function s(i,a){if(i==null||typeof i!="object"||r.has(i)||(r.add(i),lh(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,f)=>s(u,`${a}[${f}]`));return}const o=i,c=Af(o);if(c){n.push({field:a,kind:c});return}for(const[u,f]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(f,l)}}}function Af(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}_h();class If{host;rules;simulator;eventLog;events;triggerScope;constructor(e,n,r,s,i,a){this.host=e,this.rules=n,this.simulator=r,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(fr(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:ln().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const n={};for(const r of e){const s=this.state.get(r);n[r]=s?{...s}:null}return n}runSimulate(e,n,r){return So(this.state,this.rules,this.simulator,e,n,r)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,n,r){return n.has(e)?n.get(e)??null:r.exists(e)?r.get(e)??null:null}computeProjectedUpdate(e,n){return e===null?null:cs(e,n??{})}computeProjectedOverwrite(e,n){return cs(e??{},n??{})}buildBatchProjection(e){const n=new Map;for(const r of e){if(this.isReadOnlyMethod(r.method))continue;if(r.method==="delete"){n.set(r.path,null);continue}const s=this.resolvePriorDocumentState(r.path,n,this.state);if(r.method==="update"){const i=this.computeProjectedUpdate(s,r.data);n.set(r.path,i)}else{const i=this.computeProjectedOverwrite(s,r.data);n.set(r.path,i)}}return n}buildTestCase(e,n){return pr(this.state,e,n)}notify(e,n,r){this.triggerScope.run({method:e,path:n},()=>this.host.notifyListenersForPaths(r))}}class Oo{runtime;constructor(e){this.runtime=e}prepare(e,n){const r=_e.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ze({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:r}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=he("invalid-argument",c),f=n.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:n.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(n,a)?{resourceData:a.preData}:{},resourceBefore:{data:f,exists:f!==null},origin:n.origin,groupId:n.groupId,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:n,inputs:e,resolvedOps:s,serverTime:r}}evaluateAndApply(e){const{context:n,inputs:r,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=r[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:n.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const p=r[l],y=n.snapshot[p.path]??null,v=Date.now(),b=performance.now(),C=this.runtime.runSimulate([a[l]],n.bypassRules,o),T=performance.now()-b;if(!C.success){const x=he("invalid-argument",C.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[C.error.message],error:x,request:this.request(e,p,y,v,T,"deny",[`Simulation error: ${C.error.message}`])}),u=!1;continue}const R=C.data.results[0],_=be(R);if(R.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,v,T,"unsupported",_)),new bn(wn(p.ruleMethod,p.path,_),p.ruleMethod,p.path,_);const D=R.state==="PASSED";let q="deny";D&&(q="allow");const S={path:p.path,method:p.ruleMethod,allowed:D,debugMessages:_,request:this.request(e,p,y,v,T,q,_)};if(D===!1){const x=Ft(R),A=y!==null,w={request:{method:p.ruleMethod,path:p.path,auth:n.auth},resource:{data:y,exists:A}};this.includesRequestData(n,p)&&(w.request.resourceData=p.preData),x!==void 0&&(w.rule=x),S.error=he("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,w),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let f=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const p=l.errors?.[0];if(p!==void 0){const y=s[p.index];f=he(y?.method==="create"?"already-exists":"not-found",p.error);const v=c[p.index];v&&(v.allowed=!1,v.error=f)}}}return{...e,outcomes:c,allowed:u,structuralError:f}}emitAndNotify(e){const{context:n,inputs:r,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=r[a],u=e.allowed&&o.allowed,f=n.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:f,exists:f!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?ko(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:n.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:f,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:n.groupId,groupKind:n.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}})}}e.allowed&&this.runtime.notify(n.origin,r[0]?.path??"",new Set(r.map(a=>a.path)))}request(e,n,r,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:n.ruleMethod,path:n.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,n)?{resourceData:n.preData}:{},resourceBefore:{data:r,exists:r!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,n){return n.preData!==void 0&&(e.origin==="batch"||n.ruleMethod!=="delete")}}class Ef{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Oo(e)}batch(e,n,r){const s=this.runtime.capturePriors(e.map(p=>p.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(p=>({...p,ruleMethod:p.method,preData:p.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:n,bypassRules:r,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:p,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(p=>({path:p.path,allowed:p.allowed,debugMessages:p.debugMessages,...p.error?{error:p.error}:{}})),f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((p,y)=>({method:p.method,path:p.path,data:p.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(p=>p.error)?.error??he("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:f,...l?{error:l}:{}}}}const na="Firestore transactions require all reads to be executed before all writes.";class xf extends Error{simError;constructor(){super(na),this.name="ReadAfterWriteError",this.simError=he("failed-precondition",na)}}class ra extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class kf extends Error{simError=he("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class Of{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 r=n===null?null:structuredClone(n);return{path:e,exists:r!==null,data:()=>r===null?void 0:r}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n){this.queue({method:"set",path:e,data:n})}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){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new xf}}class Cf extends Error{path;secondMethod;constructor(e,n){super(`Queued ${n} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=n}}function Rf(t){const e=new Map;for(const n of t){const r=e.get(n.path);if(r===void 0){e.set(n.path,Tf(n));continue}if(r.method==="delete")throw new Cf(n.path,n.method);e.set(n.path,Nf(r,n))}return Array.from(e.values())}function Tf(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function Nf(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const n=Tr(e);return{method:"set",path:e.path,data:n}}case"update":{const n=Tr(e),s={...t.data??{},...n};return{method:t.method,path:e.path,data:s}}case"create":{const n=Tr(e),s={...t.data??{},...n};return{method:"create",path:e.path,data:s}}}}function Tr(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class Lf{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Oo(e)}transaction(e,n){return this.runAttempt(e,n,1)}runAttempt(e,n,r){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(f=>[f,this.runtime.state.version(f)])),o=f=>s[f]??null,c=new Of(o,f=>{const l=a.get(f);if(l!==void 0)return l;const p=this.runtime.state.version(f);return p<=i?p:-1});let u;try{u=e(c)}catch(f){throw this.logAbortedTransaction(c,n.auth,f),f}if(u!==null&&typeof u?.then=="function")return u.then(f=>{try{return this.commitTransaction(c,s,n,f)}catch(l){return this.retryOrThrow(l,e,n,r)}},f=>{throw this.logAbortedTransaction(c,n.auth,f),f});try{return this.commitTransaction(c,s,n,u)}catch(f){return this.retryOrThrow(f,e,n,r)}}retryOrThrow(e,n,r,s){if(!(e instanceof ra))throw e;const i=r.maxAttempts??5;if(s>=i)throw new kf;return this.runAttempt(n,r,s+1)}commitTransaction(e,n,r,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[_,D]of o)if(this.runtime.state.version(_)!==D)throw new ra;const c=r.auth;if(a.length===0){const _=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(D=>({path:D.path,data:D.data})),operations:[],snapshot:n,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:_}}let u;try{u=Rf(a)}catch(_){const D=_;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(q=>({path:q.path,data:q.data})),error:{name:D.name,message:D.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${D.message}`]}),_}const f=Object.fromEntries(u.map(_=>[_.path,n[_.path]??null])),l=u.map(_=>{const D=_.method==="set"?this.runtime.state.get(_.path)!==null?"update":"create":_.method;return{..._,ruleMethod:D,preData:_.data}}),p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:p,auth:c,bypassRules:r.bypassRules,provenance:r.provenance,snapshot:f});if(!("resolvedOps"in y)){const _=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(D=>({path:D.path,data:D.data})),operations:u.map(D=>({method:D.method,path:D.path,data:D.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map((D,q)=>({path:D.path,method:D.ruleMethod,allowed:!1,debugMessages:q===y.index?[y.message]:[],...q===y.index?{error:y.error}:{}})),returnValue:s,event:_,error:y.error}}const v=this.pipeline.evaluateAndApply(y),b=v.outcomes.map(_=>({path:_.path,method:_.method,allowed:_.allowed,debugMessages:_.debugMessages,..._.error?{error:_.error}:{}})),C=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:v.allowed,reads:i.map(_=>({path:_.path,data:_.data})),operations:v.resolvedOps.map((_,D)=>({method:_.method,path:_.path,data:_.data,allowed:b[D]?.allowed??!1})),snapshot:v.allowed?n:void 0,debugMessages:v.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let T;v.allowed||(T=v.structuralError??b.find(_=>_.error)?.error??he("permission-denied","Transaction denied"));const R={allowed:v.allowed,reads:[...i],writes:b,returnValue:s,event:C,...T?{error:T}:{}};return r.readOnly&&e.hadWrites()&&(R.readOnlyViolation=!0),R}logAbortedTransaction(e,n,r){const s=r,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:r.name,message:r.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${r.message}`]})}}class Df{runtime;batches;transactions;constructor(e,n,r,s,i,a){this.runtime=new If(e,n,r,s,i,a),this.batches=new Ef(this.runtime),this.transactions=new Lf(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,n,r,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(n,r??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(n,r??{});return i.success?null:he("already-exists",i.error??`Document '${n}' already exists`)}case"update":{const i=this.runtime.state.update(n,r??{});return i.success?null:he("not-found",i.error??`Document '${n}' does not exist`)}case"set":return this.runtime.state.set(n,r??{}),null;case"delete":return this.runtime.state.delete(n),null;default:return null}}execute(e){const{method:n,path:r,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,f=u?{admin:!0}:void 0,l=this.runtime.capturePriors([r]),p=o??_e.fromMillis(Date.now());let y;try{y=i&&Ze({...i},{path:r,method:n,prior:this.runtime.state.get(r),serverTime:p}),n==="update"&&y&&Ih(y)}catch(I){const E=I.message,h=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${E}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:n,path:r,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${E}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[E],event:h,error:he("invalid-argument",E)}}const v=this.runtime.buildTestCase({...e,data:y},p),b=Date.now(),C=performance.now(),T=this.runtime.runSimulate([v],u),R=performance.now()-C;if(!T.success){const I=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${T.error.message}`]});return this.runtime.emitRequest({at:b,evalMs:R,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${T.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[T.error.message],event:I,error:he("invalid-argument",T.error.message)}}const _=T.data.results[0];if(_.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:b,evalMs:R,method:n,path:r,auth:s,result:"unsupported",debugMessages:be(_),...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...f?{detail:f}:{}}),new bn(wn(n,r,be(_)),n,r,be(_));let D=_.state==="PASSED",q=null;D&&(q=this.applyWrite(n,r,y,c),q&&(D=!1));const S=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:y,allowed:D,priorDocs:D?l:void 0,debugMessages:be(_)}),x={allowed:D,debugMessages:be(_),event:S};if(D===!1){let I=!1;if(q!==void 0&&q!==null&&(I=!0),I)x.error=q;else{let h=null;const d=l[r];d!==void 0&&(h=d);let m=n;n==="set"&&(h!==null?m="update":m="create");const k=Ft(_),N={request:{method:m,path:r,auth:s},resource:{data:h,exists:h!==null}};i!==void 0&&(N.request.resourceData=i),k!==void 0&&(N.rule=k),x.error=he("permission-denied",`${n} ${r} denied by rules`,N),this.runtime.emitDenial(x.error)}}const A=l[r]??null,w=D?this.runtime.state.get(r):A;if(this.runtime.emitRequest({at:b,evalMs:R,method:n,path:r,auth:s,result:D?"allow":"deny",debugMessages:be(_),evaluatedRule:Ft(_),...i?{resourceData:i}:{},resourceBefore:{data:A,exists:A!==null},...n!=="delete"?{resourceAfter:{data:w,exists:w!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...f?{detail:f}:{}}),D){const I=i?ko(i):void 0,E=a&&n==="create"?r.split("/").pop():void 0;this.runtime.emitWrite({method:n,path:r,auth:s,...n!=="delete"&&i?{data:i}:{},priorState:A,nextState:n==="delete"?null:w,...I&&I.length>0?{sentinels:I}:{},...E?{autoId:E}:{},requestTime:p,...f?{detail:f}:{}})}return D&&this.runtime.notify(n,r,new Set([r])),x}createWithAutoId(e,n,r,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=_f(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:r,data:n,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,n,r){return this.batches.batch(e,n,r)}transaction(e,n){return this.transactions.transaction(e,n)}}class sa{state;eventLog;history;simulator;rules;seedSnapshot;events=new Nh;triggerScope=new Lh;reads;writes;listeners;constructor(){this.state=new Or,this.eventLog=new Oh;const e=this;this.simulator=new ud,this.rules=new zh(Th),this.reads=new Sf(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new Uh(this.events,this.triggerScope,this.reads),this.writes=new Df({get state(){return e.state},notifyListenersForPaths:n=>e.listeners.notifyListenersForPaths(n)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new Bh(this.eventLog,{get state(){return e.state},capturePriors:n=>this.writes.capturePriors(n),applyWrite:(n,r,s,i)=>this.writes.applyWrite(n,r,s,i)}),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,r={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,n,r,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new Or({},new kh(e.baseDocuments)):new Or(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Kr(e.rules)}deployRules(e){const n=Kr(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,r,s){return this.writes.createWithAutoId(e,n,r,s)}batch(e,n,r){return this.writes.batch(e,n,r)}transaction(e,n){return this.writes.transaction(e,n)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class Ye extends Error{code;denialContext;remediation;constructor(e,n,r){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:n,o=s?e.denialContext:r,c=s?e.remediation:void 0,u=c!==void 0?`${a}
|
|
507
|
+
|
|
508
|
+
Remediation:
|
|
509
|
+
${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function fs(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function Sn(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 wp(t){const e=Sn(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ia(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function js(t,e){const n=t?.operationContext?.source??t?.actor,r=e?.operationContext?.source??e?.actor;return Sn({source:ia(t)??ia(e)??n??r??{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 Ff(t){return js(void 0,t)}function Mf(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 Co(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"}:Mf(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 jf(t){if(t===null)return null;let e;return t.token!==void 0&&(e=Ro(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function Ro(t){const e={};for(const[n,r]of Object.entries(t))e[n]=To(r);return Object.freeze(e)}function To(t){return Array.isArray(t)?Object.freeze(t.map(To)):t&&typeof t=="object"?Ro(t):t}function Sp(t){if(!fs(t))return null;let e="listen",n;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(n=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(n=t.target.path));let r="firestore";return t.service!==void 0&&(r=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:r,method:e,...n===void 0?{}:{path:n},auth:jf(t.auth),result:t.result,context:Ff(t),rules:Object.freeze({...Co(t)})})}function aa(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 r;if(typeof n=="object"&&n!==null&&!Array.isArray(n)){const s=n;r={...s,tenant:s.tenant!==void 0?s.tenant:t.tenant}}else r={tenant:t.tenant};return e.firebase=r,{uid:t.uid,tenant:t.tenant,token:e}}function oa(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 gr{sandbox;auth;operationContext;constructor(e,n,r){this.sandbox=e,cr(n);const s=aa(n);this.auth=s,this.operationContext=Sn(r??{source:{kind:"unattributed"},authLens:oa(s)})}withAuth(e){cr(e);const n=aa(e);return new gr(this.sandbox,n,{source:this.operationContext.source,authLens:oa(n),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function _p(t,e){return new gr(t.sandbox,t.auth,e)}function cr(t){if(t===null)return;if(t===void 0)throw new Ye({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(`
|
|
510
|
+
`)});if(typeof t!="object")throw new Ye("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 Ye("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 Ye("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 Ye("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function $f(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function Pf(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function No(t){return ps(t,!0)}function ps(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ps(o,!1));return e&&us(a,Vi(t)),a}const n=t,r=a=>(e&&us(a,Vi(t)),a),s=(a,o)=>(Ls(a,Object.freeze(o),()=>a),r(a));if(n.__type__==="__vector__"&&Array.isArray(n.value)){const a=Object.freeze(n.value.slice());return s(new Xt(a),{type:"vector",values:a})}if(typeof n.__type=="string")switch(n.__type){case"timestamp":return s(new _e(n.seconds,n.nanos),{type:"timestamp",seconds:n.seconds,nanoseconds:n.nanos});case"bytes":{const a=$f(n.base64);return s(new Ie(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new lt(n.lat,n.lng),{type:"geo-point",latitude:n.lat,longitude:n.lng});case"duration":return r(new ve(n.seconds,n.nanos));case"reference":return r(new Rt(n.path));case"path":return r(new Xe(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const a=n.seconds,o=n.nanoseconds;return s(new _e(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Pf(n.bytes);return s(new Ie(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new lt(n.latitude,n.longitude),{type:"geo-point",latitude:n.latitude,longitude:n.longitude})}const i={};for(const[a,o]of Object.entries(n))i[a]=ps(o,!1);return r(i)}class En extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function qf(t){let e;try{e=JSON.parse(t)}catch(s){throw new En(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new En("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new En(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new En("Persisted blob has no firestore field");const n={};for(const[s,i]of Object.entries(e.firestore))n[s]=No(i);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const Uf=3,Bf=256,ms="meta";function zf(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%Bf).toString(16).padStart(2,"0")}function Vf(t){return JSON.parse(JSON.stringify(t))}function Lo(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function Do(t,e,n){const r=new Map;r.set(ms,{version:Uf,savedAt:n,services:e});for(const[s,i]of Object.entries(t)){const a=zf(s);let o=r.get(a);o||(o={docs:{}},r.set(a,o)),o.docs[s]=Vf(i)}for(const[s,i]of r)s!==ms&&(i.checksum=Lo(i.docs));return r}const Fo="pyric-v3-records";function Ap(t){return JSON.stringify({format:Fo,records:Object.fromEntries(t)})}function Ip(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===Fo&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):Mo(t)??new Map}function Mo(t){let e;try{e=qf(t)}catch{return null}return Do(e.firestore,e.services,0)}function Wf(t){const e={};let n={};for(const[r,s]of t){if(r===ms){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(n=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Lo(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=No(o)}}return{firestore:e,services:n}}const Qt="snapshots";function ca(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){const s=t.get(n)?.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,r){const s=e(n);for(const[i,a]of r)s.set(i,structuredClone(a))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const i of r)s.delete(i)},async clear(n){t.delete(n)}}}function jo(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(Qt)||s.createObjectStore(Qt)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function Nr(t,e,n){return jo(t).then(r=>new Promise((s,i)=>{const a=r.transaction(Qt,e),o=a.objectStore(Qt),c=n(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{r.close(),s(u)},a.onerror=()=>{r.close(),i(a.error)},a.onabort=()=>{r.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function ua(t,e){return jo(t).then(n=>new Promise((r,s)=>{const i=n.transaction(Qt,"readwrite");e(i.objectStore(Qt)),i.oncomplete=()=>{n.close(),r()},i.onerror=()=>{n.close(),s(i.error)},i.onabort=()=>{n.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function Hf(){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 Nr(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await Nr(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await ua(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await ua(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await Nr(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 Gf=250,la="pyric:sandbox:auth-session";function Lr(t){return t==="auth"||t==="auth-session:[DEFAULT]"?la:`${la}:${encodeURIComponent(t)}`}function $o(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function Kf(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 Zf(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?ca():Hf()}async function Jf(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??Gf,backend:e.backend??"indexedDB"},r=Zf(n),s=new Map,i=await Qf(t,r,n.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const A=t.snapshot(),w=Do(A.firestore,A.services,Date.now()),I=new Map,E=new Map;for(const[d,g]of w){const m=$o(g);E.set(d,m),s.get(d)!==m&&I.set(d,g)}const h=[...s.keys()].filter(d=>!w.has(d));I.size>0&&await r.putRecords(n.key,I),h.length>0&&await r.deleteRecords(n.key,h),s.clear();for(const[d,g]of E)s.set(d,g)};let f=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),f=f.then(u,u),f),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(A=>{if(Kf(A)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",A),p()})},n.flushIntervalMs))},y=(A,w)=>{if(!w.subscribe||c.has(A))return;const I=w.subscribe(()=>{p()});c.set(A,I)},v=new Map,b=new Map,C=(A,w)=>{if(!n.sessionStorage)return;const{local:I,session:E}=n.sessionStorage,h=Lr(A),d=w.currentUid(),g=w.mode();if(d===null||g==="NONE"){I.removeItem(h),E.removeItem(h);return}const m=JSON.stringify({uid:d});g==="LOCAL"?(E.removeItem(h),I.setItem(h,m)):(I.removeItem(h),E.setItem(h,m))},T=A=>{if(!n.sessionStorage)return null;const w=Lr(A);for(const[I,E]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const h=E.getItem(w);if(h)try{const d=JSON.parse(h);if(typeof d?.uid=="string")return{uid:d.uid,mode:I}}catch{E.removeItem(w)}}return null},R=A=>{if(!n.sessionStorage)return;const w=Lr(A);n.sessionStorage.local.removeItem(w),n.sessionStorage.session.removeItem(w)},_=(A,w,I)=>{if(I.session)try{I.session.restore(w.uid,w.mode),b.delete(A)}catch(E){console.warn(`[sandbox/persistence] session restore for uid '${w.uid}' failed — clearing stored session:`,E),R(A),b.delete(A)}},D=(A,w)=>{if(!n.sessionStorage||!w.session||v.has(A))return;const I=w.session;v.set(A,I.subscribe(()=>C(A,I)))},q=(A,w)=>{if(!w.session)return;const I=b.get(A)??T(A);I&&_(A,I,w)};if(t instanceof wt){for(const[A,w]of t.getServiceRegistry())y(A,w),q(A,w),D(A,w);t.setServiceRegistrationHook((A,w)=>{if(i!==null&&A in i)try{w.restore(i[A])}catch(E){console.warn(`[sandbox/persistence] late-restore for service '${A}' failed:`,E)}const I=T(A);I&&b.set(A,I),q(A,w),y(A,w),D(A,w),p()}),t.setServiceUnregistrationHook(A=>{c.get(A)?.(),c.delete(A),v.get(A)?.(),v.delete(A),b.delete(A),p()})}const S=t.onEvent(A=>{Yf(A)&&p()}),x=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",x),{options:n,flush:l,async clear(){a&&(clearTimeout(a),a=null),await r.clear(n.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const A of c.values())A();c.clear();for(const A of v.values())A();v.clear(),t instanceof wt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",x)}}}}async function Qf(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(f){return console.warn("[sandbox/persistence] backend list failed:",f),null}if(s.length===0)return null;const i=[];for(const f of s)try{const l=await e.getRecord(n,f);l!==null&&i.push([f,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${f}':`,l)}const a=[],o=[];let c=null;for(const[f,l]of i)if(typeof l=="string"){const p=Mo(l);p&&(o.push(f),c=p)}else a.push([f,l]);if(c){try{await e.putRecords(n,c),o.length>0&&await e.deleteRecords(n,o)}catch(f){console.warn("[sandbox/persistence] v2 migration write failed:",f)}for(const[f,l]of c)a.push([f,l])}for(const[f,l]of a)r.set(f,$o(l));const u=Wf(a);for(const[f,l]of Object.entries(u.firestore))t.admin.setDocument(f,l);if(t instanceof wt){const f=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=f.get(l);if(y)try{y.restore(p)}catch(v){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,v)}}}return u.services}function Yf(t){return t.kind==="write"||t.kind==="session_boundary"}function Xf(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let ep=0;function tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++ep}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function np(t,e={}){let n,r=!1;if(e.channel)n=e.channel,r=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),r=!0;else return()=>{};const s=e.originId??tp();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};n.postMessage(p)}),c=l=>{if(!Xf(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")f(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};n.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(_n(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[v,b]of Object.entries(p.snapshot.firestore))t.admin.setDocument(v,b)}finally{i=!1}a=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:s};return n.postMessage(u),()=>{o(),n.removeEventListener("message",c),r&&n.close()};function f(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function rp(t,e){const n={...t};n.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=fs(n)||t.operationContext!==void 0?js(e,s):sp(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}),fs(n)&&(n.rulesDisposition=Object.freeze({...Co(n)})),n}function sp(t,e){return Sn({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 ip(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Po(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 r=Sn({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:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function Po(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 r=js(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let ap=1;function Ct(){const t=(ap++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class wt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new wt(new sa)}getEnv(){return this._env}withAuth(e){return cr(e),new gr(this,e)}attachToEnv(){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,r)=>{const s={kind:"listener_errored",id:Ct(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=Po(this.ambientProvenance,n);this.dispatch(rp(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=ip(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&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]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Ct(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new sa,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Ct(),at:Date.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()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){cr(e),!op(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 r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new Ye("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 Jf(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return np(this,e)}async flush(){if(!this.persistence)throw new Ye("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 Ye("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 op(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),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function _n(t){if(!(t instanceof wt))throw new Ye("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Ep(t,e,n){if(!(t instanceof wt))throw new Ye("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function xp(t){return{kind:"service_mutation",id:Ct(),at:Date.now(),...t}}function kp(t){const{at:e,...n}=t;return{kind:"operation",id:Ct(),at:e??Date.now(),...n}}function Op(t){const{at:e,...n}=t;return{kind:"commit",id:Ct(),at:e??Date.now(),...n}}function Cp(t){const{at:e,...n}=t;return{kind:"listener",id:Ct(),at:e??Date.now(),...n}}function Rp(){return wt.createRoot()}function Tp(t,e){return _n(t).deployRules(e)}function Np(t,e){const n=_n(t);return n.seed({rules:n.getRules(),documents:e})}function Lp(t){return _n(t).snapshot()}function Dp(t,e={}){const n=e.recentEventLimit??10,r=_n(t),s=r.getRules(),i=s?Kr(s):{warnings:[]},a=i.warnings.map(b=>({rule:b.rule,severity:b.severity,message:b.message})),o={errors:0,warnings:0,info:0};for(const b of i.warnings)b.severity==="error"?o.errors++:b.severity==="warning"?o.warnings++:o.info++;const c=r.snapshot(),u={};for(const b of Object.keys(c)){const C=b.split("/")[0]??"";C&&(u[C]=(u[C]??0)+1)}const f=t.history(),l=[];for(const b of f){const C=b.kind==="request",T=b.kind==="operation",R=b.kind==="listener";(C||T||R&&b.phase==="errored")&&l.push(b)}const p=[];for(const b of l)if(b.result==="deny")p.push(b);else{const T=b.error;T!==void 0&&T.code==="PERMISSION_DENIED"&&p.push(b)}const y=l.slice(-n).map(b=>{let C="";if(b.path!==void 0)C=String(b.path);else{const D=b.target;D!==void 0&&D.path!==void 0&&(C=String(D.path))}let T="listen";b.method!==void 0&&(T=String(b.method));let R="error";if(b.result!==void 0)R=String(b.result);else{const D=b.error;D!==void 0&&D.code==="PERMISSION_DENIED"&&(R="deny")}let _=null;return b.auth!==void 0&&(_=b.auth),{path:C,method:T,result:R,auth:_}}),v=p.slice(-n).map(b=>{let C="";if(b.path!==void 0)C=String(b.path);else{const S=b.target;S!==void 0&&S.path!==void 0&&(C=String(S.path))}let T="listen";b.method!==void 0&&(T=String(b.method));let R=null;b.auth!==void 0&&(R=b.auth);let _;typeof b.debugMessage=="string"&&(_=b.debugMessage);const D=b.evaluatedRule??b.rule??void 0,q=Array.isArray(b.debugMessages)?b.debugMessages:typeof b.debugMessage=="string"?[b.debugMessage]:void 0;return{path:C,method:T,auth:R,debugMessage:_,rule:D,reasons:q}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:f.length,recentDenials:v,recentRequests:y}}}export{hp as $,js as A,wp as B,_p as C,ut as D,ot as E,Zt as F,Yr as G,Nt as H,Zn as I,Hn as J,_n as K,ca as L,Ye as M,Sp as N,fs as O,dp as P,go as Q,ae as R,gr as S,Wt as T,vo as U,gp as V,Dh as W,vp as X,ir as Y,fe as Z,lh as _,Np as a,fp as a0,Ls as a1,us as a2,Qe as a3,wf as a4,he as a5,_f as a6,xf as a7,kf as a8,rn as a9,nn as aa,na as ab,yp as ac,bp as ad,Ie as ae,lt as af,Xt as ag,pp as ah,Lp as b,Rp as c,kp as d,Ep as e,Op as f,zc as g,Cp as h,Dp as i,lp as j,Vd as k,Ot as l,xp as m,Ts as n,ct as o,zd as p,er as q,yn as r,Tp as s,Rs as t,gn as u,mp as v,Ip as w,Ap as x,No as y,Nn as z};
|