npm-christmas-tree 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Seochan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # 🎄 npm install christmas-tree
2
+
3
+ ![License](https://img.shields.io/badge/license-MIT-green)
4
+ ![Version](https://img.shields.io/badge/version-2.0.0-blue)
5
+ [![Deploy](https://img.shields.io/badge/demo-live-brightgreen)](https://npm-christmas-tree.web.app)
6
+
7
+ A hyper-realistic, terminal-based Christmas experience for developers. Simulates a package installation that compiles into a 3D "Matrix Code" tree with physics-based snow and global usage stats.
8
+
9
+ **🔗 [Live Demo](https://npm-christmas-tree.web.app)**
10
+
11
+ ## 🚀 Usage
12
+
13
+ ### Option 1: Run with npx (Instant Experience)
14
+
15
+ No installation required. Just run this command to open the experience in your browser:
16
+
17
+ ```bash
18
+ npx npm-christmas-tree
19
+ ```
20
+
21
+ ### Option 2: Use as a Library (Programmatic)
22
+
23
+ You can include the Christmas Tree experience in your own web projects.
24
+
25
+ ```bash
26
+ npm install npm-christmas-tree
27
+ ```
28
+
29
+ #### Basic Usage
30
+
31
+ ```javascript
32
+ import { ChristmasTreeApp } from 'npm-christmas-tree';
33
+ import 'npm-christmas-tree/dist/assets/index.css'; // If using the bundled version
34
+
35
+ const app = new ChristmasTreeApp({
36
+ treeCanvasId: 'my-canvas'
37
+ });
38
+ app.start();
39
+ ```
40
+
41
+ ## ✨ Features
42
+
43
+ - **Terminal Simulation** - Realistic typing animation with logs fetched from npm registry
44
+ - **3D Matrix Tree** - Rotating tree rendered with binary code characters
45
+ - **Twinkling Lights** - Colorful Christmas ornaments (red, gold, blue, pink, white)
46
+ - **Physics Snow** - Lightweight particle engine for realistic snowfall
47
+ - **CRT Aesthetics** - Scanlines, screen flicker, and chromatic aberration effects
48
+ - **Global Stats** - Real-time visitor counter via Firebase Firestore
49
+ - **Viral Sharing** - Native Web Share API integration
50
+ - **Mobile Responsive** - Optimized for all screen sizes
51
+
52
+ ## 📸 Preview
53
+
54
+ The app simulates `npm install christmas-tree` and reveals a beautiful animated Christmas tree!
55
+
56
+ ## 🚀 Quick Start
57
+
58
+ ### Prerequisites
59
+
60
+ - Node.js 18+
61
+ - Firebase project with Firestore enabled
62
+
63
+ ### Installation
64
+
65
+ ```bash
66
+ # Clone the repository
67
+ git clone https://github.com/seochan99/npm-christmas-tree.git
68
+ cd npm-christmas-tree
69
+
70
+ # Install dependencies
71
+ npm install
72
+
73
+ # Set up environment variables
74
+ cp .env.example .env
75
+ # Edit .env with your Firebase config
76
+
77
+ # Run development server
78
+ npm run dev
79
+ ```
80
+
81
+ ### Firebase Setup
82
+
83
+ 1. Create a project at [Firebase Console](https://console.firebase.google.com)
84
+ 2. Enable **Firestore Database** (start in test mode)
85
+ 3. Go to Project Settings > Your Apps > Add Web App
86
+ 4. Copy the config values to your `.env` file
87
+
88
+ ### Firestore Rules
89
+
90
+ For the global counter to work, update your Firestore rules:
91
+
92
+ ```javascript
93
+ rules_version = '2';
94
+ service cloud.firestore {
95
+ match /databases/{database}/documents {
96
+ match /{document=**} {
97
+ allow read, write: if true;
98
+ }
99
+ }
100
+ }
101
+ ```
102
+
103
+ ### Deploy
104
+
105
+ ```bash
106
+ # Build for production
107
+ npm run build
108
+
109
+ # Deploy to Firebase Hosting
110
+ firebase deploy --only hosting
111
+ ```
112
+
113
+ ## 🛠️ Tech Stack
114
+
115
+ - **Vite** - Build tool
116
+ - **Vanilla JavaScript** - No frameworks, pure JS
117
+ - **HTML5 Canvas** - 3D rendering
118
+ - **Firebase** - Firestore + Analytics + Hosting
119
+ - **CSS3** - Animations & effects
120
+
121
+ ## 📁 Project Structure
122
+
123
+ ```text
124
+ ├── index.html # Entry point
125
+ ├── main.js # App orchestration
126
+ ├── terminal.js # Typing animation & npm simulation
127
+ ├── tree.js # 3D Matrix tree rendering
128
+ ├── snow.js # Particle snow system
129
+ ├── firebase.js # Firebase integration
130
+ ├── style.css # All styles & effects
131
+ └── firestore.rules # Database security rules
132
+ ```
133
+
134
+ ## 🤝 Contributing
135
+
136
+ Contributions are welcome! Feel free to:
137
+
138
+ 1. Fork the repo
139
+ 2. Create a feature branch (`git checkout -b feature/amazing`)
140
+ 3. Commit changes (`git commit -m 'Add amazing feature'`)
141
+ 4. Push (`git push origin feature/amazing`)
142
+ 5. Open a Pull Request
143
+
144
+ ## 👤 Author
145
+
146
+ **Seochan**
147
+
148
+ - Instagram: [@dev_seochan](https://www.instagram.com/dev_seochan/)
149
+ - GitHub: [@seochan99](https://github.com/seochan99)
150
+
151
+ ## 📄 License
152
+
153
+ MIT License - feel free to use this for your own Christmas greeting!
154
+
155
+ ---
156
+
157
+ Made with ❤️ and ☕ | Merry Christmas! 🎄
package/bin/cli.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+
3
+ import open from 'open';
4
+
5
+ const url = 'https://npm-christmas-tree.web.app';
6
+
7
+ console.log('\x1b[32m%s\x1b[0m', '🎄 Starting npm-christmas-tree experience...');
8
+ console.log('Opening: ' + url);
9
+
10
+ open(url).catch(err => {
11
+ console.error('Failed to open browser:', err);
12
+ process.exit(1);
13
+ });
@@ -0,0 +1 @@
1
+ :root{--term-bg: #0a0a0a;--term-color: #00ff41;--term-dim: #008f11;--neon-red: #ff0055;--neon-gold: #ffd700}body,html{margin:0;padding:0;width:100%;height:100%;background-color:var(--term-bg);overflow:hidden;font-family:Fira Code,monospace;color:var(--term-color)}#app{width:100vw;height:100vh;position:relative}.terminal-overlay{position:absolute;top:0;left:0;width:100%;height:100%;z-index:100;padding:2rem;box-sizing:border-box;background:#0a0a0af2;transition:opacity 1s ease-out}.terminal-overlay.fade-out{opacity:0;pointer-events:none}.terminal-content{font-size:1.2rem;line-height:1.5;text-shadow:0 0 5px var(--term-dim)}.prompt{color:#bd93f9;margin-right:.5rem}#logs{margin-top:1rem;color:#ccc;font-size:.9rem;white-space:pre-wrap;height:80vh;overflow:hidden;display:flex;flex-direction:column-reverse}.log-line{margin-bottom:2px}.log-success{color:var(--term-color)}.log-warn{color:var(--neon-gold)}.log-bg{color:#555}.cursor{animation:blink 1s step-end infinite}@keyframes blink{50%{opacity:0}}#scene{position:absolute;top:0;left:0;width:100%;height:100%;z-index:1}canvas{position:absolute;top:0;left:0}#bg-canvas{z-index:2}#tree-canvas{z-index:3}#snow-canvas{z-index:4}#ui-top{position:absolute;top:2rem;left:50%;transform:translate(-50%);z-index:10;text-align:center;pointer-events:none;width:100%;max-width:600px;padding:0 1rem;box-sizing:border-box}#ui-bottom{position:absolute;bottom:2rem;left:50%;transform:translate(-50%);z-index:10;text-align:center;width:100%;max-width:500px;padding:0 1rem;box-sizing:border-box}#title{font-family:Orbitron,sans-serif;font-size:4rem;color:var(--term-color);text-shadow:0 0 10px var(--term-color),0 0 20px var(--term-color);opacity:0;transform:scale(.9);transition:opacity 2s ease,transform 2s ease;margin:0;pointer-events:auto}#title.visible{opacity:1;transform:scale(1)}#reset-btn{margin-top:2rem;background:transparent;border:1px solid var(--term-color);color:var(--term-color);padding:1rem 2rem;font-family:Fira Code,monospace;cursor:pointer;opacity:0;transition:all .3s ease;pointer-events:auto}#reset-btn:hover{background:var(--term-color);color:var(--term-bg);box-shadow:0 0 15px var(--term-color)}#reset-btn.visible{opacity:1}@keyframes scanline{0%{transform:translateY(-100%)}to{transform:translateY(100%)}}.scanline:before{content:" ";display:block;position:absolute;inset:0;background:linear-gradient(to bottom,#12101000 50%,#00000040 50%);background-size:100% 4px;z-index:999;pointer-events:none}.crt:after{content:" ";display:block;position:absolute;inset:0;background:#1210101a;opacity:0;z-index:999;pointer-events:none;animation:flicker .15s infinite}@keyframes flicker{0%{opacity:.02795}5%{opacity:.04416}10%{opacity:.02325}15%{opacity:.06734}20%{opacity:.01633}25%{opacity:.05341}30%{opacity:.07621}35%{opacity:.05814}40%{opacity:.0308}45%{opacity:.04616}50%{opacity:.08819}55%{opacity:.02704}60%{opacity:.07897}65%{opacity:.02058}70%{opacity:.09638}75%{opacity:.07076}80%{opacity:.01955}85%{opacity:.09315}90%{opacity:.01525}95%{opacity:.045}to{opacity:.02641}}.glitch{position:relative;text-shadow:2px 0 var(--neon-red),-2px 0 #00ffff;animation:chroma 2s infinite alternate}@keyframes chroma{0%{text-shadow:2px 0 var(--neon-red),-2px 0 #00ffff}to{text-shadow:-2px 0 var(--neon-red),2px 0 #00ffff}}canvas{filter:drop-shadow(0 0 5px var(--term-color))}#tree-canvas{filter:drop-shadow(0 0 10px var(--term-color)) blur(.5px)}.hidden{display:none!important}#stats{margin-top:1rem;font-family:Fira Code,monospace;color:var(--neon-gold);font-size:1.2rem;text-shadow:0 0 5px var(--neon-gold);opacity:0;transition:opacity 1s ease}#stats.visible{opacity:1}.action-buttons{margin-top:2rem;display:flex;gap:1rem;justify-content:center}#reset-btn{margin-top:0}#share-btn{background:var(--term-color);border:1px solid var(--term-color);color:var(--term-bg);padding:1rem 2rem;font-family:Fira Code,monospace;font-weight:700;cursor:pointer;opacity:0;transition:all .3s ease;pointer-events:auto;box-shadow:0 0 10px var(--term-color)}#share-btn:hover{background:var(--term-bg);color:var(--term-color);box-shadow:0 0 20px var(--term-color)}#share-btn.visible{opacity:1}#footer{margin-top:3rem;font-size:.8rem;color:#555;opacity:0;transition:opacity 1s ease;pointer-events:auto}#footer a{color:#777;text-decoration:none;border-bottom:1px dotted #777;transition:color .3s}#footer a:hover{color:var(--term-color);border-bottom-color:var(--term-color)}#footer.visible{opacity:1}@media screen and (max-width:768px){.terminal-content{font-size:.9rem;padding:1rem}.terminal-overlay{padding:1rem}#logs{font-size:.75rem;height:70vh}#ui-layer{width:90%;padding:1rem}#title{font-size:2rem;line-height:1.2}#stats{font-size:.9rem;margin-top:.5rem}.action-buttons{flex-direction:column;gap:.75rem;margin-top:1.5rem}#reset-btn,#share-btn{padding:.75rem 1.5rem;font-size:.9rem;width:100%}#footer{margin-top:2rem;font-size:.7rem}}@media screen and (max-width:480px){#title{font-size:1.5rem}.terminal-content{font-size:.8rem}#logs{font-size:.65rem}.prompt{font-size:.8rem}}@supports (-webkit-touch-callout: none){body,html{height:-webkit-fill-available}#app{min-height:-webkit-fill-available}}
@@ -0,0 +1,36 @@
1
+ (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function e(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=e(s);fetch(s.href,o)}})();class $l{constructor(t,e,r){this.typewriterEl=document.getElementById(t),this.logsEl=document.getElementById(e),this.onComplete=r,this.command="npm install christmas-tree",this.typingSpeed=30,this.packages=["extracting festive-spirit... [OK]","fetching decoration-modules... [OK]","parsing tinsel-dependencies... [OK]","compiling binary-star... [OK]","linking north-pole-api... [OK]","optimizing reindeer-routes... [OK]","wrapping presents... [OK]","[WARN] glitter-leak detected, patching... [FIXED]","installing snow-shader v2.0... [OK]","deploying magic-kernel... [SUCCESS]","injecting holiday-cheer... [SUCCESS]"]}async start(){const t=this.fetchRealNpmData();await this.typeCommand(),await t,await this.runInstall()}async fetchRealNpmData(){try{const t=new AbortController,e=setTimeout(()=>t.abort(),2e3),r=await fetch("https://registry.npmjs.org/christmas",{signal:t.signal});if(clearTimeout(e),!r.ok)throw new Error("Network response was not ok");const s=await r.json(),o=Object.keys(s.versions).slice(-5),a=s["dist-tags"].latest,u=s.versions[a].dependencies||{},h=Object.keys(u),d=[];o.forEach(m=>{d.push(`checking christmas@${m}... [MATCHED]`)}),h.length>0&&h.forEach(m=>{d.push(`resolving ${m}... [OK]`),d.push(`fetching ${m}@latest... [200 OK]`)}),d.push("running post-install scripts..."),d.push("generating holiday assets..."),d.push("[SUCCESS] installed christmas and "+(h.length+3)+" packages"),d.length<10?this.packages=[...d,...this.packages.slice(5)]:this.packages=d}catch(t){console.warn("Failed to fetch npm data, utilizing fallback",t)}}typeCommand(){return new Promise(t=>{let e=0;const r=setInterval(()=>{this.typewriterEl.textContent+=this.command[e],e++,e>=this.command.length&&(clearInterval(r),setTimeout(t,200))},this.typingSpeed)})}runInstall(){return new Promise(t=>{let e=0;const r=()=>{if(e>=this.packages.length){this.log("Done in 1.337s","log-success"),setTimeout(()=>{this.onComplete&&this.onComplete(),t()},500);return}const s=this.packages[e],o=s.includes("[WARN]")?"log-warn":"log-bg";this.log(`[${e+1}/${this.packages.length}] ${s}`,o),e++,setTimeout(r,Math.random()*80+20)};r()})}log(t,e=""){const r=document.createElement("div");r.className=`log-line ${e}`,r.textContent=t,this.logsEl.prepend(r)}}class zl{constructor(t){this.canvas=document.getElementById(t),this.ctx=this.canvas.getContext("2d"),this.chars="01",this.points=[],this.width=0,this.height=0,this.rotation=0,this.lightColors=["#ff0055","#ffd700","#00bfff","#ff69b4","#ffffff","#00ff41"],this.resize(),window.addEventListener("resize",()=>this.resize()),this.initPoints()}resize(){this.width=window.innerWidth,this.height=window.innerHeight,this.canvas.width=this.width,this.canvas.height=this.height}initPoints(){this.points=[];const t=60;for(let e=0;e<t;e++){const r=-.8+e/t*1.6,s=e/t*.5,o=1+e*6;for(let a=0;a<o;a++){const u=a/o*Math.PI*2,h=Math.random()>.85,d=h?this.lightColors[Math.floor(Math.random()*this.lightColors.length)]:null;this.points.push({x:Math.cos(u)*s,y:r,z:Math.sin(u)*s,char:this.chars[Math.floor(Math.random()*this.chars.length)],speed:Math.random()*.02+.01,isLight:h,lightColor:d,twinklePhase:Math.random()*Math.PI*2})}}}animate(){this.ctx.clearRect(0,0,this.width,this.height),this.rotation+=.01;const t=300,e=Date.now()*.003;this.points.forEach(r=>{const s=r.x*Math.cos(this.rotation)-r.z*Math.sin(this.rotation),o=r.x*Math.sin(this.rotation)+r.z*Math.cos(this.rotation),a=t/(t+o*300+400),u=s*600*a+this.width/2,h=r.y*600*a+this.height/2-50,d=Math.floor(14*a);if(this.ctx.font=`${d}px 'Fira Code'`,r.isLight){const m=Math.sin(e+r.twinklePhase)*.5+.5;this.ctx.fillStyle=r.lightColor,this.ctx.globalAlpha=.5+m*.5,this.ctx.font=`bold ${Math.floor(18*a)}px 'Fira Code'`,this.ctx.fillText("●",u,h),this.ctx.shadowColor=r.lightColor,this.ctx.shadowBlur=10*m}else this.ctx.globalAlpha=a,this.ctx.fillStyle=`rgba(0, 255, 65, ${a})`,this.ctx.shadowBlur=0,Math.random()>.95&&(r.char=Math.random()>.5?"0":"1"),this.ctx.fillText(r.char,u,h);this.ctx.globalAlpha=1,this.ctx.shadowBlur=0}),requestAnimationFrame(()=>this.animate())}}class Gl{constructor(t){this.canvas=document.getElementById(t),this.ctx=this.canvas.getContext("2d"),this.flakes=[],this.width=0,this.height=0,this.resize(),window.addEventListener("resize",()=>this.resize()),this.initFlakes()}resize(){this.width=window.innerWidth,this.height=window.innerHeight,this.canvas.width=this.width,this.canvas.height=this.height}initFlakes(){for(let e=0;e<200;e++)this.flakes.push(this.createFlake())}createFlake(){return{x:Math.random()*this.width,y:Math.random()*this.height,radius:Math.random()*2+1,speed:Math.random()*1+.5,wind:Math.random()*.5-.25}}animate(){this.ctx.clearRect(0,0,this.width,this.height),this.ctx.fillStyle="rgba(255, 255, 255, 0.8)",this.ctx.beginPath(),this.flakes.forEach(t=>{this.ctx.moveTo(t.x,t.y),this.ctx.arc(t.x,t.y,t.radius,0,Math.PI*2),t.y+=t.speed,t.x+=t.wind,t.y>this.height&&(t.y=-5,t.x=Math.random()*this.width),t.x>this.width&&(t.x=0),t.x<0&&(t.x=this.width)}),this.ctx.fill(),requestAnimationFrame(()=>this.animate())}}const Hl=()=>{};var qo={};const rc=function(n){const t=[];let e=0;for(let r=0;r<n.length;r++){let s=n.charCodeAt(r);s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&r+1<n.length&&(n.charCodeAt(r+1)&64512)===56320?(s=65536+((s&1023)<<10)+(n.charCodeAt(++r)&1023),t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128)}return t},Kl=function(n){const t=[];let e=0,r=0;for(;e<n.length;){const s=n[e++];if(s<128)t[r++]=String.fromCharCode(s);else if(s>191&&s<224){const o=n[e++];t[r++]=String.fromCharCode((s&31)<<6|o&63)}else if(s>239&&s<365){const o=n[e++],a=n[e++],u=n[e++],h=((s&7)<<18|(o&63)<<12|(a&63)<<6|u&63)-65536;t[r++]=String.fromCharCode(55296+(h>>10)),t[r++]=String.fromCharCode(56320+(h&1023))}else{const o=n[e++],a=n[e++];t[r++]=String.fromCharCode((s&15)<<12|(o&63)<<6|a&63)}}return t.join("")},sc={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(n,t){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();const e=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let s=0;s<n.length;s+=3){const o=n[s],a=s+1<n.length,u=a?n[s+1]:0,h=s+2<n.length,d=h?n[s+2]:0,m=o>>2,T=(o&3)<<4|u>>4;let v=(u&15)<<2|d>>6,b=d&63;h||(b=64,a||(v=64)),r.push(e[m],e[T],e[v],e[b])}return r.join("")},encodeString(n,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(n):this.encodeByteArray(rc(n),t)},decodeString(n,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(n):Kl(this.decodeStringToByteArray(n,t))},decodeStringToByteArray(n,t){this.init_();const e=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let s=0;s<n.length;){const o=e[n.charAt(s++)],u=s<n.length?e[n.charAt(s)]:0;++s;const d=s<n.length?e[n.charAt(s)]:64;++s;const T=s<n.length?e[n.charAt(s)]:64;if(++s,o==null||u==null||d==null||T==null)throw new Wl;const v=o<<2|u>>4;if(r.push(v),d!==64){const b=u<<4&240|d>>2;if(r.push(b),T!==64){const k=d<<6&192|T;r.push(k)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let n=0;n<this.ENCODED_VALS.length;n++)this.byteToCharMap_[n]=this.ENCODED_VALS.charAt(n),this.charToByteMap_[this.byteToCharMap_[n]]=n,this.byteToCharMapWebSafe_[n]=this.ENCODED_VALS_WEBSAFE.charAt(n),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[n]]=n,n>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(n)]=n,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(n)]=n)}}};class Wl extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const Ql=function(n){const t=rc(n);return sc.encodeByteArray(t,!0)},ur=function(n){return Ql(n).replace(/\./g,"")},Xl=function(n){try{return sc.decodeString(n,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function Yl(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}const Jl=()=>Yl().__FIREBASE_DEFAULTS__,Zl=()=>{if(typeof process>"u"||typeof qo>"u")return;const n=qo.__FIREBASE_DEFAULTS__;if(n)return JSON.parse(n)},th=()=>{if(typeof document>"u")return;let n;try{n=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const t=n&&Xl(n[1]);return t&&JSON.parse(t)},Js=()=>{try{return Hl()||Jl()||Zl()||th()}catch(n){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${n}`);return}},eh=n=>Js()?.emulatorHosts?.[n],nh=n=>{const t=eh(n);if(!t)return;const e=t.lastIndexOf(":");if(e<=0||e+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(e+1),10);return t[0]==="["?[t.substring(1,e-1),r]:[t.substring(0,e),r]},ic=()=>Js()?.config;class rh{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}wrapCallback(t){return(e,r)=>{e?this.reject(e):this.resolve(r),typeof t=="function"&&(this.promise.catch(()=>{}),t.length===1?t(e):t(e,r))}}}function Zs(n){try{return(n.startsWith("http://")||n.startsWith("https://")?new URL(n).hostname:n).endsWith(".cloudworkstations.dev")}catch{return!1}}async function sh(n){return(await fetch(n,{credentials:"include"})).ok}function ih(n,t){if(n.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const e={alg:"none",type:"JWT"},r=t||"demo-project",s=n.iat||0,o=n.sub||n.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const a={iss:`https://securetoken.google.com/${r}`,aud:r,iat:s,exp:s+3600,auth_time:s,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}},...n};return[ur(JSON.stringify(e)),ur(JSON.stringify(a)),""].join(".")}const pn={};function oh(){const n={prod:[],emulator:[]};for(const t of Object.keys(pn))pn[t]?n.emulator.push(t):n.prod.push(t);return n}function ah(n){let t=document.getElementById(n),e=!1;return t||(t=document.createElement("div"),t.setAttribute("id",n),e=!0),{created:e,element:t}}let $o=!1;function ch(n,t){if(typeof window>"u"||typeof document>"u"||!Zs(window.location.host)||pn[n]===t||pn[n]||$o)return;pn[n]=t;function e(v){return`__firebase__banner__${v}`}const r="__firebase__banner",o=oh().prod.length>0;function a(){const v=document.getElementById(r);v&&v.remove()}function u(v){v.style.display="flex",v.style.background="#7faaf0",v.style.position="fixed",v.style.bottom="5px",v.style.left="5px",v.style.padding=".5em",v.style.borderRadius="5px",v.style.alignItems="center"}function h(v,b){v.setAttribute("width","24"),v.setAttribute("id",b),v.setAttribute("height","24"),v.setAttribute("viewBox","0 0 24 24"),v.setAttribute("fill","none"),v.style.marginLeft="-6px"}function d(){const v=document.createElement("span");return v.style.cursor="pointer",v.style.marginLeft="16px",v.style.fontSize="24px",v.innerHTML=" &times;",v.onclick=()=>{$o=!0,a()},v}function m(v,b){v.setAttribute("id",b),v.innerText="Learn more",v.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",v.setAttribute("target","__blank"),v.style.paddingLeft="5px",v.style.textDecoration="underline"}function T(){const v=ah(r),b=e("text"),k=document.getElementById(b)||document.createElement("span"),M=e("learnmore"),V=document.getElementById(M)||document.createElement("a"),z=e("preprendIcon"),G=document.getElementById(z)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(v.created){const H=v.element;u(H),m(V,M);const _t=d();h(G,z),H.append(G,k,V,_t),document.body.appendChild(H)}o?(k.innerText="Preview backend disconnected.",G.innerHTML=`<g clip-path="url(#clip0_6013_33858)">
2
+ <path d="M4.8 17.6L12 5.6L19.2 17.6H4.8ZM6.91667 16.4H17.0833L12 7.93333L6.91667 16.4ZM12 15.6C12.1667 15.6 12.3056 15.5444 12.4167 15.4333C12.5389 15.3111 12.6 15.1667 12.6 15C12.6 14.8333 12.5389 14.6944 12.4167 14.5833C12.3056 14.4611 12.1667 14.4 12 14.4C11.8333 14.4 11.6889 14.4611 11.5667 14.5833C11.4556 14.6944 11.4 14.8333 11.4 15C11.4 15.1667 11.4556 15.3111 11.5667 15.4333C11.6889 15.5444 11.8333 15.6 12 15.6ZM11.4 13.6H12.6V10.4H11.4V13.6Z" fill="#212121"/>
3
+ </g>
4
+ <defs>
5
+ <clipPath id="clip0_6013_33858">
6
+ <rect width="24" height="24" fill="white"/>
7
+ </clipPath>
8
+ </defs>`):(G.innerHTML=`<g clip-path="url(#clip0_6083_34804)">
9
+ <path d="M11.4 15.2H12.6V11.2H11.4V15.2ZM12 10C12.1667 10 12.3056 9.94444 12.4167 9.83333C12.5389 9.71111 12.6 9.56667 12.6 9.4C12.6 9.23333 12.5389 9.09444 12.4167 8.98333C12.3056 8.86111 12.1667 8.8 12 8.8C11.8333 8.8 11.6889 8.86111 11.5667 8.98333C11.4556 9.09444 11.4 9.23333 11.4 9.4C11.4 9.56667 11.4556 9.71111 11.5667 9.83333C11.6889 9.94444 11.8333 10 12 10ZM12 18.4C11.1222 18.4 10.2944 18.2333 9.51667 17.9C8.73889 17.5667 8.05556 17.1111 7.46667 16.5333C6.88889 15.9444 6.43333 15.2611 6.1 14.4833C5.76667 13.7056 5.6 12.8778 5.6 12C5.6 11.1111 5.76667 10.2833 6.1 9.51667C6.43333 8.73889 6.88889 8.06111 7.46667 7.48333C8.05556 6.89444 8.73889 6.43333 9.51667 6.1C10.2944 5.76667 11.1222 5.6 12 5.6C12.8889 5.6 13.7167 5.76667 14.4833 6.1C15.2611 6.43333 15.9389 6.89444 16.5167 7.48333C17.1056 8.06111 17.5667 8.73889 17.9 9.51667C18.2333 10.2833 18.4 11.1111 18.4 12C18.4 12.8778 18.2333 13.7056 17.9 14.4833C17.5667 15.2611 17.1056 15.9444 16.5167 16.5333C15.9389 17.1111 15.2611 17.5667 14.4833 17.9C13.7167 18.2333 12.8889 18.4 12 18.4ZM12 17.2C13.4444 17.2 14.6722 16.6944 15.6833 15.6833C16.6944 14.6722 17.2 13.4444 17.2 12C17.2 10.5556 16.6944 9.32778 15.6833 8.31667C14.6722 7.30555 13.4444 6.8 12 6.8C10.5556 6.8 9.32778 7.30555 8.31667 8.31667C7.30556 9.32778 6.8 10.5556 6.8 12C6.8 13.4444 7.30556 14.6722 8.31667 15.6833C9.32778 16.6944 10.5556 17.2 12 17.2Z" fill="#212121"/>
10
+ </g>
11
+ <defs>
12
+ <clipPath id="clip0_6083_34804">
13
+ <rect width="24" height="24" fill="white"/>
14
+ </clipPath>
15
+ </defs>`,k.innerText="Preview backend running in this workspace."),k.setAttribute("id",b)}document.readyState==="loading"?window.addEventListener("DOMContentLoaded",T):T()}function uh(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function lh(){const n=Js()?.forceEnvironment;if(n==="node")return!0;if(n==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function hh(){const n=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof n=="object"&&n.id!==void 0}function dh(){return!lh()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function oc(){try{return typeof indexedDB=="object"}catch{return!1}}function ac(){return new Promise((n,t)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(r);s.onsuccess=()=>{s.result.close(),e||self.indexedDB.deleteDatabase(r),n(!0)},s.onupgradeneeded=()=>{e=!1},s.onerror=()=>{t(s.error?.message||"")}}catch(e){t(e)}})}function fh(){return!(typeof navigator>"u"||!navigator.cookieEnabled)}const mh="FirebaseError";class ue extends Error{constructor(t,e,r){super(e),this.code=t,this.customData=r,this.name=mh,Object.setPrototypeOf(this,ue.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Rr.prototype.create)}}class Rr{constructor(t,e,r){this.service=t,this.serviceName=e,this.errors=r}create(t,...e){const r=e[0]||{},s=`${this.service}/${t}`,o=this.errors[t],a=o?ph(o,r):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new ue(s,u,r)}}function ph(n,t){return n.replace(gh,(e,r)=>{const s=t[r];return s!=null?String(s):`<${r}?>`})}const gh=/\{\$([^}]+)}/g;function In(n,t){if(n===t)return!0;const e=Object.keys(n),r=Object.keys(t);for(const s of e){if(!r.includes(s))return!1;const o=n[s],a=t[s];if(zo(o)&&zo(a)){if(!In(o,a))return!1}else if(o!==a)return!1}for(const s of r)if(!e.includes(s))return!1;return!0}function zo(n){return n!==null&&typeof n=="object"}const _h=1e3,yh=2,Eh=14400*1e3,Th=.5;function Go(n,t=_h,e=yh){const r=t*Math.pow(e,n),s=Math.round(Th*r*(Math.random()-.5)*2);return Math.min(Eh,r+s)}function Ft(n){return n&&n._delegate?n._delegate:n}class jt{constructor(t,e,r){this.name=t,this.instanceFactory=e,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}const ye="[DEFAULT]";class Ih{constructor(t,e){this.name=t,this.container=e,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(t){const e=this.normalizeInstanceIdentifier(t);if(!this.instancesDeferred.has(e)){const r=new rh;if(this.instancesDeferred.set(e,r),this.isInitialized(e)||this.shouldAutoInitialize())try{const s=this.getOrInitializeService({instanceIdentifier:e});s&&r.resolve(s)}catch{}}return this.instancesDeferred.get(e).promise}getImmediate(t){const e=this.normalizeInstanceIdentifier(t?.identifier),r=t?.optional??!1;if(this.isInitialized(e)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:e})}catch(s){if(r)return null;throw s}else{if(r)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,!!this.shouldAutoInitialize()){if(vh(t))try{this.getOrInitializeService({instanceIdentifier:ye})}catch{}for(const[e,r]of this.instancesDeferred.entries()){const s=this.normalizeInstanceIdentifier(e);try{const o=this.getOrInitializeService({instanceIdentifier:s});r.resolve(o)}catch{}}}}clearInstance(t=ye){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...t.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return this.component!=null}isInitialized(t=ye){return this.instances.has(t)}getOptions(t=ye){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,r=this.normalizeInstanceIdentifier(t.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:r,options:e});for(const[o,a]of this.instancesDeferred.entries()){const u=this.normalizeInstanceIdentifier(o);r===u&&a.resolve(s)}return s}onInit(t,e){const r=this.normalizeInstanceIdentifier(e),s=this.onInitCallbacks.get(r)??new Set;s.add(t),this.onInitCallbacks.set(r,s);const o=this.instances.get(r);return o&&t(o,r),()=>{s.delete(t)}}invokeOnInitCallbacks(t,e){const r=this.onInitCallbacks.get(e);if(r)for(const s of r)try{s(t,e)}catch{}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let r=this.instances.get(t);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:wh(t),options:e}),this.instances.set(t,r),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(r,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,r)}catch{}return r||null}normalizeInstanceIdentifier(t=ye){return this.component?this.component.multipleInstances?t:ye:t}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function wh(n){return n===ye?void 0:n}function vh(n){return n.instantiationMode==="EAGER"}class Ah{constructor(t){this.name=t,this.providers=new Map}addComponent(t){const e=this.getProvider(t.name);if(e.isComponentSet())throw new Error(`Component ${t.name} has already been registered with ${this.name}`);e.setComponent(t)}addOrOverwriteComponent(t){this.getProvider(t.name).isComponentSet()&&this.providers.delete(t.name),this.addComponent(t)}getProvider(t){if(this.providers.has(t))return this.providers.get(t);const e=new Ih(t,this);return this.providers.set(t,e),e}getProviders(){return Array.from(this.providers.values())}}var $;(function(n){n[n.DEBUG=0]="DEBUG",n[n.VERBOSE=1]="VERBOSE",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.SILENT=5]="SILENT"})($||($={}));const Rh={debug:$.DEBUG,verbose:$.VERBOSE,info:$.INFO,warn:$.WARN,error:$.ERROR,silent:$.SILENT},Sh=$.INFO,Ch={[$.DEBUG]:"log",[$.VERBOSE]:"log",[$.INFO]:"info",[$.WARN]:"warn",[$.ERROR]:"error"},bh=(n,t,...e)=>{if(t<n.logLevel)return;const r=new Date().toISOString(),s=Ch[t];if(s)console[s](`[${r}] ${n.name}:`,...e);else throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`)};class ti{constructor(t){this.name=t,this._logLevel=Sh,this._logHandler=bh,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(t){if(!(t in $))throw new TypeError(`Invalid value "${t}" assigned to \`logLevel\``);this._logLevel=t}setLogLevel(t){this._logLevel=typeof t=="string"?Rh[t]:t}get logHandler(){return this._logHandler}set logHandler(t){if(typeof t!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t}get userLogHandler(){return this._userLogHandler}set userLogHandler(t){this._userLogHandler=t}debug(...t){this._userLogHandler&&this._userLogHandler(this,$.DEBUG,...t),this._logHandler(this,$.DEBUG,...t)}log(...t){this._userLogHandler&&this._userLogHandler(this,$.VERBOSE,...t),this._logHandler(this,$.VERBOSE,...t)}info(...t){this._userLogHandler&&this._userLogHandler(this,$.INFO,...t),this._logHandler(this,$.INFO,...t)}warn(...t){this._userLogHandler&&this._userLogHandler(this,$.WARN,...t),this._logHandler(this,$.WARN,...t)}error(...t){this._userLogHandler&&this._userLogHandler(this,$.ERROR,...t),this._logHandler(this,$.ERROR,...t)}}const Ph=(n,t)=>t.some(e=>n instanceof e);let Ho,Ko;function Vh(){return Ho||(Ho=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Dh(){return Ko||(Ko=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const cc=new WeakMap,Cs=new WeakMap,uc=new WeakMap,ps=new WeakMap,ei=new WeakMap;function kh(n){const t=new Promise((e,r)=>{const s=()=>{n.removeEventListener("success",o),n.removeEventListener("error",a)},o=()=>{e(Jt(n.result)),s()},a=()=>{r(n.error),s()};n.addEventListener("success",o),n.addEventListener("error",a)});return t.then(e=>{e instanceof IDBCursor&&cc.set(e,n)}).catch(()=>{}),ei.set(t,n),t}function Nh(n){if(Cs.has(n))return;const t=new Promise((e,r)=>{const s=()=>{n.removeEventListener("complete",o),n.removeEventListener("error",a),n.removeEventListener("abort",a)},o=()=>{e(),s()},a=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",o),n.addEventListener("error",a),n.addEventListener("abort",a)});Cs.set(n,t)}let bs={get(n,t,e){if(n instanceof IDBTransaction){if(t==="done")return Cs.get(n);if(t==="objectStoreNames")return n.objectStoreNames||uc.get(n);if(t==="store")return e.objectStoreNames[1]?void 0:e.objectStore(e.objectStoreNames[0])}return Jt(n[t])},set(n,t,e){return n[t]=e,!0},has(n,t){return n instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in n}};function Mh(n){bs=n(bs)}function xh(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...e){const r=n.call(gs(this),t,...e);return uc.set(r,t.sort?t.sort():[t]),Jt(r)}:Dh().includes(n)?function(...t){return n.apply(gs(this),t),Jt(cc.get(this))}:function(...t){return Jt(n.apply(gs(this),t))}}function Oh(n){return typeof n=="function"?xh(n):(n instanceof IDBTransaction&&Nh(n),Ph(n,Vh())?new Proxy(n,bs):n)}function Jt(n){if(n instanceof IDBRequest)return kh(n);if(ps.has(n))return ps.get(n);const t=Oh(n);return t!==n&&(ps.set(n,t),ei.set(t,n)),t}const gs=n=>ei.get(n);function lc(n,t,{blocked:e,upgrade:r,blocking:s,terminated:o}={}){const a=indexedDB.open(n,t),u=Jt(a);return r&&a.addEventListener("upgradeneeded",h=>{r(Jt(a.result),h.oldVersion,h.newVersion,Jt(a.transaction),h)}),e&&a.addEventListener("blocked",h=>e(h.oldVersion,h.newVersion,h)),u.then(h=>{o&&h.addEventListener("close",()=>o()),s&&h.addEventListener("versionchange",d=>s(d.oldVersion,d.newVersion,d))}).catch(()=>{}),u}const Lh=["get","getKey","getAll","getAllKeys","count"],Fh=["put","add","delete","clear"],_s=new Map;function Wo(n,t){if(!(n instanceof IDBDatabase&&!(t in n)&&typeof t=="string"))return;if(_s.get(t))return _s.get(t);const e=t.replace(/FromIndex$/,""),r=t!==e,s=Fh.includes(e);if(!(e in(r?IDBIndex:IDBObjectStore).prototype)||!(s||Lh.includes(e)))return;const o=async function(a,...u){const h=this.transaction(a,s?"readwrite":"readonly");let d=h.store;return r&&(d=d.index(u.shift())),(await Promise.all([d[e](...u),s&&h.done]))[0]};return _s.set(t,o),o}Mh(n=>({...n,get:(t,e,r)=>Wo(t,e)||n.get(t,e,r),has:(t,e)=>!!Wo(t,e)||n.has(t,e)}));class Uh{constructor(t){this.container=t}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(Bh(e)){const r=e.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(e=>e).join(" ")}}function Bh(n){return n.getComponent()?.type==="VERSION"}const Ps="@firebase/app",Qo="0.14.6";const qt=new ti("@firebase/app"),jh="@firebase/app-compat",qh="@firebase/analytics-compat",$h="@firebase/analytics",zh="@firebase/app-check-compat",Gh="@firebase/app-check",Hh="@firebase/auth",Kh="@firebase/auth-compat",Wh="@firebase/database",Qh="@firebase/data-connect",Xh="@firebase/database-compat",Yh="@firebase/functions",Jh="@firebase/functions-compat",Zh="@firebase/installations",td="@firebase/installations-compat",ed="@firebase/messaging",nd="@firebase/messaging-compat",rd="@firebase/performance",sd="@firebase/performance-compat",id="@firebase/remote-config",od="@firebase/remote-config-compat",ad="@firebase/storage",cd="@firebase/storage-compat",ud="@firebase/firestore",ld="@firebase/ai",hd="@firebase/firestore-compat",dd="firebase",fd="12.6.0";const Vs="[DEFAULT]",md={[Ps]:"fire-core",[jh]:"fire-core-compat",[$h]:"fire-analytics",[qh]:"fire-analytics-compat",[Gh]:"fire-app-check",[zh]:"fire-app-check-compat",[Hh]:"fire-auth",[Kh]:"fire-auth-compat",[Wh]:"fire-rtdb",[Qh]:"fire-data-connect",[Xh]:"fire-rtdb-compat",[Yh]:"fire-fn",[Jh]:"fire-fn-compat",[Zh]:"fire-iid",[td]:"fire-iid-compat",[ed]:"fire-fcm",[nd]:"fire-fcm-compat",[rd]:"fire-perf",[sd]:"fire-perf-compat",[id]:"fire-rc",[od]:"fire-rc-compat",[ad]:"fire-gcs",[cd]:"fire-gcs-compat",[ud]:"fire-fst",[hd]:"fire-fst-compat",[ld]:"fire-vertex","fire-js":"fire-js",[dd]:"fire-js-all"};const lr=new Map,pd=new Map,Ds=new Map;function Xo(n,t){try{n.container.addComponent(t)}catch(e){qt.debug(`Component ${t.name} failed to register with FirebaseApp ${n.name}`,e)}}function ne(n){const t=n.name;if(Ds.has(t))return qt.debug(`There were multiple attempts to register component ${t}.`),!1;Ds.set(t,n);for(const e of lr.values())Xo(e,n);for(const e of pd.values())Xo(e,n);return!0}function Dn(n,t){const e=n.container.getProvider("heartbeat").getImmediate({optional:!0});return e&&e.triggerHeartbeat(),n.container.getProvider(t)}function gd(n){return n==null?!1:n.settings!==void 0}const _d={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Zt=new Rr("app","Firebase",_d);class yd{constructor(t,e,r){this._isDeleted=!1,this._options={...t},this._config={...e},this._name=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new jt("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(t){this.checkDestroyed(),this._automaticDataCollectionEnabled=t}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(t){this._isDeleted=t}checkDestroyed(){if(this.isDeleted)throw Zt.create("app-deleted",{appName:this._name})}}const Ed=fd;function hc(n,t={}){let e=n;typeof t!="object"&&(t={name:t});const r={name:Vs,automaticDataCollectionEnabled:!0,...t},s=r.name;if(typeof s!="string"||!s)throw Zt.create("bad-app-name",{appName:String(s)});if(e||(e=ic()),!e)throw Zt.create("no-options");const o=lr.get(s);if(o){if(In(e,o.options)&&In(r,o.config))return o;throw Zt.create("duplicate-app",{appName:s})}const a=new Ah(s);for(const h of Ds.values())a.addComponent(h);const u=new yd(e,r,a);return lr.set(s,u),u}function dc(n=Vs){const t=lr.get(n);if(!t&&n===Vs&&ic())return hc();if(!t)throw Zt.create("no-app",{appName:n});return t}function kt(n,t,e){let r=md[n]??n;e&&(r+=`-${e}`);const s=r.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const a=[`Unable to register library "${r}" with version "${t}":`];s&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&o&&a.push("and"),o&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),qt.warn(a.join(" "));return}ne(new jt(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}const Td="firebase-heartbeat-database",Id=1,wn="firebase-heartbeat-store";let ys=null;function fc(){return ys||(ys=lc(Td,Id,{upgrade:(n,t)=>{switch(t){case 0:try{n.createObjectStore(wn)}catch(e){console.warn(e)}}}}).catch(n=>{throw Zt.create("idb-open",{originalErrorMessage:n.message})})),ys}async function wd(n){try{const e=(await fc()).transaction(wn),r=await e.objectStore(wn).get(mc(n));return await e.done,r}catch(t){if(t instanceof ue)qt.warn(t.message);else{const e=Zt.create("idb-get",{originalErrorMessage:t?.message});qt.warn(e.message)}}}async function Yo(n,t){try{const r=(await fc()).transaction(wn,"readwrite");await r.objectStore(wn).put(t,mc(n)),await r.done}catch(e){if(e instanceof ue)qt.warn(e.message);else{const r=Zt.create("idb-set",{originalErrorMessage:e?.message});qt.warn(r.message)}}}function mc(n){return`${n.name}!${n.options.appId}`}const vd=1024,Ad=30;class Rd{constructor(t){this.container=t,this._heartbeatsCache=null;const e=this.container.getProvider("app").getImmediate();this._storage=new Cd(e),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=Jo();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(s=>s.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:e}),this._heartbeatsCache.heartbeats.length>Ad){const s=bd(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(s,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(t){qt.warn(t)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";const t=Jo(),{heartbeatsToSend:e,unsentEntries:r}=Sd(this._heartbeatsCache.heartbeats),s=ur(JSON.stringify({version:2,heartbeats:e}));return this._heartbeatsCache.lastSentHeartbeatDate=t,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(t){return qt.warn(t),""}}}function Jo(){return new Date().toISOString().substring(0,10)}function Sd(n,t=vd){const e=[];let r=n.slice();for(const s of n){const o=e.find(a=>a.agent===s.agent);if(o){if(o.dates.push(s.date),Zo(e)>t){o.dates.pop();break}}else if(e.push({agent:s.agent,dates:[s.date]}),Zo(e)>t){e.pop();break}r=r.slice(1)}return{heartbeatsToSend:e,unsentEntries:r}}class Cd{constructor(t){this.app=t,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return oc()?ac().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const e=await wd(this.app);return e?.heartbeats?e:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(t){if(await this._canUseIndexedDBPromise){const r=await this.read();return Yo(this.app,{lastSentHeartbeatDate:t.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:t.heartbeats})}else return}async add(t){if(await this._canUseIndexedDBPromise){const r=await this.read();return Yo(this.app,{lastSentHeartbeatDate:t.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...t.heartbeats]})}else return}}function Zo(n){return ur(JSON.stringify({version:2,heartbeats:n})).length}function bd(n){if(n.length===0)return-1;let t=0,e=n[0].date;for(let r=1;r<n.length;r++)n[r].date<e&&(e=n[r].date,t=r);return t}function Pd(n){ne(new jt("platform-logger",t=>new Uh(t),"PRIVATE")),ne(new jt("heartbeat",t=>new Rd(t),"PRIVATE")),kt(Ps,Qo,n),kt(Ps,Qo,"esm2020"),kt("fire-js","")}Pd("");var Vd="firebase",Dd="12.7.0";kt(Vd,Dd,"app");var ta=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var te,pc;(function(){var n;function t(E,p){function _(){}_.prototype=p.prototype,E.F=p.prototype,E.prototype=new _,E.prototype.constructor=E,E.D=function(I,y,A){for(var g=Array(arguments.length-2),wt=2;wt<arguments.length;wt++)g[wt-2]=arguments[wt];return p.prototype[y].apply(I,g)}}function e(){this.blockSize=-1}function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}t(r,e),r.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(E,p,_){_||(_=0);const I=Array(16);if(typeof p=="string")for(var y=0;y<16;++y)I[y]=p.charCodeAt(_++)|p.charCodeAt(_++)<<8|p.charCodeAt(_++)<<16|p.charCodeAt(_++)<<24;else for(y=0;y<16;++y)I[y]=p[_++]|p[_++]<<8|p[_++]<<16|p[_++]<<24;p=E.g[0],_=E.g[1],y=E.g[2];let A=E.g[3],g;g=p+(A^_&(y^A))+I[0]+3614090360&4294967295,p=_+(g<<7&4294967295|g>>>25),g=A+(y^p&(_^y))+I[1]+3905402710&4294967295,A=p+(g<<12&4294967295|g>>>20),g=y+(_^A&(p^_))+I[2]+606105819&4294967295,y=A+(g<<17&4294967295|g>>>15),g=_+(p^y&(A^p))+I[3]+3250441966&4294967295,_=y+(g<<22&4294967295|g>>>10),g=p+(A^_&(y^A))+I[4]+4118548399&4294967295,p=_+(g<<7&4294967295|g>>>25),g=A+(y^p&(_^y))+I[5]+1200080426&4294967295,A=p+(g<<12&4294967295|g>>>20),g=y+(_^A&(p^_))+I[6]+2821735955&4294967295,y=A+(g<<17&4294967295|g>>>15),g=_+(p^y&(A^p))+I[7]+4249261313&4294967295,_=y+(g<<22&4294967295|g>>>10),g=p+(A^_&(y^A))+I[8]+1770035416&4294967295,p=_+(g<<7&4294967295|g>>>25),g=A+(y^p&(_^y))+I[9]+2336552879&4294967295,A=p+(g<<12&4294967295|g>>>20),g=y+(_^A&(p^_))+I[10]+4294925233&4294967295,y=A+(g<<17&4294967295|g>>>15),g=_+(p^y&(A^p))+I[11]+2304563134&4294967295,_=y+(g<<22&4294967295|g>>>10),g=p+(A^_&(y^A))+I[12]+1804603682&4294967295,p=_+(g<<7&4294967295|g>>>25),g=A+(y^p&(_^y))+I[13]+4254626195&4294967295,A=p+(g<<12&4294967295|g>>>20),g=y+(_^A&(p^_))+I[14]+2792965006&4294967295,y=A+(g<<17&4294967295|g>>>15),g=_+(p^y&(A^p))+I[15]+1236535329&4294967295,_=y+(g<<22&4294967295|g>>>10),g=p+(y^A&(_^y))+I[1]+4129170786&4294967295,p=_+(g<<5&4294967295|g>>>27),g=A+(_^y&(p^_))+I[6]+3225465664&4294967295,A=p+(g<<9&4294967295|g>>>23),g=y+(p^_&(A^p))+I[11]+643717713&4294967295,y=A+(g<<14&4294967295|g>>>18),g=_+(A^p&(y^A))+I[0]+3921069994&4294967295,_=y+(g<<20&4294967295|g>>>12),g=p+(y^A&(_^y))+I[5]+3593408605&4294967295,p=_+(g<<5&4294967295|g>>>27),g=A+(_^y&(p^_))+I[10]+38016083&4294967295,A=p+(g<<9&4294967295|g>>>23),g=y+(p^_&(A^p))+I[15]+3634488961&4294967295,y=A+(g<<14&4294967295|g>>>18),g=_+(A^p&(y^A))+I[4]+3889429448&4294967295,_=y+(g<<20&4294967295|g>>>12),g=p+(y^A&(_^y))+I[9]+568446438&4294967295,p=_+(g<<5&4294967295|g>>>27),g=A+(_^y&(p^_))+I[14]+3275163606&4294967295,A=p+(g<<9&4294967295|g>>>23),g=y+(p^_&(A^p))+I[3]+4107603335&4294967295,y=A+(g<<14&4294967295|g>>>18),g=_+(A^p&(y^A))+I[8]+1163531501&4294967295,_=y+(g<<20&4294967295|g>>>12),g=p+(y^A&(_^y))+I[13]+2850285829&4294967295,p=_+(g<<5&4294967295|g>>>27),g=A+(_^y&(p^_))+I[2]+4243563512&4294967295,A=p+(g<<9&4294967295|g>>>23),g=y+(p^_&(A^p))+I[7]+1735328473&4294967295,y=A+(g<<14&4294967295|g>>>18),g=_+(A^p&(y^A))+I[12]+2368359562&4294967295,_=y+(g<<20&4294967295|g>>>12),g=p+(_^y^A)+I[5]+4294588738&4294967295,p=_+(g<<4&4294967295|g>>>28),g=A+(p^_^y)+I[8]+2272392833&4294967295,A=p+(g<<11&4294967295|g>>>21),g=y+(A^p^_)+I[11]+1839030562&4294967295,y=A+(g<<16&4294967295|g>>>16),g=_+(y^A^p)+I[14]+4259657740&4294967295,_=y+(g<<23&4294967295|g>>>9),g=p+(_^y^A)+I[1]+2763975236&4294967295,p=_+(g<<4&4294967295|g>>>28),g=A+(p^_^y)+I[4]+1272893353&4294967295,A=p+(g<<11&4294967295|g>>>21),g=y+(A^p^_)+I[7]+4139469664&4294967295,y=A+(g<<16&4294967295|g>>>16),g=_+(y^A^p)+I[10]+3200236656&4294967295,_=y+(g<<23&4294967295|g>>>9),g=p+(_^y^A)+I[13]+681279174&4294967295,p=_+(g<<4&4294967295|g>>>28),g=A+(p^_^y)+I[0]+3936430074&4294967295,A=p+(g<<11&4294967295|g>>>21),g=y+(A^p^_)+I[3]+3572445317&4294967295,y=A+(g<<16&4294967295|g>>>16),g=_+(y^A^p)+I[6]+76029189&4294967295,_=y+(g<<23&4294967295|g>>>9),g=p+(_^y^A)+I[9]+3654602809&4294967295,p=_+(g<<4&4294967295|g>>>28),g=A+(p^_^y)+I[12]+3873151461&4294967295,A=p+(g<<11&4294967295|g>>>21),g=y+(A^p^_)+I[15]+530742520&4294967295,y=A+(g<<16&4294967295|g>>>16),g=_+(y^A^p)+I[2]+3299628645&4294967295,_=y+(g<<23&4294967295|g>>>9),g=p+(y^(_|~A))+I[0]+4096336452&4294967295,p=_+(g<<6&4294967295|g>>>26),g=A+(_^(p|~y))+I[7]+1126891415&4294967295,A=p+(g<<10&4294967295|g>>>22),g=y+(p^(A|~_))+I[14]+2878612391&4294967295,y=A+(g<<15&4294967295|g>>>17),g=_+(A^(y|~p))+I[5]+4237533241&4294967295,_=y+(g<<21&4294967295|g>>>11),g=p+(y^(_|~A))+I[12]+1700485571&4294967295,p=_+(g<<6&4294967295|g>>>26),g=A+(_^(p|~y))+I[3]+2399980690&4294967295,A=p+(g<<10&4294967295|g>>>22),g=y+(p^(A|~_))+I[10]+4293915773&4294967295,y=A+(g<<15&4294967295|g>>>17),g=_+(A^(y|~p))+I[1]+2240044497&4294967295,_=y+(g<<21&4294967295|g>>>11),g=p+(y^(_|~A))+I[8]+1873313359&4294967295,p=_+(g<<6&4294967295|g>>>26),g=A+(_^(p|~y))+I[15]+4264355552&4294967295,A=p+(g<<10&4294967295|g>>>22),g=y+(p^(A|~_))+I[6]+2734768916&4294967295,y=A+(g<<15&4294967295|g>>>17),g=_+(A^(y|~p))+I[13]+1309151649&4294967295,_=y+(g<<21&4294967295|g>>>11),g=p+(y^(_|~A))+I[4]+4149444226&4294967295,p=_+(g<<6&4294967295|g>>>26),g=A+(_^(p|~y))+I[11]+3174756917&4294967295,A=p+(g<<10&4294967295|g>>>22),g=y+(p^(A|~_))+I[2]+718787259&4294967295,y=A+(g<<15&4294967295|g>>>17),g=_+(A^(y|~p))+I[9]+3951481745&4294967295,E.g[0]=E.g[0]+p&4294967295,E.g[1]=E.g[1]+(y+(g<<21&4294967295|g>>>11))&4294967295,E.g[2]=E.g[2]+y&4294967295,E.g[3]=E.g[3]+A&4294967295}r.prototype.v=function(E,p){p===void 0&&(p=E.length);const _=p-this.blockSize,I=this.C;let y=this.h,A=0;for(;A<p;){if(y==0)for(;A<=_;)s(this,E,A),A+=this.blockSize;if(typeof E=="string"){for(;A<p;)if(I[y++]=E.charCodeAt(A++),y==this.blockSize){s(this,I),y=0;break}}else for(;A<p;)if(I[y++]=E[A++],y==this.blockSize){s(this,I),y=0;break}}this.h=y,this.o+=p},r.prototype.A=function(){var E=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);E[0]=128;for(var p=1;p<E.length-8;++p)E[p]=0;p=this.o*8;for(var _=E.length-8;_<E.length;++_)E[_]=p&255,p/=256;for(this.v(E),E=Array(16),p=0,_=0;_<4;++_)for(let I=0;I<32;I+=8)E[p++]=this.g[_]>>>I&255;return E};function o(E,p){var _=u;return Object.prototype.hasOwnProperty.call(_,E)?_[E]:_[E]=p(E)}function a(E,p){this.h=p;const _=[];let I=!0;for(let y=E.length-1;y>=0;y--){const A=E[y]|0;I&&A==p||(_[y]=A,I=!1)}this.g=_}var u={};function h(E){return-128<=E&&E<128?o(E,function(p){return new a([p|0],p<0?-1:0)}):new a([E|0],E<0?-1:0)}function d(E){if(isNaN(E)||!isFinite(E))return T;if(E<0)return V(d(-E));const p=[];let _=1;for(let I=0;E>=_;I++)p[I]=E/_|0,_*=4294967296;return new a(p,0)}function m(E,p){if(E.length==0)throw Error("number format error: empty string");if(p=p||10,p<2||36<p)throw Error("radix out of range: "+p);if(E.charAt(0)=="-")return V(m(E.substring(1),p));if(E.indexOf("-")>=0)throw Error('number format error: interior "-" character');const _=d(Math.pow(p,8));let I=T;for(let A=0;A<E.length;A+=8){var y=Math.min(8,E.length-A);const g=parseInt(E.substring(A,A+y),p);y<8?(y=d(Math.pow(p,y)),I=I.j(y).add(d(g))):(I=I.j(_),I=I.add(d(g)))}return I}var T=h(0),v=h(1),b=h(16777216);n=a.prototype,n.m=function(){if(M(this))return-V(this).m();let E=0,p=1;for(let _=0;_<this.g.length;_++){const I=this.i(_);E+=(I>=0?I:4294967296+I)*p,p*=4294967296}return E},n.toString=function(E){if(E=E||10,E<2||36<E)throw Error("radix out of range: "+E);if(k(this))return"0";if(M(this))return"-"+V(this).toString(E);const p=d(Math.pow(E,6));var _=this;let I="";for(;;){const y=_t(_,p).g;_=z(_,y.j(p));let A=((_.g.length>0?_.g[0]:_.h)>>>0).toString(E);if(_=y,k(_))return A+I;for(;A.length<6;)A="0"+A;I=A+I}},n.i=function(E){return E<0?0:E<this.g.length?this.g[E]:this.h};function k(E){if(E.h!=0)return!1;for(let p=0;p<E.g.length;p++)if(E.g[p]!=0)return!1;return!0}function M(E){return E.h==-1}n.l=function(E){return E=z(this,E),M(E)?-1:k(E)?0:1};function V(E){const p=E.g.length,_=[];for(let I=0;I<p;I++)_[I]=~E.g[I];return new a(_,~E.h).add(v)}n.abs=function(){return M(this)?V(this):this},n.add=function(E){const p=Math.max(this.g.length,E.g.length),_=[];let I=0;for(let y=0;y<=p;y++){let A=I+(this.i(y)&65535)+(E.i(y)&65535),g=(A>>>16)+(this.i(y)>>>16)+(E.i(y)>>>16);I=g>>>16,A&=65535,g&=65535,_[y]=g<<16|A}return new a(_,_[_.length-1]&-2147483648?-1:0)};function z(E,p){return E.add(V(p))}n.j=function(E){if(k(this)||k(E))return T;if(M(this))return M(E)?V(this).j(V(E)):V(V(this).j(E));if(M(E))return V(this.j(V(E)));if(this.l(b)<0&&E.l(b)<0)return d(this.m()*E.m());const p=this.g.length+E.g.length,_=[];for(var I=0;I<2*p;I++)_[I]=0;for(I=0;I<this.g.length;I++)for(let y=0;y<E.g.length;y++){const A=this.i(I)>>>16,g=this.i(I)&65535,wt=E.i(y)>>>16,de=E.i(y)&65535;_[2*I+2*y]+=g*de,G(_,2*I+2*y),_[2*I+2*y+1]+=A*de,G(_,2*I+2*y+1),_[2*I+2*y+1]+=g*wt,G(_,2*I+2*y+1),_[2*I+2*y+2]+=A*wt,G(_,2*I+2*y+2)}for(E=0;E<p;E++)_[E]=_[2*E+1]<<16|_[2*E];for(E=p;E<2*p;E++)_[E]=0;return new a(_,0)};function G(E,p){for(;(E[p]&65535)!=E[p];)E[p+1]+=E[p]>>>16,E[p]&=65535,p++}function H(E,p){this.g=E,this.h=p}function _t(E,p){if(k(p))throw Error("division by zero");if(k(E))return new H(T,T);if(M(E))return p=_t(V(E),p),new H(V(p.g),V(p.h));if(M(p))return p=_t(E,V(p)),new H(V(p.g),p.h);if(E.g.length>30){if(M(E)||M(p))throw Error("slowDivide_ only works with positive integers.");for(var _=v,I=p;I.l(E)<=0;)_=It(_),I=It(I);var y=at(_,1),A=at(I,1);for(I=at(I,2),_=at(_,2);!k(I);){var g=A.add(I);g.l(E)<=0&&(y=y.add(_),A=g),I=at(I,1),_=at(_,1)}return p=z(E,y.j(p)),new H(y,p)}for(y=T;E.l(p)>=0;){for(_=Math.max(1,Math.floor(E.m()/p.m())),I=Math.ceil(Math.log(_)/Math.LN2),I=I<=48?1:Math.pow(2,I-48),A=d(_),g=A.j(p);M(g)||g.l(E)>0;)_-=I,A=d(_),g=A.j(p);k(A)&&(A=v),y=y.add(A),E=z(E,g)}return new H(y,E)}n.B=function(E){return _t(this,E).h},n.and=function(E){const p=Math.max(this.g.length,E.g.length),_=[];for(let I=0;I<p;I++)_[I]=this.i(I)&E.i(I);return new a(_,this.h&E.h)},n.or=function(E){const p=Math.max(this.g.length,E.g.length),_=[];for(let I=0;I<p;I++)_[I]=this.i(I)|E.i(I);return new a(_,this.h|E.h)},n.xor=function(E){const p=Math.max(this.g.length,E.g.length),_=[];for(let I=0;I<p;I++)_[I]=this.i(I)^E.i(I);return new a(_,this.h^E.h)};function It(E){const p=E.g.length+1,_=[];for(let I=0;I<p;I++)_[I]=E.i(I)<<1|E.i(I-1)>>>31;return new a(_,E.h)}function at(E,p){const _=p>>5;p%=32;const I=E.g.length-_,y=[];for(let A=0;A<I;A++)y[A]=p>0?E.i(A+_)>>>p|E.i(A+_+1)<<32-p:E.i(A+_);return new a(y,E.h)}r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,pc=r,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.B,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=d,a.fromString=m,te=a}).apply(typeof ta<"u"?ta:typeof self<"u"?self:typeof window<"u"?window:{});var Jn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var gc,hn,_c,rr,ks,yc,Ec,Tc;(function(){var n,t=Object.defineProperty;function e(i){i=[typeof globalThis=="object"&&globalThis,i,typeof window=="object"&&window,typeof self=="object"&&self,typeof Jn=="object"&&Jn];for(var c=0;c<i.length;++c){var l=i[c];if(l&&l.Math==Math)return l}throw Error("Cannot find global object")}var r=e(this);function s(i,c){if(c)t:{var l=r;i=i.split(".");for(var f=0;f<i.length-1;f++){var w=i[f];if(!(w in l))break t;l=l[w]}i=i[i.length-1],f=l[i],c=c(f),c!=f&&c!=null&&t(l,i,{configurable:!0,writable:!0,value:c})}}s("Symbol.dispose",function(i){return i||Symbol("Symbol.dispose")}),s("Array.prototype.values",function(i){return i||function(){return this[Symbol.iterator]()}}),s("Object.entries",function(i){return i||function(c){var l=[],f;for(f in c)Object.prototype.hasOwnProperty.call(c,f)&&l.push([f,c[f]]);return l}});var o=o||{},a=this||self;function u(i){var c=typeof i;return c=="object"&&i!=null||c=="function"}function h(i,c,l){return i.call.apply(i.bind,arguments)}function d(i,c,l){return d=h,d.apply(null,arguments)}function m(i,c){var l=Array.prototype.slice.call(arguments,1);return function(){var f=l.slice();return f.push.apply(f,arguments),i.apply(this,f)}}function T(i,c){function l(){}l.prototype=c.prototype,i.Z=c.prototype,i.prototype=new l,i.prototype.constructor=i,i.Ob=function(f,w,R){for(var P=Array(arguments.length-2),U=2;U<arguments.length;U++)P[U-2]=arguments[U];return c.prototype[w].apply(f,P)}}var v=typeof AsyncContext<"u"&&typeof AsyncContext.Snapshot=="function"?i=>i&&AsyncContext.Snapshot.wrap(i):i=>i;function b(i){const c=i.length;if(c>0){const l=Array(c);for(let f=0;f<c;f++)l[f]=i[f];return l}return[]}function k(i,c){for(let f=1;f<arguments.length;f++){const w=arguments[f];var l=typeof w;if(l=l!="object"?l:w?Array.isArray(w)?"array":l:"null",l=="array"||l=="object"&&typeof w.length=="number"){l=i.length||0;const R=w.length||0;i.length=l+R;for(let P=0;P<R;P++)i[l+P]=w[P]}else i.push(w)}}class M{constructor(c,l){this.i=c,this.j=l,this.h=0,this.g=null}get(){let c;return this.h>0?(this.h--,c=this.g,this.g=c.next,c.next=null):c=this.i(),c}}function V(i){a.setTimeout(()=>{throw i},0)}function z(){var i=E;let c=null;return i.g&&(c=i.g,i.g=i.g.next,i.g||(i.h=null),c.next=null),c}class G{constructor(){this.h=this.g=null}add(c,l){const f=H.get();f.set(c,l),this.h?this.h.next=f:this.g=f,this.h=f}}var H=new M(()=>new _t,i=>i.reset());class _t{constructor(){this.next=this.g=this.h=null}set(c,l){this.h=c,this.g=l,this.next=null}reset(){this.next=this.g=this.h=null}}let It,at=!1,E=new G,p=()=>{const i=Promise.resolve(void 0);It=()=>{i.then(_)}};function _(){for(var i;i=z();){try{i.h.call(i.g)}catch(l){V(l)}var c=H;c.j(i),c.h<100&&(c.h++,i.next=c.g,c.g=i)}at=!1}function I(){this.u=this.u,this.C=this.C}I.prototype.u=!1,I.prototype.dispose=function(){this.u||(this.u=!0,this.N())},I.prototype[Symbol.dispose]=function(){this.dispose()},I.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function y(i,c){this.type=i,this.g=this.target=c,this.defaultPrevented=!1}y.prototype.h=function(){this.defaultPrevented=!0};var A=(function(){if(!a.addEventListener||!Object.defineProperty)return!1;var i=!1,c=Object.defineProperty({},"passive",{get:function(){i=!0}});try{const l=()=>{};a.addEventListener("test",l,c),a.removeEventListener("test",l,c)}catch{}return i})();function g(i){return/^[\s\xa0]*$/.test(i)}function wt(i,c){y.call(this,i?i.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,i&&this.init(i,c)}T(wt,y),wt.prototype.init=function(i,c){const l=this.type=i.type,f=i.changedTouches&&i.changedTouches.length?i.changedTouches[0]:null;this.target=i.target||i.srcElement,this.g=c,c=i.relatedTarget,c||(l=="mouseover"?c=i.fromElement:l=="mouseout"&&(c=i.toElement)),this.relatedTarget=c,f?(this.clientX=f.clientX!==void 0?f.clientX:f.pageX,this.clientY=f.clientY!==void 0?f.clientY:f.pageY,this.screenX=f.screenX||0,this.screenY=f.screenY||0):(this.clientX=i.clientX!==void 0?i.clientX:i.pageX,this.clientY=i.clientY!==void 0?i.clientY:i.pageY,this.screenX=i.screenX||0,this.screenY=i.screenY||0),this.button=i.button,this.key=i.key||"",this.ctrlKey=i.ctrlKey,this.altKey=i.altKey,this.shiftKey=i.shiftKey,this.metaKey=i.metaKey,this.pointerId=i.pointerId||0,this.pointerType=i.pointerType,this.state=i.state,this.i=i,i.defaultPrevented&&wt.Z.h.call(this)},wt.prototype.h=function(){wt.Z.h.call(this);const i=this.i;i.preventDefault?i.preventDefault():i.returnValue=!1};var de="closure_listenable_"+(Math.random()*1e6|0),hl=0;function dl(i,c,l,f,w){this.listener=i,this.proxy=null,this.src=c,this.type=l,this.capture=!!f,this.ha=w,this.key=++hl,this.da=this.fa=!1}function Ln(i){i.da=!0,i.listener=null,i.proxy=null,i.src=null,i.ha=null}function Fn(i,c,l){for(const f in i)c.call(l,i[f],f,i)}function fl(i,c){for(const l in i)c.call(void 0,i[l],l,i)}function Bi(i){const c={};for(const l in i)c[l]=i[l];return c}const ji="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function qi(i,c){let l,f;for(let w=1;w<arguments.length;w++){f=arguments[w];for(l in f)i[l]=f[l];for(let R=0;R<ji.length;R++)l=ji[R],Object.prototype.hasOwnProperty.call(f,l)&&(i[l]=f[l])}}function Un(i){this.src=i,this.g={},this.h=0}Un.prototype.add=function(i,c,l,f,w){const R=i.toString();i=this.g[R],i||(i=this.g[R]=[],this.h++);const P=Hr(i,c,f,w);return P>-1?(c=i[P],l||(c.fa=!1)):(c=new dl(c,this.src,R,!!f,w),c.fa=l,i.push(c)),c};function Gr(i,c){const l=c.type;if(l in i.g){var f=i.g[l],w=Array.prototype.indexOf.call(f,c,void 0),R;(R=w>=0)&&Array.prototype.splice.call(f,w,1),R&&(Ln(c),i.g[l].length==0&&(delete i.g[l],i.h--))}}function Hr(i,c,l,f){for(let w=0;w<i.length;++w){const R=i[w];if(!R.da&&R.listener==c&&R.capture==!!l&&R.ha==f)return w}return-1}var Kr="closure_lm_"+(Math.random()*1e6|0),Wr={};function $i(i,c,l,f,w){if(Array.isArray(c)){for(let R=0;R<c.length;R++)$i(i,c[R],l,f,w);return null}return l=Hi(l),i&&i[de]?i.J(c,l,u(f)?!!f.capture:!1,w):ml(i,c,l,!1,f,w)}function ml(i,c,l,f,w,R){if(!c)throw Error("Invalid event type");const P=u(w)?!!w.capture:!!w;let U=Xr(i);if(U||(i[Kr]=U=new Un(i)),l=U.add(c,l,f,P,R),l.proxy)return l;if(f=pl(),l.proxy=f,f.src=i,f.listener=l,i.addEventListener)A||(w=P),w===void 0&&(w=!1),i.addEventListener(c.toString(),f,w);else if(i.attachEvent)i.attachEvent(Gi(c.toString()),f);else if(i.addListener&&i.removeListener)i.addListener(f);else throw Error("addEventListener and attachEvent are unavailable.");return l}function pl(){function i(l){return c.call(i.src,i.listener,l)}const c=gl;return i}function zi(i,c,l,f,w){if(Array.isArray(c))for(var R=0;R<c.length;R++)zi(i,c[R],l,f,w);else f=u(f)?!!f.capture:!!f,l=Hi(l),i&&i[de]?(i=i.i,R=String(c).toString(),R in i.g&&(c=i.g[R],l=Hr(c,l,f,w),l>-1&&(Ln(c[l]),Array.prototype.splice.call(c,l,1),c.length==0&&(delete i.g[R],i.h--)))):i&&(i=Xr(i))&&(c=i.g[c.toString()],i=-1,c&&(i=Hr(c,l,f,w)),(l=i>-1?c[i]:null)&&Qr(l))}function Qr(i){if(typeof i!="number"&&i&&!i.da){var c=i.src;if(c&&c[de])Gr(c.i,i);else{var l=i.type,f=i.proxy;c.removeEventListener?c.removeEventListener(l,f,i.capture):c.detachEvent?c.detachEvent(Gi(l),f):c.addListener&&c.removeListener&&c.removeListener(f),(l=Xr(c))?(Gr(l,i),l.h==0&&(l.src=null,c[Kr]=null)):Ln(i)}}}function Gi(i){return i in Wr?Wr[i]:Wr[i]="on"+i}function gl(i,c){if(i.da)i=!0;else{c=new wt(c,this);const l=i.listener,f=i.ha||i.src;i.fa&&Qr(i),i=l.call(f,c)}return i}function Xr(i){return i=i[Kr],i instanceof Un?i:null}var Yr="__closure_events_fn_"+(Math.random()*1e9>>>0);function Hi(i){return typeof i=="function"?i:(i[Yr]||(i[Yr]=function(c){return i.handleEvent(c)}),i[Yr])}function ft(){I.call(this),this.i=new Un(this),this.M=this,this.G=null}T(ft,I),ft.prototype[de]=!0,ft.prototype.removeEventListener=function(i,c,l,f){zi(this,i,c,l,f)};function yt(i,c){var l,f=i.G;if(f)for(l=[];f;f=f.G)l.push(f);if(i=i.M,f=c.type||c,typeof c=="string")c=new y(c,i);else if(c instanceof y)c.target=c.target||i;else{var w=c;c=new y(f,i),qi(c,w)}w=!0;let R,P;if(l)for(P=l.length-1;P>=0;P--)R=c.g=l[P],w=Bn(R,f,!0,c)&&w;if(R=c.g=i,w=Bn(R,f,!0,c)&&w,w=Bn(R,f,!1,c)&&w,l)for(P=0;P<l.length;P++)R=c.g=l[P],w=Bn(R,f,!1,c)&&w}ft.prototype.N=function(){if(ft.Z.N.call(this),this.i){var i=this.i;for(const c in i.g){const l=i.g[c];for(let f=0;f<l.length;f++)Ln(l[f]);delete i.g[c],i.h--}}this.G=null},ft.prototype.J=function(i,c,l,f){return this.i.add(String(i),c,!1,l,f)},ft.prototype.K=function(i,c,l,f){return this.i.add(String(i),c,!0,l,f)};function Bn(i,c,l,f){if(c=i.i.g[String(c)],!c)return!0;c=c.concat();let w=!0;for(let R=0;R<c.length;++R){const P=c[R];if(P&&!P.da&&P.capture==l){const U=P.listener,rt=P.ha||P.src;P.fa&&Gr(i.i,P),w=U.call(rt,f)!==!1&&w}}return w&&!f.defaultPrevented}function _l(i,c){if(typeof i!="function")if(i&&typeof i.handleEvent=="function")i=d(i.handleEvent,i);else throw Error("Invalid listener argument");return Number(c)>2147483647?-1:a.setTimeout(i,c||0)}function Ki(i){i.g=_l(()=>{i.g=null,i.i&&(i.i=!1,Ki(i))},i.l);const c=i.h;i.h=null,i.m.apply(null,c)}class yl extends I{constructor(c,l){super(),this.m=c,this.l=l,this.h=null,this.i=!1,this.g=null}j(c){this.h=arguments,this.g?this.i=!0:Ki(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function We(i){I.call(this),this.h=i,this.g={}}T(We,I);var Wi=[];function Qi(i){Fn(i.g,function(c,l){this.g.hasOwnProperty(l)&&Qr(c)},i),i.g={}}We.prototype.N=function(){We.Z.N.call(this),Qi(this)},We.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Jr=a.JSON.stringify,El=a.JSON.parse,Tl=class{stringify(i){return a.JSON.stringify(i,void 0)}parse(i){return a.JSON.parse(i,void 0)}};function Xi(){}function Yi(){}var Qe={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Zr(){y.call(this,"d")}T(Zr,y);function ts(){y.call(this,"c")}T(ts,y);var fe={},Ji=null;function jn(){return Ji=Ji||new ft}fe.Ia="serverreachability";function Zi(i){y.call(this,fe.Ia,i)}T(Zi,y);function Xe(i){const c=jn();yt(c,new Zi(c))}fe.STAT_EVENT="statevent";function to(i,c){y.call(this,fe.STAT_EVENT,i),this.stat=c}T(to,y);function Et(i){const c=jn();yt(c,new to(c,i))}fe.Ja="timingevent";function eo(i,c){y.call(this,fe.Ja,i),this.size=c}T(eo,y);function Ye(i,c){if(typeof i!="function")throw Error("Fn must not be null and must be a function");return a.setTimeout(function(){i()},c)}function Je(){this.g=!0}Je.prototype.ua=function(){this.g=!1};function Il(i,c,l,f,w,R){i.info(function(){if(i.g)if(R){var P="",U=R.split("&");for(let W=0;W<U.length;W++){var rt=U[W].split("=");if(rt.length>1){const ct=rt[0];rt=rt[1];const Vt=ct.split("_");P=Vt.length>=2&&Vt[1]=="type"?P+(ct+"="+rt+"&"):P+(ct+"=redacted&")}}}else P=null;else P=R;return"XMLHTTP REQ ("+f+") [attempt "+w+"]: "+c+`
16
+ `+l+`
17
+ `+P})}function wl(i,c,l,f,w,R,P){i.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+w+"]: "+c+`
18
+ `+l+`
19
+ `+R+" "+P})}function Pe(i,c,l,f){i.info(function(){return"XMLHTTP TEXT ("+c+"): "+Al(i,l)+(f?" "+f:"")})}function vl(i,c){i.info(function(){return"TIMEOUT: "+c})}Je.prototype.info=function(){};function Al(i,c){if(!i.g)return c;if(!c)return null;try{const R=JSON.parse(c);if(R){for(i=0;i<R.length;i++)if(Array.isArray(R[i])){var l=R[i];if(!(l.length<2)){var f=l[1];if(Array.isArray(f)&&!(f.length<1)){var w=f[0];if(w!="noop"&&w!="stop"&&w!="close")for(let P=1;P<f.length;P++)f[P]=""}}}}return Jr(R)}catch{return c}}var qn={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},no={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"},ro;function es(){}T(es,Xi),es.prototype.g=function(){return new XMLHttpRequest},ro=new es;function Ze(i){return encodeURIComponent(String(i))}function Rl(i){var c=1;i=i.split(":");const l=[];for(;c>0&&i.length;)l.push(i.shift()),c--;return i.length&&l.push(i.join(":")),l}function Gt(i,c,l,f){this.j=i,this.i=c,this.l=l,this.S=f||1,this.V=new We(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new so}function so(){this.i=null,this.g="",this.h=!1}var io={},ns={};function rs(i,c,l){i.M=1,i.A=zn(Pt(c)),i.u=l,i.R=!0,oo(i,null)}function oo(i,c){i.F=Date.now(),$n(i),i.B=Pt(i.A);var l=i.B,f=i.S;Array.isArray(f)||(f=[String(f)]),To(l.i,"t",f),i.C=0,l=i.j.L,i.h=new so,i.g=Fo(i.j,l?c:null,!i.u),i.P>0&&(i.O=new yl(d(i.Y,i,i.g),i.P)),c=i.V,l=i.g,f=i.ba;var w="readystatechange";Array.isArray(w)||(w&&(Wi[0]=w.toString()),w=Wi);for(let R=0;R<w.length;R++){const P=$i(l,w[R],f||c.handleEvent,!1,c.h||c);if(!P)break;c.g[P.key]=P}c=i.J?Bi(i.J):{},i.u?(i.v||(i.v="POST"),c["Content-Type"]="application/x-www-form-urlencoded",i.g.ea(i.B,i.v,i.u,c)):(i.v="GET",i.g.ea(i.B,i.v,null,c)),Xe(),Il(i.i,i.v,i.B,i.l,i.S,i.u)}Gt.prototype.ba=function(i){i=i.target;const c=this.O;c&&Wt(i)==3?c.j():this.Y(i)},Gt.prototype.Y=function(i){try{if(i==this.g)t:{const U=Wt(this.g),rt=this.g.ya(),W=this.g.ca();if(!(U<3)&&(U!=3||this.g&&(this.h.h||this.g.la()||Co(this.g)))){this.K||U!=4||rt==7||(rt==8||W<=0?Xe(3):Xe(2)),ss(this);var c=this.g.ca();this.X=c;var l=Sl(this);if(this.o=c==200,wl(this.i,this.v,this.B,this.l,this.S,U,c),this.o){if(this.U&&!this.L){e:{if(this.g){var f,w=this.g;if((f=w.g?w.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!g(f)){var R=f;break e}}R=null}if(i=R)Pe(this.i,this.l,i,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,is(this,i);else{this.o=!1,this.m=3,Et(12),me(this),tn(this);break t}}if(this.R){i=!0;let ct;for(;!this.K&&this.C<l.length;)if(ct=Cl(this,l),ct==ns){U==4&&(this.m=4,Et(14),i=!1),Pe(this.i,this.l,null,"[Incomplete Response]");break}else if(ct==io){this.m=4,Et(15),Pe(this.i,this.l,l,"[Invalid Chunk]"),i=!1;break}else Pe(this.i,this.l,ct,null),is(this,ct);if(ao(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),U!=4||l.length!=0||this.h.h||(this.m=1,Et(16),i=!1),this.o=this.o&&i,!i)Pe(this.i,this.l,l,"[Invalid Chunked Response]"),me(this),tn(this);else if(l.length>0&&!this.W){this.W=!0;var P=this.j;P.g==this&&P.aa&&!P.P&&(P.j.info("Great, no buffering proxy detected. Bytes received: "+l.length),fs(P),P.P=!0,Et(11))}}else Pe(this.i,this.l,l,null),is(this,l);U==4&&me(this),this.o&&!this.K&&(U==4?Mo(this.j,this):(this.o=!1,$n(this)))}else jl(this.g),c==400&&l.indexOf("Unknown SID")>0?(this.m=3,Et(12)):(this.m=0,Et(13)),me(this),tn(this)}}}catch{}};function Sl(i){if(!ao(i))return i.g.la();const c=Co(i.g);if(c==="")return"";let l="";const f=c.length,w=Wt(i.g)==4;if(!i.h.i){if(typeof TextDecoder>"u")return me(i),tn(i),"";i.h.i=new a.TextDecoder}for(let R=0;R<f;R++)i.h.h=!0,l+=i.h.i.decode(c[R],{stream:!(w&&R==f-1)});return c.length=0,i.h.g+=l,i.C=0,i.h.g}function ao(i){return i.g?i.v=="GET"&&i.M!=2&&i.j.Aa:!1}function Cl(i,c){var l=i.C,f=c.indexOf(`
20
+ `,l);return f==-1?ns:(l=Number(c.substring(l,f)),isNaN(l)?io:(f+=1,f+l>c.length?ns:(c=c.slice(f,f+l),i.C=f+l,c)))}Gt.prototype.cancel=function(){this.K=!0,me(this)};function $n(i){i.T=Date.now()+i.H,co(i,i.H)}function co(i,c){if(i.D!=null)throw Error("WatchDog timer not null");i.D=Ye(d(i.aa,i),c)}function ss(i){i.D&&(a.clearTimeout(i.D),i.D=null)}Gt.prototype.aa=function(){this.D=null;const i=Date.now();i-this.T>=0?(vl(this.i,this.B),this.M!=2&&(Xe(),Et(17)),me(this),this.m=2,tn(this)):co(this,this.T-i)};function tn(i){i.j.I==0||i.K||Mo(i.j,i)}function me(i){ss(i);var c=i.O;c&&typeof c.dispose=="function"&&c.dispose(),i.O=null,Qi(i.V),i.g&&(c=i.g,i.g=null,c.abort(),c.dispose())}function is(i,c){try{var l=i.j;if(l.I!=0&&(l.g==i||os(l.h,i))){if(!i.L&&os(l.h,i)&&l.I==3){try{var f=l.Ba.g.parse(c)}catch{f=null}if(Array.isArray(f)&&f.length==3){var w=f;if(w[0]==0){t:if(!l.v){if(l.g)if(l.g.F+3e3<i.F)Qn(l),Kn(l);else break t;ds(l),Et(18)}}else l.xa=w[1],0<l.xa-l.K&&w[2]<37500&&l.F&&l.A==0&&!l.C&&(l.C=Ye(d(l.Va,l),6e3));ho(l.h)<=1&&l.ta&&(l.ta=void 0)}else ge(l,11)}else if((i.L||l.g==i)&&Qn(l),!g(c))for(w=l.Ba.g.parse(c),c=0;c<w.length;c++){let W=w[c];const ct=W[0];if(!(ct<=l.K))if(l.K=ct,W=W[1],l.I==2)if(W[0]=="c"){l.M=W[1],l.ba=W[2];const Vt=W[3];Vt!=null&&(l.ka=Vt,l.j.info("VER="+l.ka));const _e=W[4];_e!=null&&(l.za=_e,l.j.info("SVER="+l.za));const Qt=W[5];Qt!=null&&typeof Qt=="number"&&Qt>0&&(f=1.5*Qt,l.O=f,l.j.info("backChannelRequestTimeoutMs_="+f)),f=l;const Xt=i.g;if(Xt){const Yn=Xt.g?Xt.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Yn){var R=f.h;R.g||Yn.indexOf("spdy")==-1&&Yn.indexOf("quic")==-1&&Yn.indexOf("h2")==-1||(R.j=R.l,R.g=new Set,R.h&&(as(R,R.h),R.h=null))}if(f.G){const ms=Xt.g?Xt.g.getResponseHeader("X-HTTP-Session-Id"):null;ms&&(f.wa=ms,Q(f.J,f.G,ms))}}l.I=3,l.l&&l.l.ra(),l.aa&&(l.T=Date.now()-i.F,l.j.info("Handshake RTT: "+l.T+"ms")),f=l;var P=i;if(f.na=Lo(f,f.L?f.ba:null,f.W),P.L){fo(f.h,P);var U=P,rt=f.O;rt&&(U.H=rt),U.D&&(ss(U),$n(U)),f.g=P}else ko(f);l.i.length>0&&Wn(l)}else W[0]!="stop"&&W[0]!="close"||ge(l,7);else l.I==3&&(W[0]=="stop"||W[0]=="close"?W[0]=="stop"?ge(l,7):hs(l):W[0]!="noop"&&l.l&&l.l.qa(W),l.A=0)}}Xe(4)}catch{}}var bl=class{constructor(i,c){this.g=i,this.map=c}};function uo(i){this.l=i||10,a.PerformanceNavigationTiming?(i=a.performance.getEntriesByType("navigation"),i=i.length>0&&(i[0].nextHopProtocol=="hq"||i[0].nextHopProtocol=="h2")):i=!!(a.chrome&&a.chrome.loadTimes&&a.chrome.loadTimes()&&a.chrome.loadTimes().wasFetchedViaSpdy),this.j=i?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function lo(i){return i.h?!0:i.g?i.g.size>=i.j:!1}function ho(i){return i.h?1:i.g?i.g.size:0}function os(i,c){return i.h?i.h==c:i.g?i.g.has(c):!1}function as(i,c){i.g?i.g.add(c):i.h=c}function fo(i,c){i.h&&i.h==c?i.h=null:i.g&&i.g.has(c)&&i.g.delete(c)}uo.prototype.cancel=function(){if(this.i=mo(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(const i of this.g.values())i.cancel();this.g.clear()}};function mo(i){if(i.h!=null)return i.i.concat(i.h.G);if(i.g!=null&&i.g.size!==0){let c=i.i;for(const l of i.g.values())c=c.concat(l.G);return c}return b(i.i)}var po=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Pl(i,c){if(i){i=i.split("&");for(let l=0;l<i.length;l++){const f=i[l].indexOf("=");let w,R=null;f>=0?(w=i[l].substring(0,f),R=i[l].substring(f+1)):w=i[l],c(w,R?decodeURIComponent(R.replace(/\+/g," ")):"")}}}function Ht(i){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let c;i instanceof Ht?(this.l=i.l,en(this,i.j),this.o=i.o,this.g=i.g,nn(this,i.u),this.h=i.h,cs(this,Io(i.i)),this.m=i.m):i&&(c=String(i).match(po))?(this.l=!1,en(this,c[1]||"",!0),this.o=rn(c[2]||""),this.g=rn(c[3]||"",!0),nn(this,c[4]),this.h=rn(c[5]||"",!0),cs(this,c[6]||"",!0),this.m=rn(c[7]||"")):(this.l=!1,this.i=new on(null,this.l))}Ht.prototype.toString=function(){const i=[];var c=this.j;c&&i.push(sn(c,go,!0),":");var l=this.g;return(l||c=="file")&&(i.push("//"),(c=this.o)&&i.push(sn(c,go,!0),"@"),i.push(Ze(l).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),l=this.u,l!=null&&i.push(":",String(l))),(l=this.h)&&(this.g&&l.charAt(0)!="/"&&i.push("/"),i.push(sn(l,l.charAt(0)=="/"?kl:Dl,!0))),(l=this.i.toString())&&i.push("?",l),(l=this.m)&&i.push("#",sn(l,Ml)),i.join("")},Ht.prototype.resolve=function(i){const c=Pt(this);let l=!!i.j;l?en(c,i.j):l=!!i.o,l?c.o=i.o:l=!!i.g,l?c.g=i.g:l=i.u!=null;var f=i.h;if(l)nn(c,i.u);else if(l=!!i.h){if(f.charAt(0)!="/")if(this.g&&!this.h)f="/"+f;else{var w=c.h.lastIndexOf("/");w!=-1&&(f=c.h.slice(0,w+1)+f)}if(w=f,w==".."||w==".")f="";else if(w.indexOf("./")!=-1||w.indexOf("/.")!=-1){f=w.lastIndexOf("/",0)==0,w=w.split("/");const R=[];for(let P=0;P<w.length;){const U=w[P++];U=="."?f&&P==w.length&&R.push(""):U==".."?((R.length>1||R.length==1&&R[0]!="")&&R.pop(),f&&P==w.length&&R.push("")):(R.push(U),f=!0)}f=R.join("/")}else f=w}return l?c.h=f:l=i.i.toString()!=="",l?cs(c,Io(i.i)):l=!!i.m,l&&(c.m=i.m),c};function Pt(i){return new Ht(i)}function en(i,c,l){i.j=l?rn(c,!0):c,i.j&&(i.j=i.j.replace(/:$/,""))}function nn(i,c){if(c){if(c=Number(c),isNaN(c)||c<0)throw Error("Bad port number "+c);i.u=c}else i.u=null}function cs(i,c,l){c instanceof on?(i.i=c,xl(i.i,i.l)):(l||(c=sn(c,Nl)),i.i=new on(c,i.l))}function Q(i,c,l){i.i.set(c,l)}function zn(i){return Q(i,"zx",Math.floor(Math.random()*2147483648).toString(36)+Math.abs(Math.floor(Math.random()*2147483648)^Date.now()).toString(36)),i}function rn(i,c){return i?c?decodeURI(i.replace(/%25/g,"%2525")):decodeURIComponent(i):""}function sn(i,c,l){return typeof i=="string"?(i=encodeURI(i).replace(c,Vl),l&&(i=i.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),i):null}function Vl(i){return i=i.charCodeAt(0),"%"+(i>>4&15).toString(16)+(i&15).toString(16)}var go=/[#\/\?@]/g,Dl=/[#\?:]/g,kl=/[#\?]/g,Nl=/[#\?@]/g,Ml=/#/g;function on(i,c){this.h=this.g=null,this.i=i||null,this.j=!!c}function pe(i){i.g||(i.g=new Map,i.h=0,i.i&&Pl(i.i,function(c,l){i.add(decodeURIComponent(c.replace(/\+/g," ")),l)}))}n=on.prototype,n.add=function(i,c){pe(this),this.i=null,i=Ve(this,i);let l=this.g.get(i);return l||this.g.set(i,l=[]),l.push(c),this.h+=1,this};function _o(i,c){pe(i),c=Ve(i,c),i.g.has(c)&&(i.i=null,i.h-=i.g.get(c).length,i.g.delete(c))}function yo(i,c){return pe(i),c=Ve(i,c),i.g.has(c)}n.forEach=function(i,c){pe(this),this.g.forEach(function(l,f){l.forEach(function(w){i.call(c,w,f,this)},this)},this)};function Eo(i,c){pe(i);let l=[];if(typeof c=="string")yo(i,c)&&(l=l.concat(i.g.get(Ve(i,c))));else for(i=Array.from(i.g.values()),c=0;c<i.length;c++)l=l.concat(i[c]);return l}n.set=function(i,c){return pe(this),this.i=null,i=Ve(this,i),yo(this,i)&&(this.h-=this.g.get(i).length),this.g.set(i,[c]),this.h+=1,this},n.get=function(i,c){return i?(i=Eo(this,i),i.length>0?String(i[0]):c):c};function To(i,c,l){_o(i,c),l.length>0&&(i.i=null,i.g.set(Ve(i,c),b(l)),i.h+=l.length)}n.toString=function(){if(this.i)return this.i;if(!this.g)return"";const i=[],c=Array.from(this.g.keys());for(let f=0;f<c.length;f++){var l=c[f];const w=Ze(l);l=Eo(this,l);for(let R=0;R<l.length;R++){let P=w;l[R]!==""&&(P+="="+Ze(l[R])),i.push(P)}}return this.i=i.join("&")};function Io(i){const c=new on;return c.i=i.i,i.g&&(c.g=new Map(i.g),c.h=i.h),c}function Ve(i,c){return c=String(c),i.j&&(c=c.toLowerCase()),c}function xl(i,c){c&&!i.j&&(pe(i),i.i=null,i.g.forEach(function(l,f){const w=f.toLowerCase();f!=w&&(_o(this,f),To(this,w,l))},i)),i.j=c}function Ol(i,c){const l=new Je;if(a.Image){const f=new Image;f.onload=m(Kt,l,"TestLoadImage: loaded",!0,c,f),f.onerror=m(Kt,l,"TestLoadImage: error",!1,c,f),f.onabort=m(Kt,l,"TestLoadImage: abort",!1,c,f),f.ontimeout=m(Kt,l,"TestLoadImage: timeout",!1,c,f),a.setTimeout(function(){f.ontimeout&&f.ontimeout()},1e4),f.src=i}else c(!1)}function Ll(i,c){const l=new Je,f=new AbortController,w=setTimeout(()=>{f.abort(),Kt(l,"TestPingServer: timeout",!1,c)},1e4);fetch(i,{signal:f.signal}).then(R=>{clearTimeout(w),R.ok?Kt(l,"TestPingServer: ok",!0,c):Kt(l,"TestPingServer: server error",!1,c)}).catch(()=>{clearTimeout(w),Kt(l,"TestPingServer: error",!1,c)})}function Kt(i,c,l,f,w){try{w&&(w.onload=null,w.onerror=null,w.onabort=null,w.ontimeout=null),f(l)}catch{}}function Fl(){this.g=new Tl}function us(i){this.i=i.Sb||null,this.h=i.ab||!1}T(us,Xi),us.prototype.g=function(){return new Gn(this.i,this.h)};function Gn(i,c){ft.call(this),this.H=i,this.o=c,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}T(Gn,ft),n=Gn.prototype,n.open=function(i,c){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.F=i,this.D=c,this.readyState=1,cn(this)},n.send=function(i){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;const c={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};i&&(c.body=i),(this.H||a).fetch(new Request(this.D,c)).then(this.Pa.bind(this),this.ga.bind(this))},n.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&this.readyState!=4&&(this.g=!1,an(this)),this.readyState=0},n.Pa=function(i){if(this.g&&(this.l=i,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=i.headers,this.readyState=2,cn(this)),this.g&&(this.readyState=3,cn(this),this.g)))if(this.responseType==="arraybuffer")i.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(typeof a.ReadableStream<"u"&&"body"in i){if(this.j=i.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.B=new TextDecoder;wo(this)}else i.text().then(this.Oa.bind(this),this.ga.bind(this))};function wo(i){i.j.read().then(i.Ma.bind(i)).catch(i.ga.bind(i))}n.Ma=function(i){if(this.g){if(this.o&&i.value)this.response.push(i.value);else if(!this.o){var c=i.value?i.value:new Uint8Array(0);(c=this.B.decode(c,{stream:!i.done}))&&(this.response=this.responseText+=c)}i.done?an(this):cn(this),this.readyState==3&&wo(this)}},n.Oa=function(i){this.g&&(this.response=this.responseText=i,an(this))},n.Na=function(i){this.g&&(this.response=i,an(this))},n.ga=function(){this.g&&an(this)};function an(i){i.readyState=4,i.l=null,i.j=null,i.B=null,cn(i)}n.setRequestHeader=function(i,c){this.A.append(i,c)},n.getResponseHeader=function(i){return this.h&&this.h.get(i.toLowerCase())||""},n.getAllResponseHeaders=function(){if(!this.h)return"";const i=[],c=this.h.entries();for(var l=c.next();!l.done;)l=l.value,i.push(l[0]+": "+l[1]),l=c.next();return i.join(`\r
21
+ `)};function cn(i){i.onreadystatechange&&i.onreadystatechange.call(i)}Object.defineProperty(Gn.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(i){this.m=i?"include":"same-origin"}});function vo(i){let c="";return Fn(i,function(l,f){c+=f,c+=":",c+=l,c+=`\r
22
+ `}),c}function ls(i,c,l){t:{for(f in l){var f=!1;break t}f=!0}f||(l=vo(l),typeof i=="string"?l!=null&&Ze(l):Q(i,c,l))}function Z(i){ft.call(this),this.headers=new Map,this.L=i||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}T(Z,ft);var Ul=/^https?$/i,Bl=["POST","PUT"];n=Z.prototype,n.Fa=function(i){this.H=i},n.ea=function(i,c,l,f){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+i);c=c?c.toUpperCase():"GET",this.D=i,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():ro.g(),this.g.onreadystatechange=v(d(this.Ca,this));try{this.B=!0,this.g.open(c,String(i),!0),this.B=!1}catch(R){Ao(this,R);return}if(i=l||"",l=new Map(this.headers),f)if(Object.getPrototypeOf(f)===Object.prototype)for(var w in f)l.set(w,f[w]);else if(typeof f.keys=="function"&&typeof f.get=="function")for(const R of f.keys())l.set(R,f.get(R));else throw Error("Unknown input type for opt_headers: "+String(f));f=Array.from(l.keys()).find(R=>R.toLowerCase()=="content-type"),w=a.FormData&&i instanceof a.FormData,!(Array.prototype.indexOf.call(Bl,c,void 0)>=0)||f||w||l.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[R,P]of l)this.g.setRequestHeader(R,P);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(i),this.v=!1}catch(R){Ao(this,R)}};function Ao(i,c){i.h=!1,i.g&&(i.j=!0,i.g.abort(),i.j=!1),i.l=c,i.o=5,Ro(i),Hn(i)}function Ro(i){i.A||(i.A=!0,yt(i,"complete"),yt(i,"error"))}n.abort=function(i){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=i||7,yt(this,"complete"),yt(this,"abort"),Hn(this))},n.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Hn(this,!0)),Z.Z.N.call(this)},n.Ca=function(){this.u||(this.B||this.v||this.j?So(this):this.Xa())},n.Xa=function(){So(this)};function So(i){if(i.h&&typeof o<"u"){if(i.v&&Wt(i)==4)setTimeout(i.Ca.bind(i),0);else if(yt(i,"readystatechange"),Wt(i)==4){i.h=!1;try{const R=i.ca();t:switch(R){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var c=!0;break t;default:c=!1}var l;if(!(l=c)){var f;if(f=R===0){let P=String(i.D).match(po)[1]||null;!P&&a.self&&a.self.location&&(P=a.self.location.protocol.slice(0,-1)),f=!Ul.test(P?P.toLowerCase():"")}l=f}if(l)yt(i,"complete"),yt(i,"success");else{i.o=6;try{var w=Wt(i)>2?i.g.statusText:""}catch{w=""}i.l=w+" ["+i.ca()+"]",Ro(i)}}finally{Hn(i)}}}}function Hn(i,c){if(i.g){i.m&&(clearTimeout(i.m),i.m=null);const l=i.g;i.g=null,c||yt(i,"ready");try{l.onreadystatechange=null}catch{}}}n.isActive=function(){return!!this.g};function Wt(i){return i.g?i.g.readyState:0}n.ca=function(){try{return Wt(this)>2?this.g.status:-1}catch{return-1}},n.la=function(){try{return this.g?this.g.responseText:""}catch{return""}},n.La=function(i){if(this.g){var c=this.g.responseText;return i&&c.indexOf(i)==0&&(c=c.substring(i.length)),El(c)}};function Co(i){try{if(!i.g)return null;if("response"in i.g)return i.g.response;switch(i.F){case"":case"text":return i.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in i.g)return i.g.mozResponseArrayBuffer}return null}catch{return null}}function jl(i){const c={};i=(i.g&&Wt(i)>=2&&i.g.getAllResponseHeaders()||"").split(`\r
23
+ `);for(let f=0;f<i.length;f++){if(g(i[f]))continue;var l=Rl(i[f]);const w=l[0];if(l=l[1],typeof l!="string")continue;l=l.trim();const R=c[w]||[];c[w]=R,R.push(l)}fl(c,function(f){return f.join(", ")})}n.ya=function(){return this.o},n.Ha=function(){return typeof this.l=="string"?this.l:String(this.l)};function un(i,c,l){return l&&l.internalChannelParams&&l.internalChannelParams[i]||c}function bo(i){this.za=0,this.i=[],this.j=new Je,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=un("failFast",!1,i),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=un("baseRetryDelayMs",5e3,i),this.Za=un("retryDelaySeedMs",1e4,i),this.Ta=un("forwardChannelMaxRetries",2,i),this.va=un("forwardChannelRequestTimeoutMs",2e4,i),this.ma=i&&i.xmlHttpFactory||void 0,this.Ua=i&&i.Rb||void 0,this.Aa=i&&i.useFetchStreams||!1,this.O=void 0,this.L=i&&i.supportsCrossDomainXhr||!1,this.M="",this.h=new uo(i&&i.concurrentRequestLimit),this.Ba=new Fl,this.S=i&&i.fastHandshake||!1,this.R=i&&i.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=i&&i.Pb||!1,i&&i.ua&&this.j.ua(),i&&i.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&i&&i.detectBufferingProxy||!1,this.ia=void 0,i&&i.longPollingTimeout&&i.longPollingTimeout>0&&(this.ia=i.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}n=bo.prototype,n.ka=8,n.I=1,n.connect=function(i,c,l,f){Et(0),this.W=i,this.H=c||{},l&&f!==void 0&&(this.H.OSID=l,this.H.OAID=f),this.F=this.X,this.J=Lo(this,null,this.W),Wn(this)};function hs(i){if(Po(i),i.I==3){var c=i.V++,l=Pt(i.J);if(Q(l,"SID",i.M),Q(l,"RID",c),Q(l,"TYPE","terminate"),ln(i,l),c=new Gt(i,i.j,c),c.M=2,c.A=zn(Pt(l)),l=!1,a.navigator&&a.navigator.sendBeacon)try{l=a.navigator.sendBeacon(c.A.toString(),"")}catch{}!l&&a.Image&&(new Image().src=c.A,l=!0),l||(c.g=Fo(c.j,null),c.g.ea(c.A)),c.F=Date.now(),$n(c)}Oo(i)}function Kn(i){i.g&&(fs(i),i.g.cancel(),i.g=null)}function Po(i){Kn(i),i.v&&(a.clearTimeout(i.v),i.v=null),Qn(i),i.h.cancel(),i.m&&(typeof i.m=="number"&&a.clearTimeout(i.m),i.m=null)}function Wn(i){if(!lo(i.h)&&!i.m){i.m=!0;var c=i.Ea;It||p(),at||(It(),at=!0),E.add(c,i),i.D=0}}function ql(i,c){return ho(i.h)>=i.h.j-(i.m?1:0)?!1:i.m?(i.i=c.G.concat(i.i),!0):i.I==1||i.I==2||i.D>=(i.Sa?0:i.Ta)?!1:(i.m=Ye(d(i.Ea,i,c),xo(i,i.D)),i.D++,!0)}n.Ea=function(i){if(this.m)if(this.m=null,this.I==1){if(!i){this.V=Math.floor(Math.random()*1e5),i=this.V++;const w=new Gt(this,this.j,i);let R=this.o;if(this.U&&(R?(R=Bi(R),qi(R,this.U)):R=this.U),this.u!==null||this.R||(w.J=R,R=null),this.S)t:{for(var c=0,l=0;l<this.i.length;l++){e:{var f=this.i[l];if("__data__"in f.map&&(f=f.map.__data__,typeof f=="string")){f=f.length;break e}f=void 0}if(f===void 0)break;if(c+=f,c>4096){c=l;break t}if(c===4096||l===this.i.length-1){c=l+1;break t}}c=1e3}else c=1e3;c=Do(this,w,c),l=Pt(this.J),Q(l,"RID",i),Q(l,"CVER",22),this.G&&Q(l,"X-HTTP-Session-Id",this.G),ln(this,l),R&&(this.R?c="headers="+Ze(vo(R))+"&"+c:this.u&&ls(l,this.u,R)),as(this.h,w),this.Ra&&Q(l,"TYPE","init"),this.S?(Q(l,"$req",c),Q(l,"SID","null"),w.U=!0,rs(w,l,null)):rs(w,l,c),this.I=2}}else this.I==3&&(i?Vo(this,i):this.i.length==0||lo(this.h)||Vo(this))};function Vo(i,c){var l;c?l=c.l:l=i.V++;const f=Pt(i.J);Q(f,"SID",i.M),Q(f,"RID",l),Q(f,"AID",i.K),ln(i,f),i.u&&i.o&&ls(f,i.u,i.o),l=new Gt(i,i.j,l,i.D+1),i.u===null&&(l.J=i.o),c&&(i.i=c.G.concat(i.i)),c=Do(i,l,1e3),l.H=Math.round(i.va*.5)+Math.round(i.va*.5*Math.random()),as(i.h,l),rs(l,f,c)}function ln(i,c){i.H&&Fn(i.H,function(l,f){Q(c,f,l)}),i.l&&Fn({},function(l,f){Q(c,f,l)})}function Do(i,c,l){l=Math.min(i.i.length,l);const f=i.l?d(i.l.Ka,i.l,i):null;t:{var w=i.i;let U=-1;for(;;){const rt=["count="+l];U==-1?l>0?(U=w[0].g,rt.push("ofs="+U)):U=0:rt.push("ofs="+U);let W=!0;for(let ct=0;ct<l;ct++){var R=w[ct].g;const Vt=w[ct].map;if(R-=U,R<0)U=Math.max(0,w[ct].g-100),W=!1;else try{R="req"+R+"_"||"";try{var P=Vt instanceof Map?Vt:Object.entries(Vt);for(const[_e,Qt]of P){let Xt=Qt;u(Qt)&&(Xt=Jr(Qt)),rt.push(R+_e+"="+encodeURIComponent(Xt))}}catch(_e){throw rt.push(R+"type="+encodeURIComponent("_badmap")),_e}}catch{f&&f(Vt)}}if(W){P=rt.join("&");break t}}P=void 0}return i=i.i.splice(0,l),c.G=i,P}function ko(i){if(!i.g&&!i.v){i.Y=1;var c=i.Da;It||p(),at||(It(),at=!0),E.add(c,i),i.A=0}}function ds(i){return i.g||i.v||i.A>=3?!1:(i.Y++,i.v=Ye(d(i.Da,i),xo(i,i.A)),i.A++,!0)}n.Da=function(){if(this.v=null,No(this),this.aa&&!(this.P||this.g==null||this.T<=0)){var i=4*this.T;this.j.info("BP detection timer enabled: "+i),this.B=Ye(d(this.Wa,this),i)}},n.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,Et(10),Kn(this),No(this))};function fs(i){i.B!=null&&(a.clearTimeout(i.B),i.B=null)}function No(i){i.g=new Gt(i,i.j,"rpc",i.Y),i.u===null&&(i.g.J=i.o),i.g.P=0;var c=Pt(i.na);Q(c,"RID","rpc"),Q(c,"SID",i.M),Q(c,"AID",i.K),Q(c,"CI",i.F?"0":"1"),!i.F&&i.ia&&Q(c,"TO",i.ia),Q(c,"TYPE","xmlhttp"),ln(i,c),i.u&&i.o&&ls(c,i.u,i.o),i.O&&(i.g.H=i.O);var l=i.g;i=i.ba,l.M=1,l.A=zn(Pt(c)),l.u=null,l.R=!0,oo(l,i)}n.Va=function(){this.C!=null&&(this.C=null,Kn(this),ds(this),Et(19))};function Qn(i){i.C!=null&&(a.clearTimeout(i.C),i.C=null)}function Mo(i,c){var l=null;if(i.g==c){Qn(i),fs(i),i.g=null;var f=2}else if(os(i.h,c))l=c.G,fo(i.h,c),f=1;else return;if(i.I!=0){if(c.o)if(f==1){l=c.u?c.u.length:0,c=Date.now()-c.F;var w=i.D;f=jn(),yt(f,new eo(f,l)),Wn(i)}else ko(i);else if(w=c.m,w==3||w==0&&c.X>0||!(f==1&&ql(i,c)||f==2&&ds(i)))switch(l&&l.length>0&&(c=i.h,c.i=c.i.concat(l)),w){case 1:ge(i,5);break;case 4:ge(i,10);break;case 3:ge(i,6);break;default:ge(i,2)}}}function xo(i,c){let l=i.Qa+Math.floor(Math.random()*i.Za);return i.isActive()||(l*=2),l*c}function ge(i,c){if(i.j.info("Error code "+c),c==2){var l=d(i.bb,i),f=i.Ua;const w=!f;f=new Ht(f||"//www.google.com/images/cleardot.gif"),a.location&&a.location.protocol=="http"||en(f,"https"),zn(f),w?Ol(f.toString(),l):Ll(f.toString(),l)}else Et(2);i.I=0,i.l&&i.l.pa(c),Oo(i),Po(i)}n.bb=function(i){i?(this.j.info("Successfully pinged google.com"),Et(2)):(this.j.info("Failed to ping google.com"),Et(1))};function Oo(i){if(i.I=0,i.ja=[],i.l){const c=mo(i.h);(c.length!=0||i.i.length!=0)&&(k(i.ja,c),k(i.ja,i.i),i.h.i.length=0,b(i.i),i.i.length=0),i.l.oa()}}function Lo(i,c,l){var f=l instanceof Ht?Pt(l):new Ht(l);if(f.g!="")c&&(f.g=c+"."+f.g),nn(f,f.u);else{var w=a.location;f=w.protocol,c=c?c+"."+w.hostname:w.hostname,w=+w.port;const R=new Ht(null);f&&en(R,f),c&&(R.g=c),w&&nn(R,w),l&&(R.h=l),f=R}return l=i.G,c=i.wa,l&&c&&Q(f,l,c),Q(f,"VER",i.ka),ln(i,f),f}function Fo(i,c,l){if(c&&!i.L)throw Error("Can't create secondary domain capable XhrIo object.");return c=i.Aa&&!i.ma?new Z(new us({ab:l})):new Z(i.ma),c.Fa(i.L),c}n.isActive=function(){return!!this.l&&this.l.isActive(this)};function Uo(){}n=Uo.prototype,n.ra=function(){},n.qa=function(){},n.pa=function(){},n.oa=function(){},n.isActive=function(){return!0},n.Ka=function(){};function Xn(){}Xn.prototype.g=function(i,c){return new Rt(i,c)};function Rt(i,c){ft.call(this),this.g=new bo(c),this.l=i,this.h=c&&c.messageUrlParams||null,i=c&&c.messageHeaders||null,c&&c.clientProtocolHeaderRequired&&(i?i["X-Client-Protocol"]="webchannel":i={"X-Client-Protocol":"webchannel"}),this.g.o=i,i=c&&c.initMessageHeaders||null,c&&c.messageContentType&&(i?i["X-WebChannel-Content-Type"]=c.messageContentType:i={"X-WebChannel-Content-Type":c.messageContentType}),c&&c.sa&&(i?i["X-WebChannel-Client-Profile"]=c.sa:i={"X-WebChannel-Client-Profile":c.sa}),this.g.U=i,(i=c&&c.Qb)&&!g(i)&&(this.g.u=i),this.A=c&&c.supportsCrossDomainXhr||!1,this.v=c&&c.sendRawJson||!1,(c=c&&c.httpSessionIdParam)&&!g(c)&&(this.g.G=c,i=this.h,i!==null&&c in i&&(i=this.h,c in i&&delete i[c])),this.j=new De(this)}T(Rt,ft),Rt.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},Rt.prototype.close=function(){hs(this.g)},Rt.prototype.o=function(i){var c=this.g;if(typeof i=="string"){var l={};l.__data__=i,i=l}else this.v&&(l={},l.__data__=Jr(i),i=l);c.i.push(new bl(c.Ya++,i)),c.I==3&&Wn(c)},Rt.prototype.N=function(){this.g.l=null,delete this.j,hs(this.g),delete this.g,Rt.Z.N.call(this)};function Bo(i){Zr.call(this),i.__headers__&&(this.headers=i.__headers__,this.statusCode=i.__status__,delete i.__headers__,delete i.__status__);var c=i.__sm__;if(c){t:{for(const l in c){i=l;break t}i=void 0}(this.i=i)&&(i=this.i,c=c!==null&&i in c?c[i]:void 0),this.data=c}else this.data=i}T(Bo,Zr);function jo(){ts.call(this),this.status=1}T(jo,ts);function De(i){this.g=i}T(De,Uo),De.prototype.ra=function(){yt(this.g,"a")},De.prototype.qa=function(i){yt(this.g,new Bo(i))},De.prototype.pa=function(i){yt(this.g,new jo)},De.prototype.oa=function(){yt(this.g,"b")},Xn.prototype.createWebChannel=Xn.prototype.g,Rt.prototype.send=Rt.prototype.o,Rt.prototype.open=Rt.prototype.m,Rt.prototype.close=Rt.prototype.close,Tc=function(){return new Xn},Ec=function(){return jn()},yc=fe,ks={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},qn.NO_ERROR=0,qn.TIMEOUT=8,qn.HTTP_ERROR=6,rr=qn,no.COMPLETE="complete",_c=no,Yi.EventType=Qe,Qe.OPEN="a",Qe.CLOSE="b",Qe.ERROR="c",Qe.MESSAGE="d",ft.prototype.listen=ft.prototype.J,hn=Yi,Z.prototype.listenOnce=Z.prototype.K,Z.prototype.getLastError=Z.prototype.Ha,Z.prototype.getLastErrorCode=Z.prototype.ya,Z.prototype.getStatus=Z.prototype.ca,Z.prototype.getResponseJson=Z.prototype.La,Z.prototype.getResponseText=Z.prototype.la,Z.prototype.send=Z.prototype.ea,Z.prototype.setWithCredentials=Z.prototype.Fa,gc=Z}).apply(typeof Jn<"u"?Jn:typeof self<"u"?self:typeof window<"u"?window:{});const ea="@firebase/firestore",na="4.9.3";class pt{constructor(t){this.uid=t}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(t){return t.uid===this.uid}}pt.UNAUTHENTICATED=new pt(null),pt.GOOGLE_CREDENTIALS=new pt("google-credentials-uid"),pt.FIRST_PARTY=new pt("first-party-uid"),pt.MOCK_USER=new pt("mock-user");let ze="12.7.0";const we=new ti("@firebase/firestore");function ke(){return we.logLevel}function D(n,...t){if(we.logLevel<=$.DEBUG){const e=t.map(ni);we.debug(`Firestore (${ze}): ${n}`,...e)}}function $t(n,...t){if(we.logLevel<=$.ERROR){const e=t.map(ni);we.error(`Firestore (${ze}): ${n}`,...e)}}function Fe(n,...t){if(we.logLevel<=$.WARN){const e=t.map(ni);we.warn(`Firestore (${ze}): ${n}`,...e)}}function ni(n){if(typeof n=="string")return n;try{return(function(e){return JSON.stringify(e)})(n)}catch{return n}}function O(n,t,e){let r="Unexpected state";typeof t=="string"?r=t:e=t,Ic(n,r,e)}function Ic(n,t,e){let r=`FIRESTORE (${ze}) INTERNAL ASSERTION FAILED: ${t} (ID: ${n.toString(16)})`;if(e!==void 0)try{r+=" CONTEXT: "+JSON.stringify(e)}catch{r+=" CONTEXT: "+e}throw $t(r),new Error(r)}function K(n,t,e,r){let s="Unexpected state";typeof e=="string"?s=e:r=e,n||Ic(t,s,r)}function F(n,t){return n}const C={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class N extends ue{constructor(t,e){super(t,e),this.code=t,this.message=e,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class ee{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}}class wc{constructor(t,e){this.user=e,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${t}`)}}class kd{getToken(){return Promise.resolve(null)}invalidateToken(){}start(t,e){t.enqueueRetryable((()=>e(pt.UNAUTHENTICATED)))}shutdown(){}}class Nd{constructor(t){this.token=t,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(t,e){this.changeListener=e,t.enqueueRetryable((()=>e(this.token.user)))}shutdown(){this.changeListener=null}}class Md{constructor(t){this.t=t,this.currentUser=pt.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,e){K(this.o===void 0,42304);let r=this.i;const s=h=>this.i!==r?(r=this.i,e(h)):Promise.resolve();let o=new ee;this.o=()=>{this.i++,this.currentUser=this.u(),o.resolve(),o=new ee,t.enqueueRetryable((()=>s(this.currentUser)))};const a=()=>{const h=o;t.enqueueRetryable((async()=>{await h.promise,await s(this.currentUser)}))},u=h=>{D("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=h,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit((h=>u(h))),setTimeout((()=>{if(!this.auth){const h=this.t.getImmediate({optional:!0});h?u(h):(D("FirebaseAuthCredentialsProvider","Auth not yet detected"),o.resolve(),o=new ee)}}),0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then((r=>this.i!==t?(D("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):r?(K(typeof r.accessToken=="string",31837,{l:r}),new wc(r.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const t=this.auth&&this.auth.getUid();return K(t===null||typeof t=="string",2055,{h:t}),new pt(t)}}class xd{constructor(t,e,r){this.P=t,this.T=e,this.I=r,this.type="FirstParty",this.user=pt.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);const t=this.R();return t&&this.A.set("Authorization",t),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}}class Od{constructor(t,e,r){this.P=t,this.T=e,this.I=r}getToken(){return Promise.resolve(new xd(this.P,this.T,this.I))}start(t,e){t.enqueueRetryable((()=>e(pt.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class ra{constructor(t){this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class Ld{constructor(t,e){this.V=e,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,gd(t)&&t.settings.appCheckToken&&(this.p=t.settings.appCheckToken)}start(t,e){K(this.o===void 0,3512);const r=o=>{o.error!=null&&D("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${o.error.message}`);const a=o.token!==this.m;return this.m=o.token,D("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?e(o.token):Promise.resolve()};this.o=o=>{t.enqueueRetryable((()=>r(o)))};const s=o=>{D("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=o,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit((o=>s(o))),setTimeout((()=>{if(!this.appCheck){const o=this.V.getImmediate({optional:!0});o?s(o):D("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){if(this.p)return Promise.resolve(new ra(this.p));const t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then((e=>e?(K(typeof e.token=="string",44558,{tokenResult:e}),this.m=e.token,new ra(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function Fd(n){const t=typeof self<"u"&&(self.crypto||self.msCrypto),e=new Uint8Array(n);if(t&&typeof t.getRandomValues=="function")t.getRandomValues(e);else for(let r=0;r<n;r++)e[r]=Math.floor(256*Math.random());return e}class ri{static newId(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=62*Math.floor(4.129032258064516);let r="";for(;r.length<20;){const s=Fd(40);for(let o=0;o<s.length;++o)r.length<20&&s[o]<e&&(r+=t.charAt(s[o]%62))}return r}}function B(n,t){return n<t?-1:n>t?1:0}function Ns(n,t){const e=Math.min(n.length,t.length);for(let r=0;r<e;r++){const s=n.charAt(r),o=t.charAt(r);if(s!==o)return Es(s)===Es(o)?B(s,o):Es(s)?1:-1}return B(n.length,t.length)}const Ud=55296,Bd=57343;function Es(n){const t=n.charCodeAt(0);return t>=Ud&&t<=Bd}function Ue(n,t,e){return n.length===t.length&&n.every(((r,s)=>e(r,t[s])))}const sa="__name__";class Dt{constructor(t,e,r){e===void 0?e=0:e>t.length&&O(637,{offset:e,range:t.length}),r===void 0?r=t.length-e:r>t.length-e&&O(1746,{length:r,range:t.length-e}),this.segments=t,this.offset=e,this.len=r}get length(){return this.len}isEqual(t){return Dt.comparator(this,t)===0}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof Dt?t.forEach((r=>{e.push(r)})):e.push(t),this.construct(e)}limit(){return this.offset+this.length}popFirst(t){return t=t===void 0?1:t,this.construct(this.segments,this.offset+t,this.length-t)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(t){return this.segments[this.offset+t]}isEmpty(){return this.length===0}isPrefixOf(t){if(t.length<this.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}isImmediateParentOf(t){if(this.length+1!==t.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}forEach(t){for(let e=this.offset,r=this.limit();e<r;e++)t(this.segments[e])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(t,e){const r=Math.min(t.length,e.length);for(let s=0;s<r;s++){const o=Dt.compareSegments(t.get(s),e.get(s));if(o!==0)return o}return B(t.length,e.length)}static compareSegments(t,e){const r=Dt.isNumericId(t),s=Dt.isNumericId(e);return r&&!s?-1:!r&&s?1:r&&s?Dt.extractNumericId(t).compare(Dt.extractNumericId(e)):Ns(t,e)}static isNumericId(t){return t.startsWith("__id")&&t.endsWith("__")}static extractNumericId(t){return te.fromString(t.substring(4,t.length-2))}}class Y extends Dt{construct(t,e,r){return new Y(t,e,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...t){const e=[];for(const r of t){if(r.indexOf("//")>=0)throw new N(C.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);e.push(...r.split("/").filter((s=>s.length>0)))}return new Y(e)}static emptyPath(){return new Y([])}}const jd=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ht extends Dt{construct(t,e,r){return new ht(t,e,r)}static isValidIdentifier(t){return jd.test(t)}canonicalString(){return this.toArray().map((t=>(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),ht.isValidIdentifier(t)||(t="`"+t+"`"),t))).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===sa}static keyField(){return new ht([sa])}static fromServerFormat(t){const e=[];let r="",s=0;const o=()=>{if(r.length===0)throw new N(C.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(r),r=""};let a=!1;for(;s<t.length;){const u=t[s];if(u==="\\"){if(s+1===t.length)throw new N(C.INVALID_ARGUMENT,"Path has trailing escape character: "+t);const h=t[s+1];if(h!=="\\"&&h!=="."&&h!=="`")throw new N(C.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);r+=h,s+=2}else u==="`"?(a=!a,s++):u!=="."||a?(r+=u,s++):(o(),s++)}if(o(),a)throw new N(C.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new ht(e)}static emptyPath(){return new ht([])}}class x{constructor(t){this.path=t}static fromPath(t){return new x(Y.fromString(t))}static fromName(t){return new x(Y.fromString(t).popFirst(5))}static empty(){return new x(Y.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(t){return this.path.length>=2&&this.path.get(this.path.length-2)===t}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(t){return t!==null&&Y.comparator(this.path,t.path)===0}toString(){return this.path.toString()}static comparator(t,e){return Y.comparator(t.path,e.path)}static isDocumentKey(t){return t.length%2==0}static fromSegments(t){return new x(new Y(t.slice()))}}function qd(n,t,e){if(!e)throw new N(C.INVALID_ARGUMENT,`Function ${n}() cannot be called with an empty ${t}.`)}function $d(n,t,e,r){if(t===!0&&r===!0)throw new N(C.INVALID_ARGUMENT,`${n} and ${e} cannot be used together.`)}function ia(n){if(!x.isDocumentKey(n))throw new N(C.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${n} has ${n.length}.`)}function vc(n){return typeof n=="object"&&n!==null&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function si(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="string")return n.length>20&&(n=`${n.substring(0,20)}...`),JSON.stringify(n);if(typeof n=="number"||typeof n=="boolean")return""+n;if(typeof n=="object"){if(n instanceof Array)return"an array";{const t=(function(r){return r.constructor?r.constructor.name:null})(n);return t?`a custom ${t} object`:"an object"}}return typeof n=="function"?"a function":O(12329,{type:typeof n})}function ve(n,t){if("_delegate"in n&&(n=n._delegate),!(n instanceof t)){if(t.name===n.constructor.name)throw new N(C.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const e=si(n);throw new N(C.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${e}`)}}return n}function nt(n,t){const e={typeString:n};return t&&(e.value=t),e}function kn(n,t){if(!vc(n))throw new N(C.INVALID_ARGUMENT,"JSON must be an object");let e;for(const r in t)if(t[r]){const s=t[r].typeString,o="value"in t[r]?{value:t[r].value}:void 0;if(!(r in n)){e=`JSON missing required field: '${r}'`;break}const a=n[r];if(s&&typeof a!==s){e=`JSON field '${r}' must be a ${s}.`;break}if(o!==void 0&&a!==o.value){e=`Expected '${r}' field to equal '${o.value}'`;break}}if(e)throw new N(C.INVALID_ARGUMENT,e);return!0}const oa=-62135596800,aa=1e6;class X{static now(){return X.fromMillis(Date.now())}static fromDate(t){return X.fromMillis(t.getTime())}static fromMillis(t){const e=Math.floor(t/1e3),r=Math.floor((t-1e3*e)*aa);return new X(e,r)}constructor(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new N(C.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new N(C.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<oa)throw new N(C.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new N(C.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/aa}_compareTo(t){return this.seconds===t.seconds?B(this.nanoseconds,t.nanoseconds):B(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:X._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(t){if(kn(t,X._jsonSchema))return new X(t.seconds,t.nanoseconds)}valueOf(){const t=this.seconds-oa;return String(t).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}X._jsonSchemaVersion="firestore/timestamp/1.0",X._jsonSchema={type:nt("string",X._jsonSchemaVersion),seconds:nt("number"),nanoseconds:nt("number")};class L{static fromTimestamp(t){return new L(t)}static min(){return new L(new X(0,0))}static max(){return new L(new X(253402300799,999999999))}constructor(t){this.timestamp=t}compareTo(t){return this.timestamp._compareTo(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}const vn=-1;function zd(n,t){const e=n.toTimestamp().seconds,r=n.toTimestamp().nanoseconds+1,s=L.fromTimestamp(r===1e9?new X(e+1,0):new X(e,r));return new re(s,x.empty(),t)}function Gd(n){return new re(n.readTime,n.key,vn)}class re{constructor(t,e,r){this.readTime=t,this.documentKey=e,this.largestBatchId=r}static min(){return new re(L.min(),x.empty(),vn)}static max(){return new re(L.max(),x.empty(),vn)}}function Hd(n,t){let e=n.readTime.compareTo(t.readTime);return e!==0?e:(e=x.comparator(n.documentKey,t.documentKey),e!==0?e:B(n.largestBatchId,t.largestBatchId))}const Kd="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Wd{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(t){this.onCommittedListeners.push(t)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((t=>t()))}}async function Ge(n){if(n.code!==C.FAILED_PRECONDITION||n.message!==Kd)throw n;D("LocalStore","Unexpectedly lost primary lease")}class S{constructor(t){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(t){return this.next(void 0,t)}next(t,e){return this.callbackAttached&&O(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(e,this.error):this.wrapSuccess(t,this.result):new S(((r,s)=>{this.nextCallback=o=>{this.wrapSuccess(t,o).next(r,s)},this.catchCallback=o=>{this.wrapFailure(e,o).next(r,s)}}))}toPromise(){return new Promise(((t,e)=>{this.next(t,e)}))}wrapUserFunction(t){try{const e=t();return e instanceof S?e:S.resolve(e)}catch(e){return S.reject(e)}}wrapSuccess(t,e){return t?this.wrapUserFunction((()=>t(e))):S.resolve(e)}wrapFailure(t,e){return t?this.wrapUserFunction((()=>t(e))):S.reject(e)}static resolve(t){return new S(((e,r)=>{e(t)}))}static reject(t){return new S(((e,r)=>{r(t)}))}static waitFor(t){return new S(((e,r)=>{let s=0,o=0,a=!1;t.forEach((u=>{++s,u.next((()=>{++o,a&&o===s&&e()}),(h=>r(h)))})),a=!0,o===s&&e()}))}static or(t){let e=S.resolve(!1);for(const r of t)e=e.next((s=>s?S.resolve(s):r()));return e}static forEach(t,e){const r=[];return t.forEach(((s,o)=>{r.push(e.call(this,s,o))})),this.waitFor(r)}static mapArray(t,e){return new S(((r,s)=>{const o=t.length,a=new Array(o);let u=0;for(let h=0;h<o;h++){const d=h;e(t[d]).next((m=>{a[d]=m,++u,u===o&&r(a)}),(m=>s(m)))}}))}static doWhile(t,e){return new S(((r,s)=>{const o=()=>{t()===!0?e().next((()=>{o()}),s):r()};o()}))}}function Qd(n){const t=n.match(/Android ([\d.]+)/i),e=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(e)}function He(n){return n.name==="IndexedDbTransactionError"}class Sr{constructor(t,e){this.previousValue=t,e&&(e.sequenceNumberHandler=r=>this.ae(r),this.ue=r=>e.writeSequenceNumber(r))}ae(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){const t=++this.previousValue;return this.ue&&this.ue(t),t}}Sr.ce=-1;const ii=-1;function Cr(n){return n==null}function hr(n){return n===0&&1/n==-1/0}function Xd(n){return typeof n=="number"&&Number.isInteger(n)&&!hr(n)&&n<=Number.MAX_SAFE_INTEGER&&n>=Number.MIN_SAFE_INTEGER}const Ac="";function Yd(n){let t="";for(let e=0;e<n.length;e++)t.length>0&&(t=ca(t)),t=Jd(n.get(e),t);return ca(t)}function Jd(n,t){let e=t;const r=n.length;for(let s=0;s<r;s++){const o=n.charAt(s);switch(o){case"\0":e+="";break;case Ac:e+="";break;default:e+=o}}return e}function ca(n){return n+Ac+""}function ua(n){let t=0;for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&t++;return t}function le(n,t){for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&t(e,n[e])}function Rc(n){for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t))return!1;return!0}class J{constructor(t,e){this.comparator=t,this.root=e||lt.EMPTY}insert(t,e){return new J(this.comparator,this.root.insert(t,e,this.comparator).copy(null,null,lt.BLACK,null,null))}remove(t){return new J(this.comparator,this.root.remove(t,this.comparator).copy(null,null,lt.BLACK,null,null))}get(t){let e=this.root;for(;!e.isEmpty();){const r=this.comparator(t,e.key);if(r===0)return e.value;r<0?e=e.left:r>0&&(e=e.right)}return null}indexOf(t){let e=0,r=this.root;for(;!r.isEmpty();){const s=this.comparator(t,r.key);if(s===0)return e+r.left.size;s<0?r=r.left:(e+=r.left.size+1,r=r.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(t){return this.root.inorderTraversal(t)}forEach(t){this.inorderTraversal(((e,r)=>(t(e,r),!1)))}toString(){const t=[];return this.inorderTraversal(((e,r)=>(t.push(`${e}:${r}`),!1))),`{${t.join(", ")}}`}reverseTraversal(t){return this.root.reverseTraversal(t)}getIterator(){return new Zn(this.root,null,this.comparator,!1)}getIteratorFrom(t){return new Zn(this.root,t,this.comparator,!1)}getReverseIterator(){return new Zn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(t){return new Zn(this.root,t,this.comparator,!0)}}class Zn{constructor(t,e,r,s){this.isReverse=s,this.nodeStack=[];let o=1;for(;!t.isEmpty();)if(o=e?r(t.key,e):1,e&&s&&(o*=-1),o<0)t=this.isReverse?t.left:t.right;else{if(o===0){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}getNext(){let t=this.nodeStack.pop();const e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e}hasNext(){return this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;const t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}}}class lt{constructor(t,e,r,s,o){this.key=t,this.value=e,this.color=r??lt.RED,this.left=s??lt.EMPTY,this.right=o??lt.EMPTY,this.size=this.left.size+1+this.right.size}copy(t,e,r,s,o){return new lt(t??this.key,e??this.value,r??this.color,s??this.left,o??this.right)}isEmpty(){return!1}inorderTraversal(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)}reverseTraversal(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(t,e,r){let s=this;const o=r(t,s.key);return s=o<0?s.copy(null,null,null,s.left.insert(t,e,r),null):o===0?s.copy(null,e,null,null,null):s.copy(null,null,null,null,s.right.insert(t,e,r)),s.fixUp()}removeMin(){if(this.left.isEmpty())return lt.EMPTY;let t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),t=t.copy(null,null,null,t.left.removeMin(),null),t.fixUp()}remove(t,e){let r,s=this;if(e(t,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(t,e),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),e(t,s.key)===0){if(s.right.isEmpty())return lt.EMPTY;r=s.right.min(),s=s.copy(r.key,r.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(t,e))}return s.fixUp()}isRed(){return this.color}fixUp(){let t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t}moveRedLeft(){let t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t}moveRedRight(){let t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t}rotateLeft(){const t=this.copy(null,null,lt.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight(){const t=this.copy(null,null,lt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip(){const t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)}checkMaxDepth(){const t=this.check();return Math.pow(2,t)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw O(43730,{key:this.key,value:this.value});if(this.right.isRed())throw O(14113,{key:this.key,value:this.value});const t=this.left.check();if(t!==this.right.check())throw O(27949);return t+(this.isRed()?0:1)}}lt.EMPTY=null,lt.RED=!0,lt.BLACK=!1;lt.EMPTY=new class{constructor(){this.size=0}get key(){throw O(57766)}get value(){throw O(16141)}get color(){throw O(16727)}get left(){throw O(29726)}get right(){throw O(36894)}copy(t,e,r,s,o){return this}insert(t,e,r){return new lt(t,e)}remove(t,e){return this}isEmpty(){return!0}inorderTraversal(t){return!1}reverseTraversal(t){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class ot{constructor(t){this.comparator=t,this.data=new J(this.comparator)}has(t){return this.data.get(t)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(t){return this.data.indexOf(t)}forEach(t){this.data.inorderTraversal(((e,r)=>(t(e),!1)))}forEachInRange(t,e){const r=this.data.getIteratorFrom(t[0]);for(;r.hasNext();){const s=r.getNext();if(this.comparator(s.key,t[1])>=0)return;e(s.key)}}forEachWhile(t,e){let r;for(r=e!==void 0?this.data.getIteratorFrom(e):this.data.getIterator();r.hasNext();)if(!t(r.getNext().key))return}firstAfterOrEqual(t){const e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null}getIterator(){return new la(this.data.getIterator())}getIteratorFrom(t){return new la(this.data.getIteratorFrom(t))}add(t){return this.copy(this.data.remove(t).insert(t,!0))}delete(t){return this.has(t)?this.copy(this.data.remove(t)):this}isEmpty(){return this.data.isEmpty()}unionWith(t){let e=this;return e.size<t.size&&(e=t,t=this),t.forEach((r=>{e=e.add(r)})),e}isEqual(t){if(!(t instanceof ot)||this.size!==t.size)return!1;const e=this.data.getIterator(),r=t.data.getIterator();for(;e.hasNext();){const s=e.getNext().key,o=r.getNext().key;if(this.comparator(s,o)!==0)return!1}return!0}toArray(){const t=[];return this.forEach((e=>{t.push(e)})),t}toString(){const t=[];return this.forEach((e=>t.push(e))),"SortedSet("+t.toString()+")"}copy(t){const e=new ot(this.comparator);return e.data=t,e}}class la{constructor(t){this.iter=t}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class St{constructor(t){this.fields=t,t.sort(ht.comparator)}static empty(){return new St([])}unionWith(t){let e=new ot(ht.comparator);for(const r of this.fields)e=e.add(r);for(const r of t)e=e.add(r);return new St(e.toArray())}covers(t){for(const e of this.fields)if(e.isPrefixOf(t))return!0;return!1}isEqual(t){return Ue(this.fields,t.fields,((e,r)=>e.isEqual(r)))}}class Sc extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class dt{constructor(t){this.binaryString=t}static fromBase64String(t){const e=(function(s){try{return atob(s)}catch(o){throw typeof DOMException<"u"&&o instanceof DOMException?new Sc("Invalid base64 string: "+o):o}})(t);return new dt(e)}static fromUint8Array(t){const e=(function(s){let o="";for(let a=0;a<s.length;++a)o+=String.fromCharCode(s[a]);return o})(t);return new dt(e)}[Symbol.iterator](){let t=0;return{next:()=>t<this.binaryString.length?{value:this.binaryString.charCodeAt(t++),done:!1}:{value:void 0,done:!0}}}toBase64(){return(function(e){return btoa(e)})(this.binaryString)}toUint8Array(){return(function(e){const r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r})(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(t){return B(this.binaryString,t.binaryString)}isEqual(t){return this.binaryString===t.binaryString}}dt.EMPTY_BYTE_STRING=new dt("");const Zd=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function se(n){if(K(!!n,39018),typeof n=="string"){let t=0;const e=Zd.exec(n);if(K(!!e,46558,{timestamp:n}),e[1]){let s=e[1];s=(s+"000000000").substr(0,9),t=Number(s)}const r=new Date(n);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:tt(n.seconds),nanos:tt(n.nanos)}}function tt(n){return typeof n=="number"?n:typeof n=="string"?Number(n):0}function ie(n){return typeof n=="string"?dt.fromBase64String(n):dt.fromUint8Array(n)}const Cc="server_timestamp",bc="__type__",Pc="__previous_value__",Vc="__local_write_time__";function oi(n){return(n?.mapValue?.fields||{})[bc]?.stringValue===Cc}function br(n){const t=n.mapValue.fields[Pc];return oi(t)?br(t):t}function An(n){const t=se(n.mapValue.fields[Vc].timestampValue);return new X(t.seconds,t.nanos)}class tf{constructor(t,e,r,s,o,a,u,h,d,m){this.databaseId=t,this.appId=e,this.persistenceKey=r,this.host=s,this.ssl=o,this.forceLongPolling=a,this.autoDetectLongPolling=u,this.longPollingOptions=h,this.useFetchStreams=d,this.isUsingEmulator=m}}const dr="(default)";class Rn{constructor(t,e){this.projectId=t,this.database=e||dr}static empty(){return new Rn("","")}get isDefaultDatabase(){return this.database===dr}isEqual(t){return t instanceof Rn&&t.projectId===this.projectId&&t.database===this.database}}const Dc="__type__",ef="__max__",tr={mapValue:{}},kc="__vector__",fr="value";function oe(n){return"nullValue"in n?0:"booleanValue"in n?1:"integerValue"in n||"doubleValue"in n?2:"timestampValue"in n?3:"stringValue"in n?5:"bytesValue"in n?6:"referenceValue"in n?7:"geoPointValue"in n?8:"arrayValue"in n?9:"mapValue"in n?oi(n)?4:rf(n)?9007199254740991:nf(n)?10:11:O(28295,{value:n})}function Ut(n,t){if(n===t)return!0;const e=oe(n);if(e!==oe(t))return!1;switch(e){case 0:case 9007199254740991:return!0;case 1:return n.booleanValue===t.booleanValue;case 4:return An(n).isEqual(An(t));case 3:return(function(s,o){if(typeof s.timestampValue=="string"&&typeof o.timestampValue=="string"&&s.timestampValue.length===o.timestampValue.length)return s.timestampValue===o.timestampValue;const a=se(s.timestampValue),u=se(o.timestampValue);return a.seconds===u.seconds&&a.nanos===u.nanos})(n,t);case 5:return n.stringValue===t.stringValue;case 6:return(function(s,o){return ie(s.bytesValue).isEqual(ie(o.bytesValue))})(n,t);case 7:return n.referenceValue===t.referenceValue;case 8:return(function(s,o){return tt(s.geoPointValue.latitude)===tt(o.geoPointValue.latitude)&&tt(s.geoPointValue.longitude)===tt(o.geoPointValue.longitude)})(n,t);case 2:return(function(s,o){if("integerValue"in s&&"integerValue"in o)return tt(s.integerValue)===tt(o.integerValue);if("doubleValue"in s&&"doubleValue"in o){const a=tt(s.doubleValue),u=tt(o.doubleValue);return a===u?hr(a)===hr(u):isNaN(a)&&isNaN(u)}return!1})(n,t);case 9:return Ue(n.arrayValue.values||[],t.arrayValue.values||[],Ut);case 10:case 11:return(function(s,o){const a=s.mapValue.fields||{},u=o.mapValue.fields||{};if(ua(a)!==ua(u))return!1;for(const h in a)if(a.hasOwnProperty(h)&&(u[h]===void 0||!Ut(a[h],u[h])))return!1;return!0})(n,t);default:return O(52216,{left:n})}}function Sn(n,t){return(n.values||[]).find((e=>Ut(e,t)))!==void 0}function Be(n,t){if(n===t)return 0;const e=oe(n),r=oe(t);if(e!==r)return B(e,r);switch(e){case 0:case 9007199254740991:return 0;case 1:return B(n.booleanValue,t.booleanValue);case 2:return(function(o,a){const u=tt(o.integerValue||o.doubleValue),h=tt(a.integerValue||a.doubleValue);return u<h?-1:u>h?1:u===h?0:isNaN(u)?isNaN(h)?0:-1:1})(n,t);case 3:return ha(n.timestampValue,t.timestampValue);case 4:return ha(An(n),An(t));case 5:return Ns(n.stringValue,t.stringValue);case 6:return(function(o,a){const u=ie(o),h=ie(a);return u.compareTo(h)})(n.bytesValue,t.bytesValue);case 7:return(function(o,a){const u=o.split("/"),h=a.split("/");for(let d=0;d<u.length&&d<h.length;d++){const m=B(u[d],h[d]);if(m!==0)return m}return B(u.length,h.length)})(n.referenceValue,t.referenceValue);case 8:return(function(o,a){const u=B(tt(o.latitude),tt(a.latitude));return u!==0?u:B(tt(o.longitude),tt(a.longitude))})(n.geoPointValue,t.geoPointValue);case 9:return da(n.arrayValue,t.arrayValue);case 10:return(function(o,a){const u=o.fields||{},h=a.fields||{},d=u[fr]?.arrayValue,m=h[fr]?.arrayValue,T=B(d?.values?.length||0,m?.values?.length||0);return T!==0?T:da(d,m)})(n.mapValue,t.mapValue);case 11:return(function(o,a){if(o===tr.mapValue&&a===tr.mapValue)return 0;if(o===tr.mapValue)return 1;if(a===tr.mapValue)return-1;const u=o.fields||{},h=Object.keys(u),d=a.fields||{},m=Object.keys(d);h.sort(),m.sort();for(let T=0;T<h.length&&T<m.length;++T){const v=Ns(h[T],m[T]);if(v!==0)return v;const b=Be(u[h[T]],d[m[T]]);if(b!==0)return b}return B(h.length,m.length)})(n.mapValue,t.mapValue);default:throw O(23264,{he:e})}}function ha(n,t){if(typeof n=="string"&&typeof t=="string"&&n.length===t.length)return B(n,t);const e=se(n),r=se(t),s=B(e.seconds,r.seconds);return s!==0?s:B(e.nanos,r.nanos)}function da(n,t){const e=n.values||[],r=t.values||[];for(let s=0;s<e.length&&s<r.length;++s){const o=Be(e[s],r[s]);if(o)return o}return B(e.length,r.length)}function je(n){return Ms(n)}function Ms(n){return"nullValue"in n?"null":"booleanValue"in n?""+n.booleanValue:"integerValue"in n?""+n.integerValue:"doubleValue"in n?""+n.doubleValue:"timestampValue"in n?(function(e){const r=se(e);return`time(${r.seconds},${r.nanos})`})(n.timestampValue):"stringValue"in n?n.stringValue:"bytesValue"in n?(function(e){return ie(e).toBase64()})(n.bytesValue):"referenceValue"in n?(function(e){return x.fromName(e).toString()})(n.referenceValue):"geoPointValue"in n?(function(e){return`geo(${e.latitude},${e.longitude})`})(n.geoPointValue):"arrayValue"in n?(function(e){let r="[",s=!0;for(const o of e.values||[])s?s=!1:r+=",",r+=Ms(o);return r+"]"})(n.arrayValue):"mapValue"in n?(function(e){const r=Object.keys(e.fields||{}).sort();let s="{",o=!0;for(const a of r)o?o=!1:s+=",",s+=`${a}:${Ms(e.fields[a])}`;return s+"}"})(n.mapValue):O(61005,{value:n})}function sr(n){switch(oe(n)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const t=br(n);return t?16+sr(t):16;case 5:return 2*n.stringValue.length;case 6:return ie(n.bytesValue).approximateByteSize();case 7:return n.referenceValue.length;case 9:return(function(r){return(r.values||[]).reduce(((s,o)=>s+sr(o)),0)})(n.arrayValue);case 10:case 11:return(function(r){let s=0;return le(r.fields,((o,a)=>{s+=o.length+sr(a)})),s})(n.mapValue);default:throw O(13486,{value:n})}}function xs(n){return!!n&&"integerValue"in n}function ai(n){return!!n&&"arrayValue"in n}function fa(n){return!!n&&"nullValue"in n}function ma(n){return!!n&&"doubleValue"in n&&isNaN(Number(n.doubleValue))}function ir(n){return!!n&&"mapValue"in n}function nf(n){return(n?.mapValue?.fields||{})[Dc]?.stringValue===kc}function gn(n){if(n.geoPointValue)return{geoPointValue:{...n.geoPointValue}};if(n.timestampValue&&typeof n.timestampValue=="object")return{timestampValue:{...n.timestampValue}};if(n.mapValue){const t={mapValue:{fields:{}}};return le(n.mapValue.fields,((e,r)=>t.mapValue.fields[e]=gn(r))),t}if(n.arrayValue){const t={arrayValue:{values:[]}};for(let e=0;e<(n.arrayValue.values||[]).length;++e)t.arrayValue.values[e]=gn(n.arrayValue.values[e]);return t}return{...n}}function rf(n){return(((n.mapValue||{}).fields||{}).__type__||{}).stringValue===ef}class At{constructor(t){this.value=t}static empty(){return new At({mapValue:{}})}field(t){if(t.isEmpty())return this.value;{let e=this.value;for(let r=0;r<t.length-1;++r)if(e=(e.mapValue.fields||{})[t.get(r)],!ir(e))return null;return e=(e.mapValue.fields||{})[t.lastSegment()],e||null}}set(t,e){this.getFieldsMap(t.popLast())[t.lastSegment()]=gn(e)}setAll(t){let e=ht.emptyPath(),r={},s=[];t.forEach(((a,u)=>{if(!e.isImmediateParentOf(u)){const h=this.getFieldsMap(e);this.applyChanges(h,r,s),r={},s=[],e=u.popLast()}a?r[u.lastSegment()]=gn(a):s.push(u.lastSegment())}));const o=this.getFieldsMap(e);this.applyChanges(o,r,s)}delete(t){const e=this.field(t.popLast());ir(e)&&e.mapValue.fields&&delete e.mapValue.fields[t.lastSegment()]}isEqual(t){return Ut(this.value,t.value)}getFieldsMap(t){let e=this.value;e.mapValue.fields||(e.mapValue={fields:{}});for(let r=0;r<t.length;++r){let s=e.mapValue.fields[t.get(r)];ir(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},e.mapValue.fields[t.get(r)]=s),e=s}return e.mapValue.fields}applyChanges(t,e,r){le(e,((s,o)=>t[s]=o));for(const s of r)delete t[s]}clone(){return new At(gn(this.value))}}function Nc(n){const t=[];return le(n.fields,((e,r)=>{const s=new ht([e]);if(ir(r)){const o=Nc(r.mapValue).fields;if(o.length===0)t.push(s);else for(const a of o)t.push(s.child(a))}else t.push(s)})),new St(t)}class gt{constructor(t,e,r,s,o,a,u){this.key=t,this.documentType=e,this.version=r,this.readTime=s,this.createTime=o,this.data=a,this.documentState=u}static newInvalidDocument(t){return new gt(t,0,L.min(),L.min(),L.min(),At.empty(),0)}static newFoundDocument(t,e,r,s){return new gt(t,1,e,L.min(),r,s,0)}static newNoDocument(t,e){return new gt(t,2,e,L.min(),L.min(),At.empty(),0)}static newUnknownDocument(t,e){return new gt(t,3,e,L.min(),L.min(),At.empty(),2)}convertToFoundDocument(t,e){return!this.createTime.isEqual(L.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=t),this.version=t,this.documentType=1,this.data=e,this.documentState=0,this}convertToNoDocument(t){return this.version=t,this.documentType=2,this.data=At.empty(),this.documentState=0,this}convertToUnknownDocument(t){return this.version=t,this.documentType=3,this.data=At.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=L.min(),this}setReadTime(t){return this.readTime=t,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(t){return t instanceof gt&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}mutableCopy(){return new gt(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class mr{constructor(t,e){this.position=t,this.inclusive=e}}function pa(n,t,e){let r=0;for(let s=0;s<n.position.length;s++){const o=t[s],a=n.position[s];if(o.field.isKeyField()?r=x.comparator(x.fromName(a.referenceValue),e.key):r=Be(a,e.data.field(o.field)),o.dir==="desc"&&(r*=-1),r!==0)break}return r}function ga(n,t){if(n===null)return t===null;if(t===null||n.inclusive!==t.inclusive||n.position.length!==t.position.length)return!1;for(let e=0;e<n.position.length;e++)if(!Ut(n.position[e],t.position[e]))return!1;return!0}class pr{constructor(t,e="asc"){this.field=t,this.dir=e}}function sf(n,t){return n.dir===t.dir&&n.field.isEqual(t.field)}class Mc{}class st extends Mc{constructor(t,e,r){super(),this.field=t,this.op=e,this.value=r}static create(t,e,r){return t.isKeyField()?e==="in"||e==="not-in"?this.createKeyFieldInFilter(t,e,r):new af(t,e,r):e==="array-contains"?new lf(t,r):e==="in"?new hf(t,r):e==="not-in"?new df(t,r):e==="array-contains-any"?new ff(t,r):new st(t,e,r)}static createKeyFieldInFilter(t,e,r){return e==="in"?new cf(t,r):new uf(t,r)}matches(t){const e=t.data.field(this.field);return this.op==="!="?e!==null&&e.nullValue===void 0&&this.matchesComparison(Be(e,this.value)):e!==null&&oe(this.value)===oe(e)&&this.matchesComparison(Be(e,this.value))}matchesComparison(t){switch(this.op){case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;case">":return t>0;case">=":return t>=0;default:return O(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class Bt extends Mc{constructor(t,e){super(),this.filters=t,this.op=e,this.Pe=null}static create(t,e){return new Bt(t,e)}matches(t){return xc(this)?this.filters.find((e=>!e.matches(t)))===void 0:this.filters.find((e=>e.matches(t)))!==void 0}getFlattenedFilters(){return this.Pe!==null||(this.Pe=this.filters.reduce(((t,e)=>t.concat(e.getFlattenedFilters())),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function xc(n){return n.op==="and"}function Oc(n){return of(n)&&xc(n)}function of(n){for(const t of n.filters)if(t instanceof Bt)return!1;return!0}function Os(n){if(n instanceof st)return n.field.canonicalString()+n.op.toString()+je(n.value);if(Oc(n))return n.filters.map((t=>Os(t))).join(",");{const t=n.filters.map((e=>Os(e))).join(",");return`${n.op}(${t})`}}function Lc(n,t){return n instanceof st?(function(r,s){return s instanceof st&&r.op===s.op&&r.field.isEqual(s.field)&&Ut(r.value,s.value)})(n,t):n instanceof Bt?(function(r,s){return s instanceof Bt&&r.op===s.op&&r.filters.length===s.filters.length?r.filters.reduce(((o,a,u)=>o&&Lc(a,s.filters[u])),!0):!1})(n,t):void O(19439)}function Fc(n){return n instanceof st?(function(e){return`${e.field.canonicalString()} ${e.op} ${je(e.value)}`})(n):n instanceof Bt?(function(e){return e.op.toString()+" {"+e.getFilters().map(Fc).join(" ,")+"}"})(n):"Filter"}class af extends st{constructor(t,e,r){super(t,e,r),this.key=x.fromName(r.referenceValue)}matches(t){const e=x.comparator(t.key,this.key);return this.matchesComparison(e)}}class cf extends st{constructor(t,e){super(t,"in",e),this.keys=Uc("in",e)}matches(t){return this.keys.some((e=>e.isEqual(t.key)))}}class uf extends st{constructor(t,e){super(t,"not-in",e),this.keys=Uc("not-in",e)}matches(t){return!this.keys.some((e=>e.isEqual(t.key)))}}function Uc(n,t){return(t.arrayValue?.values||[]).map((e=>x.fromName(e.referenceValue)))}class lf extends st{constructor(t,e){super(t,"array-contains",e)}matches(t){const e=t.data.field(this.field);return ai(e)&&Sn(e.arrayValue,this.value)}}class hf extends st{constructor(t,e){super(t,"in",e)}matches(t){const e=t.data.field(this.field);return e!==null&&Sn(this.value.arrayValue,e)}}class df extends st{constructor(t,e){super(t,"not-in",e)}matches(t){if(Sn(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const e=t.data.field(this.field);return e!==null&&e.nullValue===void 0&&!Sn(this.value.arrayValue,e)}}class ff extends st{constructor(t,e){super(t,"array-contains-any",e)}matches(t){const e=t.data.field(this.field);return!(!ai(e)||!e.arrayValue.values)&&e.arrayValue.values.some((r=>Sn(this.value.arrayValue,r)))}}class mf{constructor(t,e=null,r=[],s=[],o=null,a=null,u=null){this.path=t,this.collectionGroup=e,this.orderBy=r,this.filters=s,this.limit=o,this.startAt=a,this.endAt=u,this.Te=null}}function _a(n,t=null,e=[],r=[],s=null,o=null,a=null){return new mf(n,t,e,r,s,o,a)}function ci(n){const t=F(n);if(t.Te===null){let e=t.path.canonicalString();t.collectionGroup!==null&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((r=>Os(r))).join(","),e+="|ob:",e+=t.orderBy.map((r=>(function(o){return o.field.canonicalString()+o.dir})(r))).join(","),Cr(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((r=>je(r))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((r=>je(r))).join(",")),t.Te=e}return t.Te}function ui(n,t){if(n.limit!==t.limit||n.orderBy.length!==t.orderBy.length)return!1;for(let e=0;e<n.orderBy.length;e++)if(!sf(n.orderBy[e],t.orderBy[e]))return!1;if(n.filters.length!==t.filters.length)return!1;for(let e=0;e<n.filters.length;e++)if(!Lc(n.filters[e],t.filters[e]))return!1;return n.collectionGroup===t.collectionGroup&&!!n.path.isEqual(t.path)&&!!ga(n.startAt,t.startAt)&&ga(n.endAt,t.endAt)}function Ls(n){return x.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}class Pr{constructor(t,e=null,r=[],s=[],o=null,a="F",u=null,h=null){this.path=t,this.collectionGroup=e,this.explicitOrderBy=r,this.filters=s,this.limit=o,this.limitType=a,this.startAt=u,this.endAt=h,this.Ie=null,this.Ee=null,this.de=null,this.startAt,this.endAt}}function pf(n,t,e,r,s,o,a,u){return new Pr(n,t,e,r,s,o,a,u)}function li(n){return new Pr(n)}function ya(n){return n.filters.length===0&&n.limit===null&&n.startAt==null&&n.endAt==null&&(n.explicitOrderBy.length===0||n.explicitOrderBy.length===1&&n.explicitOrderBy[0].field.isKeyField())}function gf(n){return n.collectionGroup!==null}function _n(n){const t=F(n);if(t.Ie===null){t.Ie=[];const e=new Set;for(const o of t.explicitOrderBy)t.Ie.push(o),e.add(o.field.canonicalString());const r=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";(function(a){let u=new ot(ht.comparator);return a.filters.forEach((h=>{h.getFlattenedFilters().forEach((d=>{d.isInequality()&&(u=u.add(d.field))}))})),u})(t).forEach((o=>{e.has(o.canonicalString())||o.isKeyField()||t.Ie.push(new pr(o,r))})),e.has(ht.keyField().canonicalString())||t.Ie.push(new pr(ht.keyField(),r))}return t.Ie}function Nt(n){const t=F(n);return t.Ee||(t.Ee=_f(t,_n(n))),t.Ee}function _f(n,t){if(n.limitType==="F")return _a(n.path,n.collectionGroup,t,n.filters,n.limit,n.startAt,n.endAt);{t=t.map((s=>{const o=s.dir==="desc"?"asc":"desc";return new pr(s.field,o)}));const e=n.endAt?new mr(n.endAt.position,n.endAt.inclusive):null,r=n.startAt?new mr(n.startAt.position,n.startAt.inclusive):null;return _a(n.path,n.collectionGroup,t,n.filters,n.limit,e,r)}}function Fs(n,t,e){return new Pr(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),t,e,n.startAt,n.endAt)}function Vr(n,t){return ui(Nt(n),Nt(t))&&n.limitType===t.limitType}function Bc(n){return`${ci(Nt(n))}|lt:${n.limitType}`}function Ne(n){return`Query(target=${(function(e){let r=e.path.canonicalString();return e.collectionGroup!==null&&(r+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(r+=`, filters: [${e.filters.map((s=>Fc(s))).join(", ")}]`),Cr(e.limit)||(r+=", limit: "+e.limit),e.orderBy.length>0&&(r+=`, orderBy: [${e.orderBy.map((s=>(function(a){return`${a.field.canonicalString()} (${a.dir})`})(s))).join(", ")}]`),e.startAt&&(r+=", startAt: ",r+=e.startAt.inclusive?"b:":"a:",r+=e.startAt.position.map((s=>je(s))).join(",")),e.endAt&&(r+=", endAt: ",r+=e.endAt.inclusive?"a:":"b:",r+=e.endAt.position.map((s=>je(s))).join(",")),`Target(${r})`})(Nt(n))}; limitType=${n.limitType})`}function Dr(n,t){return t.isFoundDocument()&&(function(r,s){const o=s.key.path;return r.collectionGroup!==null?s.key.hasCollectionId(r.collectionGroup)&&r.path.isPrefixOf(o):x.isDocumentKey(r.path)?r.path.isEqual(o):r.path.isImmediateParentOf(o)})(n,t)&&(function(r,s){for(const o of _n(r))if(!o.field.isKeyField()&&s.data.field(o.field)===null)return!1;return!0})(n,t)&&(function(r,s){for(const o of r.filters)if(!o.matches(s))return!1;return!0})(n,t)&&(function(r,s){return!(r.startAt&&!(function(a,u,h){const d=pa(a,u,h);return a.inclusive?d<=0:d<0})(r.startAt,_n(r),s)||r.endAt&&!(function(a,u,h){const d=pa(a,u,h);return a.inclusive?d>=0:d>0})(r.endAt,_n(r),s))})(n,t)}function yf(n){return n.collectionGroup||(n.path.length%2==1?n.path.lastSegment():n.path.get(n.path.length-2))}function jc(n){return(t,e)=>{let r=!1;for(const s of _n(n)){const o=Ef(s,t,e);if(o!==0)return o;r=r||s.field.isKeyField()}return 0}}function Ef(n,t,e){const r=n.field.isKeyField()?x.comparator(t.key,e.key):(function(o,a,u){const h=a.data.field(o),d=u.data.field(o);return h!==null&&d!==null?Be(h,d):O(42886)})(n.field,t,e);switch(n.dir){case"asc":return r;case"desc":return-1*r;default:return O(19790,{direction:n.dir})}}class Ce{constructor(t,e){this.mapKeyFn=t,this.equalsFn=e,this.inner={},this.innerSize=0}get(t){const e=this.mapKeyFn(t),r=this.inner[e];if(r!==void 0){for(const[s,o]of r)if(this.equalsFn(s,t))return o}}has(t){return this.get(t)!==void 0}set(t,e){const r=this.mapKeyFn(t),s=this.inner[r];if(s===void 0)return this.inner[r]=[[t,e]],void this.innerSize++;for(let o=0;o<s.length;o++)if(this.equalsFn(s[o][0],t))return void(s[o]=[t,e]);s.push([t,e]),this.innerSize++}delete(t){const e=this.mapKeyFn(t),r=this.inner[e];if(r===void 0)return!1;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],t))return r.length===1?delete this.inner[e]:r.splice(s,1),this.innerSize--,!0;return!1}forEach(t){le(this.inner,((e,r)=>{for(const[s,o]of r)t(s,o)}))}isEmpty(){return Rc(this.inner)}size(){return this.innerSize}}const Tf=new J(x.comparator);function zt(){return Tf}const qc=new J(x.comparator);function dn(...n){let t=qc;for(const e of n)t=t.insert(e.key,e);return t}function $c(n){let t=qc;return n.forEach(((e,r)=>t=t.insert(e,r.overlayedDocument))),t}function Ee(){return yn()}function zc(){return yn()}function yn(){return new Ce((n=>n.toString()),((n,t)=>n.isEqual(t)))}const If=new J(x.comparator),wf=new ot(x.comparator);function j(...n){let t=wf;for(const e of n)t=t.add(e);return t}const vf=new ot(B);function Af(){return vf}function hi(n,t){if(n.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:hr(t)?"-0":t}}function Gc(n){return{integerValue:""+n}}function Hc(n,t){return Xd(t)?Gc(t):hi(n,t)}class kr{constructor(){this._=void 0}}function Rf(n,t,e){return n instanceof gr?(function(s,o){const a={fields:{[bc]:{stringValue:Cc},[Vc]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return o&&oi(o)&&(o=br(o)),o&&(a.fields[Pc]=o),{mapValue:a}})(e,t):n instanceof Cn?Wc(n,t):n instanceof bn?Qc(n,t):(function(s,o){const a=Kc(s,o),u=Ea(a)+Ea(s.Ae);return xs(a)&&xs(s.Ae)?Gc(u):hi(s.serializer,u)})(n,t)}function Sf(n,t,e){return n instanceof Cn?Wc(n,t):n instanceof bn?Qc(n,t):e}function Kc(n,t){return n instanceof Pn?(function(r){return xs(r)||(function(o){return!!o&&"doubleValue"in o})(r)})(t)?t:{integerValue:0}:null}class gr extends kr{}class Cn extends kr{constructor(t){super(),this.elements=t}}function Wc(n,t){const e=Xc(t);for(const r of n.elements)e.some((s=>Ut(s,r)))||e.push(r);return{arrayValue:{values:e}}}class bn extends kr{constructor(t){super(),this.elements=t}}function Qc(n,t){let e=Xc(t);for(const r of n.elements)e=e.filter((s=>!Ut(s,r)));return{arrayValue:{values:e}}}class Pn extends kr{constructor(t,e){super(),this.serializer=t,this.Ae=e}}function Ea(n){return tt(n.integerValue||n.doubleValue)}function Xc(n){return ai(n)&&n.arrayValue.values?n.arrayValue.values.slice():[]}class Cf{constructor(t,e){this.field=t,this.transform=e}}function bf(n,t){return n.field.isEqual(t.field)&&(function(r,s){return r instanceof Cn&&s instanceof Cn||r instanceof bn&&s instanceof bn?Ue(r.elements,s.elements,Ut):r instanceof Pn&&s instanceof Pn?Ut(r.Ae,s.Ae):r instanceof gr&&s instanceof gr})(n.transform,t.transform)}class Pf{constructor(t,e){this.version=t,this.transformResults=e}}class Mt{constructor(t,e){this.updateTime=t,this.exists=e}static none(){return new Mt}static exists(t){return new Mt(void 0,t)}static updateTime(t){return new Mt(t)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(t){return this.exists===t.exists&&(this.updateTime?!!t.updateTime&&this.updateTime.isEqual(t.updateTime):!t.updateTime)}}function or(n,t){return n.updateTime!==void 0?t.isFoundDocument()&&t.version.isEqual(n.updateTime):n.exists===void 0||n.exists===t.isFoundDocument()}class Nr{}function Yc(n,t){if(!n.hasLocalMutations||t&&t.fields.length===0)return null;if(t===null)return n.isNoDocument()?new Zc(n.key,Mt.none()):new Nn(n.key,n.data,Mt.none());{const e=n.data,r=At.empty();let s=new ot(ht.comparator);for(let o of t.fields)if(!s.has(o)){let a=e.field(o);a===null&&o.length>1&&(o=o.popLast(),a=e.field(o)),a===null?r.delete(o):r.set(o,a),s=s.add(o)}return new he(n.key,r,new St(s.toArray()),Mt.none())}}function Vf(n,t,e){n instanceof Nn?(function(s,o,a){const u=s.value.clone(),h=Ia(s.fieldTransforms,o,a.transformResults);u.setAll(h),o.convertToFoundDocument(a.version,u).setHasCommittedMutations()})(n,t,e):n instanceof he?(function(s,o,a){if(!or(s.precondition,o))return void o.convertToUnknownDocument(a.version);const u=Ia(s.fieldTransforms,o,a.transformResults),h=o.data;h.setAll(Jc(s)),h.setAll(u),o.convertToFoundDocument(a.version,h).setHasCommittedMutations()})(n,t,e):(function(s,o,a){o.convertToNoDocument(a.version).setHasCommittedMutations()})(0,t,e)}function En(n,t,e,r){return n instanceof Nn?(function(o,a,u,h){if(!or(o.precondition,a))return u;const d=o.value.clone(),m=wa(o.fieldTransforms,h,a);return d.setAll(m),a.convertToFoundDocument(a.version,d).setHasLocalMutations(),null})(n,t,e,r):n instanceof he?(function(o,a,u,h){if(!or(o.precondition,a))return u;const d=wa(o.fieldTransforms,h,a),m=a.data;return m.setAll(Jc(o)),m.setAll(d),a.convertToFoundDocument(a.version,m).setHasLocalMutations(),u===null?null:u.unionWith(o.fieldMask.fields).unionWith(o.fieldTransforms.map((T=>T.field)))})(n,t,e,r):(function(o,a,u){return or(o.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u})(n,t,e)}function Df(n,t){let e=null;for(const r of n.fieldTransforms){const s=t.data.field(r.field),o=Kc(r.transform,s||null);o!=null&&(e===null&&(e=At.empty()),e.set(r.field,o))}return e||null}function Ta(n,t){return n.type===t.type&&!!n.key.isEqual(t.key)&&!!n.precondition.isEqual(t.precondition)&&!!(function(r,s){return r===void 0&&s===void 0||!(!r||!s)&&Ue(r,s,((o,a)=>bf(o,a)))})(n.fieldTransforms,t.fieldTransforms)&&(n.type===0?n.value.isEqual(t.value):n.type!==1||n.data.isEqual(t.data)&&n.fieldMask.isEqual(t.fieldMask))}class Nn extends Nr{constructor(t,e,r,s=[]){super(),this.key=t,this.value=e,this.precondition=r,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class he extends Nr{constructor(t,e,r,s,o=[]){super(),this.key=t,this.data=e,this.fieldMask=r,this.precondition=s,this.fieldTransforms=o,this.type=1}getFieldMask(){return this.fieldMask}}function Jc(n){const t=new Map;return n.fieldMask.fields.forEach((e=>{if(!e.isEmpty()){const r=n.data.field(e);t.set(e,r)}})),t}function Ia(n,t,e){const r=new Map;K(n.length===e.length,32656,{Re:e.length,Ve:n.length});for(let s=0;s<e.length;s++){const o=n[s],a=o.transform,u=t.data.field(o.field);r.set(o.field,Sf(a,u,e[s]))}return r}function wa(n,t,e){const r=new Map;for(const s of n){const o=s.transform,a=e.data.field(s.field);r.set(s.field,Rf(o,a,t))}return r}class Zc extends Nr{constructor(t,e){super(),this.key=t,this.precondition=e,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class kf extends Nr{constructor(t,e){super(),this.key=t,this.precondition=e,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Nf{constructor(t,e,r,s){this.batchId=t,this.localWriteTime=e,this.baseMutations=r,this.mutations=s}applyToRemoteDocument(t,e){const r=e.mutationResults;for(let s=0;s<this.mutations.length;s++){const o=this.mutations[s];o.key.isEqual(t.key)&&Vf(o,t,r[s])}}applyToLocalView(t,e){for(const r of this.baseMutations)r.key.isEqual(t.key)&&(e=En(r,t,e,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(t.key)&&(e=En(r,t,e,this.localWriteTime));return e}applyToLocalDocumentSet(t,e){const r=zc();return this.mutations.forEach((s=>{const o=t.get(s.key),a=o.overlayedDocument;let u=this.applyToLocalView(a,o.mutatedFields);u=e.has(s.key)?null:u;const h=Yc(a,u);h!==null&&r.set(s.key,h),a.isValidDocument()||a.convertToNoDocument(L.min())})),r}keys(){return this.mutations.reduce(((t,e)=>t.add(e.key)),j())}isEqual(t){return this.batchId===t.batchId&&Ue(this.mutations,t.mutations,((e,r)=>Ta(e,r)))&&Ue(this.baseMutations,t.baseMutations,((e,r)=>Ta(e,r)))}}class di{constructor(t,e,r,s){this.batch=t,this.commitVersion=e,this.mutationResults=r,this.docVersions=s}static from(t,e,r){K(t.mutations.length===r.length,58842,{me:t.mutations.length,fe:r.length});let s=(function(){return If})();const o=t.mutations;for(let a=0;a<o.length;a++)s=s.insert(o[a].key,r[a].version);return new di(t,e,r,s)}}class Mf{constructor(t,e){this.largestBatchId=t,this.mutation=e}getKey(){return this.mutation.key}isEqual(t){return t!==null&&this.mutation===t.mutation}toString(){return`Overlay{
24
+ largestBatchId: ${this.largestBatchId},
25
+ mutation: ${this.mutation.toString()}
26
+ }`}}class xf{constructor(t,e){this.count=t,this.unchangedNames=e}}var et,q;function Of(n){switch(n){case C.OK:return O(64938);case C.CANCELLED:case C.UNKNOWN:case C.DEADLINE_EXCEEDED:case C.RESOURCE_EXHAUSTED:case C.INTERNAL:case C.UNAVAILABLE:case C.UNAUTHENTICATED:return!1;case C.INVALID_ARGUMENT:case C.NOT_FOUND:case C.ALREADY_EXISTS:case C.PERMISSION_DENIED:case C.FAILED_PRECONDITION:case C.ABORTED:case C.OUT_OF_RANGE:case C.UNIMPLEMENTED:case C.DATA_LOSS:return!0;default:return O(15467,{code:n})}}function tu(n){if(n===void 0)return $t("GRPC error has no .code"),C.UNKNOWN;switch(n){case et.OK:return C.OK;case et.CANCELLED:return C.CANCELLED;case et.UNKNOWN:return C.UNKNOWN;case et.DEADLINE_EXCEEDED:return C.DEADLINE_EXCEEDED;case et.RESOURCE_EXHAUSTED:return C.RESOURCE_EXHAUSTED;case et.INTERNAL:return C.INTERNAL;case et.UNAVAILABLE:return C.UNAVAILABLE;case et.UNAUTHENTICATED:return C.UNAUTHENTICATED;case et.INVALID_ARGUMENT:return C.INVALID_ARGUMENT;case et.NOT_FOUND:return C.NOT_FOUND;case et.ALREADY_EXISTS:return C.ALREADY_EXISTS;case et.PERMISSION_DENIED:return C.PERMISSION_DENIED;case et.FAILED_PRECONDITION:return C.FAILED_PRECONDITION;case et.ABORTED:return C.ABORTED;case et.OUT_OF_RANGE:return C.OUT_OF_RANGE;case et.UNIMPLEMENTED:return C.UNIMPLEMENTED;case et.DATA_LOSS:return C.DATA_LOSS;default:return O(39323,{code:n})}}(q=et||(et={}))[q.OK=0]="OK",q[q.CANCELLED=1]="CANCELLED",q[q.UNKNOWN=2]="UNKNOWN",q[q.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",q[q.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",q[q.NOT_FOUND=5]="NOT_FOUND",q[q.ALREADY_EXISTS=6]="ALREADY_EXISTS",q[q.PERMISSION_DENIED=7]="PERMISSION_DENIED",q[q.UNAUTHENTICATED=16]="UNAUTHENTICATED",q[q.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",q[q.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",q[q.ABORTED=10]="ABORTED",q[q.OUT_OF_RANGE=11]="OUT_OF_RANGE",q[q.UNIMPLEMENTED=12]="UNIMPLEMENTED",q[q.INTERNAL=13]="INTERNAL",q[q.UNAVAILABLE=14]="UNAVAILABLE",q[q.DATA_LOSS=15]="DATA_LOSS";function Lf(){return new TextEncoder}const Ff=new te([4294967295,4294967295],0);function va(n){const t=Lf().encode(n),e=new pc;return e.update(t),new Uint8Array(e.digest())}function Aa(n){const t=new DataView(n.buffer),e=t.getUint32(0,!0),r=t.getUint32(4,!0),s=t.getUint32(8,!0),o=t.getUint32(12,!0);return[new te([e,r],0),new te([s,o],0)]}class fi{constructor(t,e,r){if(this.bitmap=t,this.padding=e,this.hashCount=r,e<0||e>=8)throw new fn(`Invalid padding: ${e}`);if(r<0)throw new fn(`Invalid hash count: ${r}`);if(t.length>0&&this.hashCount===0)throw new fn(`Invalid hash count: ${r}`);if(t.length===0&&e!==0)throw new fn(`Invalid padding when bitmap length is 0: ${e}`);this.ge=8*t.length-e,this.pe=te.fromNumber(this.ge)}ye(t,e,r){let s=t.add(e.multiply(te.fromNumber(r)));return s.compare(Ff)===1&&(s=new te([s.getBits(0),s.getBits(1)],0)),s.modulo(this.pe).toNumber()}we(t){return!!(this.bitmap[Math.floor(t/8)]&1<<t%8)}mightContain(t){if(this.ge===0)return!1;const e=va(t),[r,s]=Aa(e);for(let o=0;o<this.hashCount;o++){const a=this.ye(r,s,o);if(!this.we(a))return!1}return!0}static create(t,e,r){const s=t%8==0?0:8-t%8,o=new Uint8Array(Math.ceil(t/8)),a=new fi(o,s,e);return r.forEach((u=>a.insert(u))),a}insert(t){if(this.ge===0)return;const e=va(t),[r,s]=Aa(e);for(let o=0;o<this.hashCount;o++){const a=this.ye(r,s,o);this.Se(a)}}Se(t){const e=Math.floor(t/8),r=t%8;this.bitmap[e]|=1<<r}}class fn extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Mr{constructor(t,e,r,s,o){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=r,this.documentUpdates=s,this.resolvedLimboDocuments=o}static createSynthesizedRemoteEventForCurrentChange(t,e,r){const s=new Map;return s.set(t,Mn.createSynthesizedTargetChangeForCurrentChange(t,e,r)),new Mr(L.min(),s,new J(B),zt(),j())}}class Mn{constructor(t,e,r,s,o){this.resumeToken=t,this.current=e,this.addedDocuments=r,this.modifiedDocuments=s,this.removedDocuments=o}static createSynthesizedTargetChangeForCurrentChange(t,e,r){return new Mn(r,e,j(),j(),j())}}class ar{constructor(t,e,r,s){this.be=t,this.removedTargetIds=e,this.key=r,this.De=s}}class eu{constructor(t,e){this.targetId=t,this.Ce=e}}class nu{constructor(t,e,r=dt.EMPTY_BYTE_STRING,s=null){this.state=t,this.targetIds=e,this.resumeToken=r,this.cause=s}}class Ra{constructor(){this.ve=0,this.Fe=Sa(),this.Me=dt.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return this.ve!==0}get Be(){return this.Oe}Le(t){t.approximateByteSize()>0&&(this.Oe=!0,this.Me=t)}ke(){let t=j(),e=j(),r=j();return this.Fe.forEach(((s,o)=>{switch(o){case 0:t=t.add(s);break;case 2:e=e.add(s);break;case 1:r=r.add(s);break;default:O(38017,{changeType:o})}})),new Mn(this.Me,this.xe,t,e,r)}qe(){this.Oe=!1,this.Fe=Sa()}Qe(t,e){this.Oe=!0,this.Fe=this.Fe.insert(t,e)}$e(t){this.Oe=!0,this.Fe=this.Fe.remove(t)}Ue(){this.ve+=1}Ke(){this.ve-=1,K(this.ve>=0,3241,{ve:this.ve})}We(){this.Oe=!0,this.xe=!0}}class Uf{constructor(t){this.Ge=t,this.ze=new Map,this.je=zt(),this.Je=er(),this.He=er(),this.Ye=new J(B)}Ze(t){for(const e of t.be)t.De&&t.De.isFoundDocument()?this.Xe(e,t.De):this.et(e,t.key,t.De);for(const e of t.removedTargetIds)this.et(e,t.key,t.De)}tt(t){this.forEachTarget(t,(e=>{const r=this.nt(e);switch(t.state){case 0:this.rt(e)&&r.Le(t.resumeToken);break;case 1:r.Ke(),r.Ne||r.qe(),r.Le(t.resumeToken);break;case 2:r.Ke(),r.Ne||this.removeTarget(e);break;case 3:this.rt(e)&&(r.We(),r.Le(t.resumeToken));break;case 4:this.rt(e)&&(this.it(e),r.Le(t.resumeToken));break;default:O(56790,{state:t.state})}}))}forEachTarget(t,e){t.targetIds.length>0?t.targetIds.forEach(e):this.ze.forEach(((r,s)=>{this.rt(s)&&e(s)}))}st(t){const e=t.targetId,r=t.Ce.count,s=this.ot(e);if(s){const o=s.target;if(Ls(o))if(r===0){const a=new x(o.path);this.et(e,a,gt.newNoDocument(a,L.min()))}else K(r===1,20013,{expectedCount:r});else{const a=this._t(e);if(a!==r){const u=this.ut(t),h=u?this.ct(u,t,a):1;if(h!==0){this.it(e);const d=h===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ye=this.Ye.insert(e,d)}}}}}ut(t){const e=t.Ce.unchangedNames;if(!e||!e.bits)return null;const{bits:{bitmap:r="",padding:s=0},hashCount:o=0}=e;let a,u;try{a=ie(r).toUint8Array()}catch(h){if(h instanceof Sc)return Fe("Decoding the base64 bloom filter in existence filter failed ("+h.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw h}try{u=new fi(a,s,o)}catch(h){return Fe(h instanceof fn?"BloomFilter error: ":"Applying bloom filter failed: ",h),null}return u.ge===0?null:u}ct(t,e,r){return e.Ce.count===r-this.Pt(t,e.targetId)?0:2}Pt(t,e){const r=this.Ge.getRemoteKeysForTarget(e);let s=0;return r.forEach((o=>{const a=this.Ge.ht(),u=`projects/${a.projectId}/databases/${a.database}/documents/${o.path.canonicalString()}`;t.mightContain(u)||(this.et(e,o,null),s++)})),s}Tt(t){const e=new Map;this.ze.forEach(((o,a)=>{const u=this.ot(a);if(u){if(o.current&&Ls(u.target)){const h=new x(u.target.path);this.It(h).has(a)||this.Et(a,h)||this.et(a,h,gt.newNoDocument(h,t))}o.Be&&(e.set(a,o.ke()),o.qe())}}));let r=j();this.He.forEach(((o,a)=>{let u=!0;a.forEachWhile((h=>{const d=this.ot(h);return!d||d.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)})),u&&(r=r.add(o))})),this.je.forEach(((o,a)=>a.setReadTime(t)));const s=new Mr(t,e,this.Ye,this.je,r);return this.je=zt(),this.Je=er(),this.He=er(),this.Ye=new J(B),s}Xe(t,e){if(!this.rt(t))return;const r=this.Et(t,e.key)?2:0;this.nt(t).Qe(e.key,r),this.je=this.je.insert(e.key,e),this.Je=this.Je.insert(e.key,this.It(e.key).add(t)),this.He=this.He.insert(e.key,this.dt(e.key).add(t))}et(t,e,r){if(!this.rt(t))return;const s=this.nt(t);this.Et(t,e)?s.Qe(e,1):s.$e(e),this.He=this.He.insert(e,this.dt(e).delete(t)),this.He=this.He.insert(e,this.dt(e).add(t)),r&&(this.je=this.je.insert(e,r))}removeTarget(t){this.ze.delete(t)}_t(t){const e=this.nt(t).ke();return this.Ge.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size}Ue(t){this.nt(t).Ue()}nt(t){let e=this.ze.get(t);return e||(e=new Ra,this.ze.set(t,e)),e}dt(t){let e=this.He.get(t);return e||(e=new ot(B),this.He=this.He.insert(t,e)),e}It(t){let e=this.Je.get(t);return e||(e=new ot(B),this.Je=this.Je.insert(t,e)),e}rt(t){const e=this.ot(t)!==null;return e||D("WatchChangeAggregator","Detected inactive target",t),e}ot(t){const e=this.ze.get(t);return e&&e.Ne?null:this.Ge.At(t)}it(t){this.ze.set(t,new Ra),this.Ge.getRemoteKeysForTarget(t).forEach((e=>{this.et(t,e,null)}))}Et(t,e){return this.Ge.getRemoteKeysForTarget(t).has(e)}}function er(){return new J(x.comparator)}function Sa(){return new J(x.comparator)}const Bf={asc:"ASCENDING",desc:"DESCENDING"},jf={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},qf={and:"AND",or:"OR"};class $f{constructor(t,e){this.databaseId=t,this.useProto3Json=e}}function Us(n,t){return n.useProto3Json||Cr(t)?t:{value:t}}function _r(n,t){return n.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function ru(n,t){return n.useProto3Json?t.toBase64():t.toUint8Array()}function zf(n,t){return _r(n,t.toTimestamp())}function xt(n){return K(!!n,49232),L.fromTimestamp((function(e){const r=se(e);return new X(r.seconds,r.nanos)})(n))}function mi(n,t){return Bs(n,t).canonicalString()}function Bs(n,t){const e=(function(s){return new Y(["projects",s.projectId,"databases",s.database])})(n).child("documents");return t===void 0?e:e.child(t)}function su(n){const t=Y.fromString(n);return K(uu(t),10190,{key:t.toString()}),t}function js(n,t){return mi(n.databaseId,t.path)}function Ts(n,t){const e=su(t);if(e.get(1)!==n.databaseId.projectId)throw new N(C.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+e.get(1)+" vs "+n.databaseId.projectId);if(e.get(3)!==n.databaseId.database)throw new N(C.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+e.get(3)+" vs "+n.databaseId.database);return new x(ou(e))}function iu(n,t){return mi(n.databaseId,t)}function Gf(n){const t=su(n);return t.length===4?Y.emptyPath():ou(t)}function qs(n){return new Y(["projects",n.databaseId.projectId,"databases",n.databaseId.database]).canonicalString()}function ou(n){return K(n.length>4&&n.get(4)==="documents",29091,{key:n.toString()}),n.popFirst(5)}function Ca(n,t,e){return{name:js(n,t),fields:e.value.mapValue.fields}}function Hf(n,t){let e;if("targetChange"in t){t.targetChange;const r=(function(d){return d==="NO_CHANGE"?0:d==="ADD"?1:d==="REMOVE"?2:d==="CURRENT"?3:d==="RESET"?4:O(39313,{state:d})})(t.targetChange.targetChangeType||"NO_CHANGE"),s=t.targetChange.targetIds||[],o=(function(d,m){return d.useProto3Json?(K(m===void 0||typeof m=="string",58123),dt.fromBase64String(m||"")):(K(m===void 0||m instanceof Buffer||m instanceof Uint8Array,16193),dt.fromUint8Array(m||new Uint8Array))})(n,t.targetChange.resumeToken),a=t.targetChange.cause,u=a&&(function(d){const m=d.code===void 0?C.UNKNOWN:tu(d.code);return new N(m,d.message||"")})(a);e=new nu(r,s,o,u||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const s=Ts(n,r.document.name),o=xt(r.document.updateTime),a=r.document.createTime?xt(r.document.createTime):L.min(),u=new At({mapValue:{fields:r.document.fields}}),h=gt.newFoundDocument(s,o,a,u),d=r.targetIds||[],m=r.removedTargetIds||[];e=new ar(d,m,h.key,h)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const s=Ts(n,r.document),o=r.readTime?xt(r.readTime):L.min(),a=gt.newNoDocument(s,o),u=r.removedTargetIds||[];e=new ar([],u,a.key,a)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const s=Ts(n,r.document),o=r.removedTargetIds||[];e=new ar([],o,s,null)}else{if(!("filter"in t))return O(11601,{Rt:t});{t.filter;const r=t.filter;r.targetId;const{count:s=0,unchangedNames:o}=r,a=new xf(s,o),u=r.targetId;e=new eu(u,a)}}return e}function Kf(n,t){let e;if(t instanceof Nn)e={update:Ca(n,t.key,t.value)};else if(t instanceof Zc)e={delete:js(n,t.key)};else if(t instanceof he)e={update:Ca(n,t.key,t.data),updateMask:nm(t.fieldMask)};else{if(!(t instanceof kf))return O(16599,{Vt:t.type});e={verify:js(n,t.key)}}return t.fieldTransforms.length>0&&(e.updateTransforms=t.fieldTransforms.map((r=>(function(o,a){const u=a.transform;if(u instanceof gr)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof Cn)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof bn)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof Pn)return{fieldPath:a.field.canonicalString(),increment:u.Ae};throw O(20930,{transform:a.transform})})(0,r)))),t.precondition.isNone||(e.currentDocument=(function(s,o){return o.updateTime!==void 0?{updateTime:zf(s,o.updateTime)}:o.exists!==void 0?{exists:o.exists}:O(27497)})(n,t.precondition)),e}function Wf(n,t){return n&&n.length>0?(K(t!==void 0,14353),n.map((e=>(function(s,o){let a=s.updateTime?xt(s.updateTime):xt(o);return a.isEqual(L.min())&&(a=xt(o)),new Pf(a,s.transformResults||[])})(e,t)))):[]}function Qf(n,t){return{documents:[iu(n,t.path)]}}function Xf(n,t){const e={structuredQuery:{}},r=t.path;let s;t.collectionGroup!==null?(s=r,e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(s=r.popLast(),e.structuredQuery.from=[{collectionId:r.lastSegment()}]),e.parent=iu(n,s);const o=(function(d){if(d.length!==0)return cu(Bt.create(d,"and"))})(t.filters);o&&(e.structuredQuery.where=o);const a=(function(d){if(d.length!==0)return d.map((m=>(function(v){return{field:Me(v.field),direction:Zf(v.dir)}})(m)))})(t.orderBy);a&&(e.structuredQuery.orderBy=a);const u=Us(n,t.limit);return u!==null&&(e.structuredQuery.limit=u),t.startAt&&(e.structuredQuery.startAt=(function(d){return{before:d.inclusive,values:d.position}})(t.startAt)),t.endAt&&(e.structuredQuery.endAt=(function(d){return{before:!d.inclusive,values:d.position}})(t.endAt)),{ft:e,parent:s}}function Yf(n){let t=Gf(n.parent);const e=n.structuredQuery,r=e.from?e.from.length:0;let s=null;if(r>0){K(r===1,65062);const m=e.from[0];m.allDescendants?s=m.collectionId:t=t.child(m.collectionId)}let o=[];e.where&&(o=(function(T){const v=au(T);return v instanceof Bt&&Oc(v)?v.getFilters():[v]})(e.where));let a=[];e.orderBy&&(a=(function(T){return T.map((v=>(function(k){return new pr(xe(k.field),(function(V){switch(V){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(k.direction))})(v)))})(e.orderBy));let u=null;e.limit&&(u=(function(T){let v;return v=typeof T=="object"?T.value:T,Cr(v)?null:v})(e.limit));let h=null;e.startAt&&(h=(function(T){const v=!!T.before,b=T.values||[];return new mr(b,v)})(e.startAt));let d=null;return e.endAt&&(d=(function(T){const v=!T.before,b=T.values||[];return new mr(b,v)})(e.endAt)),pf(t,s,a,o,u,"F",h,d)}function Jf(n,t){const e=(function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return O(28987,{purpose:s})}})(t.purpose);return e==null?null:{"goog-listen-tags":e}}function au(n){return n.unaryFilter!==void 0?(function(e){switch(e.unaryFilter.op){case"IS_NAN":const r=xe(e.unaryFilter.field);return st.create(r,"==",{doubleValue:NaN});case"IS_NULL":const s=xe(e.unaryFilter.field);return st.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const o=xe(e.unaryFilter.field);return st.create(o,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const a=xe(e.unaryFilter.field);return st.create(a,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return O(61313);default:return O(60726)}})(n):n.fieldFilter!==void 0?(function(e){return st.create(xe(e.fieldFilter.field),(function(s){switch(s){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return O(58110);default:return O(50506)}})(e.fieldFilter.op),e.fieldFilter.value)})(n):n.compositeFilter!==void 0?(function(e){return Bt.create(e.compositeFilter.filters.map((r=>au(r))),(function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return O(1026)}})(e.compositeFilter.op))})(n):O(30097,{filter:n})}function Zf(n){return Bf[n]}function tm(n){return jf[n]}function em(n){return qf[n]}function Me(n){return{fieldPath:n.canonicalString()}}function xe(n){return ht.fromServerFormat(n.fieldPath)}function cu(n){return n instanceof st?(function(e){if(e.op==="=="){if(ma(e.value))return{unaryFilter:{field:Me(e.field),op:"IS_NAN"}};if(fa(e.value))return{unaryFilter:{field:Me(e.field),op:"IS_NULL"}}}else if(e.op==="!="){if(ma(e.value))return{unaryFilter:{field:Me(e.field),op:"IS_NOT_NAN"}};if(fa(e.value))return{unaryFilter:{field:Me(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Me(e.field),op:tm(e.op),value:e.value}}})(n):n instanceof Bt?(function(e){const r=e.getFilters().map((s=>cu(s)));return r.length===1?r[0]:{compositeFilter:{op:em(e.op),filters:r}}})(n):O(54877,{filter:n})}function nm(n){const t=[];return n.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function uu(n){return n.length>=4&&n.get(0)==="projects"&&n.get(2)==="databases"}class Yt{constructor(t,e,r,s,o=L.min(),a=L.min(),u=dt.EMPTY_BYTE_STRING,h=null){this.target=t,this.targetId=e,this.purpose=r,this.sequenceNumber=s,this.snapshotVersion=o,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=u,this.expectedCount=h}withSequenceNumber(t){return new Yt(this.target,this.targetId,this.purpose,t,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(t,e){return new Yt(this.target,this.targetId,this.purpose,this.sequenceNumber,e,this.lastLimboFreeSnapshotVersion,t,null)}withExpectedCount(t){return new Yt(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,t)}withLastLimboFreeSnapshotVersion(t){return new Yt(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,t,this.resumeToken,this.expectedCount)}}class rm{constructor(t){this.yt=t}}function sm(n){const t=Yf({parent:n.parent,structuredQuery:n.structuredQuery});return n.limitType==="LAST"?Fs(t,t.limit,"L"):t}class im{constructor(){this.Cn=new om}addToCollectionParentIndex(t,e){return this.Cn.add(e),S.resolve()}getCollectionParents(t,e){return S.resolve(this.Cn.getEntries(e))}addFieldIndex(t,e){return S.resolve()}deleteFieldIndex(t,e){return S.resolve()}deleteAllFieldIndexes(t){return S.resolve()}createTargetIndexes(t,e){return S.resolve()}getDocumentsMatchingTarget(t,e){return S.resolve(null)}getIndexType(t,e){return S.resolve(0)}getFieldIndexes(t,e){return S.resolve([])}getNextCollectionGroupToUpdate(t){return S.resolve(null)}getMinOffset(t,e){return S.resolve(re.min())}getMinOffsetFromCollectionGroup(t,e){return S.resolve(re.min())}updateCollectionGroup(t,e,r){return S.resolve()}updateIndexEntries(t,e){return S.resolve()}}class om{constructor(){this.index={}}add(t){const e=t.lastSegment(),r=t.popLast(),s=this.index[e]||new ot(Y.comparator),o=!s.has(r);return this.index[e]=s.add(r),o}has(t){const e=t.lastSegment(),r=t.popLast(),s=this.index[e];return s&&s.has(r)}getEntries(t){return(this.index[t]||new ot(Y.comparator)).toArray()}}const ba={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},lu=41943040;class vt{static withCacheSize(t){return new vt(t,vt.DEFAULT_COLLECTION_PERCENTILE,vt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(t,e,r){this.cacheSizeCollectionThreshold=t,this.percentileToCollect=e,this.maximumSequenceNumbersToCollect=r}}vt.DEFAULT_COLLECTION_PERCENTILE=10,vt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,vt.DEFAULT=new vt(lu,vt.DEFAULT_COLLECTION_PERCENTILE,vt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),vt.DISABLED=new vt(-1,0,0);class qe{constructor(t){this.ar=t}next(){return this.ar+=2,this.ar}static ur(){return new qe(0)}static cr(){return new qe(-1)}}const Pa="LruGarbageCollector",am=1048576;function Va([n,t],[e,r]){const s=B(n,e);return s===0?B(t,r):s}class cm{constructor(t){this.Ir=t,this.buffer=new ot(Va),this.Er=0}dr(){return++this.Er}Ar(t){const e=[t,this.dr()];if(this.buffer.size<this.Ir)this.buffer=this.buffer.add(e);else{const r=this.buffer.last();Va(e,r)<0&&(this.buffer=this.buffer.delete(r).add(e))}}get maxValue(){return this.buffer.last()[0]}}class um{constructor(t,e,r){this.garbageCollector=t,this.asyncQueue=e,this.localStore=r,this.Rr=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Vr(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return this.Rr!==null}Vr(t){D(Pa,`Garbage collection scheduled in ${t}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,(async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){He(e)?D(Pa,"Ignoring IndexedDB error during garbage collection: ",e):await Ge(e)}await this.Vr(3e5)}))}}class lm{constructor(t,e){this.mr=t,this.params=e}calculateTargetCount(t,e){return this.mr.gr(t).next((r=>Math.floor(e/100*r)))}nthSequenceNumber(t,e){if(e===0)return S.resolve(Sr.ce);const r=new cm(e);return this.mr.forEachTarget(t,(s=>r.Ar(s.sequenceNumber))).next((()=>this.mr.pr(t,(s=>r.Ar(s))))).next((()=>r.maxValue))}removeTargets(t,e,r){return this.mr.removeTargets(t,e,r)}removeOrphanedDocuments(t,e){return this.mr.removeOrphanedDocuments(t,e)}collect(t,e){return this.params.cacheSizeCollectionThreshold===-1?(D("LruGarbageCollector","Garbage collection skipped; disabled"),S.resolve(ba)):this.getCacheSize(t).next((r=>r<this.params.cacheSizeCollectionThreshold?(D("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),ba):this.yr(t,e)))}getCacheSize(t){return this.mr.getCacheSize(t)}yr(t,e){let r,s,o,a,u,h,d;const m=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next((T=>(T>this.params.maximumSequenceNumbersToCollect?(D("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${T}`),s=this.params.maximumSequenceNumbersToCollect):s=T,a=Date.now(),this.nthSequenceNumber(t,s)))).next((T=>(r=T,u=Date.now(),this.removeTargets(t,r,e)))).next((T=>(o=T,h=Date.now(),this.removeOrphanedDocuments(t,r)))).next((T=>(d=Date.now(),ke()<=$.DEBUG&&D("LruGarbageCollector",`LRU Garbage Collection
27
+ Counted targets in ${a-m}ms
28
+ Determined least recently used ${s} in `+(u-a)+`ms
29
+ Removed ${o} targets in `+(h-u)+`ms
30
+ Removed ${T} documents in `+(d-h)+`ms
31
+ Total Duration: ${d-m}ms`),S.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:o,documentsRemoved:T}))))}}function hm(n,t){return new lm(n,t)}class dm{constructor(){this.changes=new Ce((t=>t.toString()),((t,e)=>t.isEqual(e))),this.changesApplied=!1}addEntry(t){this.assertNotApplied(),this.changes.set(t.key,t)}removeEntry(t,e){this.assertNotApplied(),this.changes.set(t,gt.newInvalidDocument(t).setReadTime(e))}getEntry(t,e){this.assertNotApplied();const r=this.changes.get(e);return r!==void 0?S.resolve(r):this.getFromCache(t,e)}getEntries(t,e){return this.getAllFromCache(t,e)}apply(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)}assertNotApplied(){}}class fm{constructor(t,e){this.overlayedDocument=t,this.mutatedFields=e}}class mm{constructor(t,e,r,s){this.remoteDocumentCache=t,this.mutationQueue=e,this.documentOverlayCache=r,this.indexManager=s}getDocument(t,e){let r=null;return this.documentOverlayCache.getOverlay(t,e).next((s=>(r=s,this.remoteDocumentCache.getEntry(t,e)))).next((s=>(r!==null&&En(r.mutation,s,St.empty(),X.now()),s)))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next((r=>this.getLocalViewOfDocuments(t,r,j()).next((()=>r))))}getLocalViewOfDocuments(t,e,r=j()){const s=Ee();return this.populateOverlays(t,s,e).next((()=>this.computeViews(t,e,s,r).next((o=>{let a=dn();return o.forEach(((u,h)=>{a=a.insert(u,h.overlayedDocument)})),a}))))}getOverlayedDocuments(t,e){const r=Ee();return this.populateOverlays(t,r,e).next((()=>this.computeViews(t,e,r,j())))}populateOverlays(t,e,r){const s=[];return r.forEach((o=>{e.has(o)||s.push(o)})),this.documentOverlayCache.getOverlays(t,s).next((o=>{o.forEach(((a,u)=>{e.set(a,u)}))}))}computeViews(t,e,r,s){let o=zt();const a=yn(),u=(function(){return yn()})();return e.forEach(((h,d)=>{const m=r.get(d.key);s.has(d.key)&&(m===void 0||m.mutation instanceof he)?o=o.insert(d.key,d):m!==void 0?(a.set(d.key,m.mutation.getFieldMask()),En(m.mutation,d,m.mutation.getFieldMask(),X.now())):a.set(d.key,St.empty())})),this.recalculateAndSaveOverlays(t,o).next((h=>(h.forEach(((d,m)=>a.set(d,m))),e.forEach(((d,m)=>u.set(d,new fm(m,a.get(d)??null)))),u)))}recalculateAndSaveOverlays(t,e){const r=yn();let s=new J(((a,u)=>a-u)),o=j();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t,e).next((a=>{for(const u of a)u.keys().forEach((h=>{const d=e.get(h);if(d===null)return;let m=r.get(h)||St.empty();m=u.applyToLocalView(d,m),r.set(h,m);const T=(s.get(u.batchId)||j()).add(h);s=s.insert(u.batchId,T)}))})).next((()=>{const a=[],u=s.getReverseIterator();for(;u.hasNext();){const h=u.getNext(),d=h.key,m=h.value,T=zc();m.forEach((v=>{if(!o.has(v)){const b=Yc(e.get(v),r.get(v));b!==null&&T.set(v,b),o=o.add(v)}})),a.push(this.documentOverlayCache.saveOverlays(t,d,T))}return S.waitFor(a)})).next((()=>r))}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next((r=>this.recalculateAndSaveOverlays(t,r)))}getDocumentsMatchingQuery(t,e,r,s){return(function(a){return x.isDocumentKey(a.path)&&a.collectionGroup===null&&a.filters.length===0})(e)?this.getDocumentsMatchingDocumentQuery(t,e.path):gf(e)?this.getDocumentsMatchingCollectionGroupQuery(t,e,r,s):this.getDocumentsMatchingCollectionQuery(t,e,r,s)}getNextDocuments(t,e,r,s){return this.remoteDocumentCache.getAllFromCollectionGroup(t,e,r,s).next((o=>{const a=s-o.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(t,e,r.largestBatchId,s-o.size):S.resolve(Ee());let u=vn,h=o;return a.next((d=>S.forEach(d,((m,T)=>(u<T.largestBatchId&&(u=T.largestBatchId),o.get(m)?S.resolve():this.remoteDocumentCache.getEntry(t,m).next((v=>{h=h.insert(m,v)}))))).next((()=>this.populateOverlays(t,d,o))).next((()=>this.computeViews(t,h,d,j()))).next((m=>({batchId:u,changes:$c(m)})))))}))}getDocumentsMatchingDocumentQuery(t,e){return this.getDocument(t,new x(e)).next((r=>{let s=dn();return r.isFoundDocument()&&(s=s.insert(r.key,r)),s}))}getDocumentsMatchingCollectionGroupQuery(t,e,r,s){const o=e.collectionGroup;let a=dn();return this.indexManager.getCollectionParents(t,o).next((u=>S.forEach(u,(h=>{const d=(function(T,v){return new Pr(v,null,T.explicitOrderBy.slice(),T.filters.slice(),T.limit,T.limitType,T.startAt,T.endAt)})(e,h.child(o));return this.getDocumentsMatchingCollectionQuery(t,d,r,s).next((m=>{m.forEach(((T,v)=>{a=a.insert(T,v)}))}))})).next((()=>a))))}getDocumentsMatchingCollectionQuery(t,e,r,s){let o;return this.documentOverlayCache.getOverlaysForCollection(t,e.path,r.largestBatchId).next((a=>(o=a,this.remoteDocumentCache.getDocumentsMatchingQuery(t,e,r,o,s)))).next((a=>{o.forEach(((h,d)=>{const m=d.getKey();a.get(m)===null&&(a=a.insert(m,gt.newInvalidDocument(m)))}));let u=dn();return a.forEach(((h,d)=>{const m=o.get(h);m!==void 0&&En(m.mutation,d,St.empty(),X.now()),Dr(e,d)&&(u=u.insert(h,d))})),u}))}}class pm{constructor(t){this.serializer=t,this.Lr=new Map,this.kr=new Map}getBundleMetadata(t,e){return S.resolve(this.Lr.get(e))}saveBundleMetadata(t,e){return this.Lr.set(e.id,(function(s){return{id:s.id,version:s.version,createTime:xt(s.createTime)}})(e)),S.resolve()}getNamedQuery(t,e){return S.resolve(this.kr.get(e))}saveNamedQuery(t,e){return this.kr.set(e.name,(function(s){return{name:s.name,query:sm(s.bundledQuery),readTime:xt(s.readTime)}})(e)),S.resolve()}}class gm{constructor(){this.overlays=new J(x.comparator),this.qr=new Map}getOverlay(t,e){return S.resolve(this.overlays.get(e))}getOverlays(t,e){const r=Ee();return S.forEach(e,(s=>this.getOverlay(t,s).next((o=>{o!==null&&r.set(s,o)})))).next((()=>r))}saveOverlays(t,e,r){return r.forEach(((s,o)=>{this.St(t,e,o)})),S.resolve()}removeOverlaysForBatchId(t,e,r){const s=this.qr.get(r);return s!==void 0&&(s.forEach((o=>this.overlays=this.overlays.remove(o))),this.qr.delete(r)),S.resolve()}getOverlaysForCollection(t,e,r){const s=Ee(),o=e.length+1,a=new x(e.child("")),u=this.overlays.getIteratorFrom(a);for(;u.hasNext();){const h=u.getNext().value,d=h.getKey();if(!e.isPrefixOf(d.path))break;d.path.length===o&&h.largestBatchId>r&&s.set(h.getKey(),h)}return S.resolve(s)}getOverlaysForCollectionGroup(t,e,r,s){let o=new J(((d,m)=>d-m));const a=this.overlays.getIterator();for(;a.hasNext();){const d=a.getNext().value;if(d.getKey().getCollectionGroup()===e&&d.largestBatchId>r){let m=o.get(d.largestBatchId);m===null&&(m=Ee(),o=o.insert(d.largestBatchId,m)),m.set(d.getKey(),d)}}const u=Ee(),h=o.getIterator();for(;h.hasNext()&&(h.getNext().value.forEach(((d,m)=>u.set(d,m))),!(u.size()>=s)););return S.resolve(u)}St(t,e,r){const s=this.overlays.get(r.key);if(s!==null){const a=this.qr.get(s.largestBatchId).delete(r.key);this.qr.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(r.key,new Mf(e,r));let o=this.qr.get(e);o===void 0&&(o=j(),this.qr.set(e,o)),this.qr.set(e,o.add(r.key))}}class _m{constructor(){this.sessionToken=dt.EMPTY_BYTE_STRING}getSessionToken(t){return S.resolve(this.sessionToken)}setSessionToken(t,e){return this.sessionToken=e,S.resolve()}}class pi{constructor(){this.Qr=new ot(ut.$r),this.Ur=new ot(ut.Kr)}isEmpty(){return this.Qr.isEmpty()}addReference(t,e){const r=new ut(t,e);this.Qr=this.Qr.add(r),this.Ur=this.Ur.add(r)}Wr(t,e){t.forEach((r=>this.addReference(r,e)))}removeReference(t,e){this.Gr(new ut(t,e))}zr(t,e){t.forEach((r=>this.removeReference(r,e)))}jr(t){const e=new x(new Y([])),r=new ut(e,t),s=new ut(e,t+1),o=[];return this.Ur.forEachInRange([r,s],(a=>{this.Gr(a),o.push(a.key)})),o}Jr(){this.Qr.forEach((t=>this.Gr(t)))}Gr(t){this.Qr=this.Qr.delete(t),this.Ur=this.Ur.delete(t)}Hr(t){const e=new x(new Y([])),r=new ut(e,t),s=new ut(e,t+1);let o=j();return this.Ur.forEachInRange([r,s],(a=>{o=o.add(a.key)})),o}containsKey(t){const e=new ut(t,0),r=this.Qr.firstAfterOrEqual(e);return r!==null&&t.isEqual(r.key)}}class ut{constructor(t,e){this.key=t,this.Yr=e}static $r(t,e){return x.comparator(t.key,e.key)||B(t.Yr,e.Yr)}static Kr(t,e){return B(t.Yr,e.Yr)||x.comparator(t.key,e.key)}}class ym{constructor(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutationQueue=[],this.tr=1,this.Zr=new ot(ut.$r)}checkEmpty(t){return S.resolve(this.mutationQueue.length===0)}addMutationBatch(t,e,r,s){const o=this.tr;this.tr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const a=new Nf(o,e,r,s);this.mutationQueue.push(a);for(const u of s)this.Zr=this.Zr.add(new ut(u.key,o)),this.indexManager.addToCollectionParentIndex(t,u.key.path.popLast());return S.resolve(a)}lookupMutationBatch(t,e){return S.resolve(this.Xr(e))}getNextMutationBatchAfterBatchId(t,e){const r=e+1,s=this.ei(r),o=s<0?0:s;return S.resolve(this.mutationQueue.length>o?this.mutationQueue[o]:null)}getHighestUnacknowledgedBatchId(){return S.resolve(this.mutationQueue.length===0?ii:this.tr-1)}getAllMutationBatches(t){return S.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(t,e){const r=new ut(e,0),s=new ut(e,Number.POSITIVE_INFINITY),o=[];return this.Zr.forEachInRange([r,s],(a=>{const u=this.Xr(a.Yr);o.push(u)})),S.resolve(o)}getAllMutationBatchesAffectingDocumentKeys(t,e){let r=new ot(B);return e.forEach((s=>{const o=new ut(s,0),a=new ut(s,Number.POSITIVE_INFINITY);this.Zr.forEachInRange([o,a],(u=>{r=r.add(u.Yr)}))})),S.resolve(this.ti(r))}getAllMutationBatchesAffectingQuery(t,e){const r=e.path,s=r.length+1;let o=r;x.isDocumentKey(o)||(o=o.child(""));const a=new ut(new x(o),0);let u=new ot(B);return this.Zr.forEachWhile((h=>{const d=h.key.path;return!!r.isPrefixOf(d)&&(d.length===s&&(u=u.add(h.Yr)),!0)}),a),S.resolve(this.ti(u))}ti(t){const e=[];return t.forEach((r=>{const s=this.Xr(r);s!==null&&e.push(s)})),e}removeMutationBatch(t,e){K(this.ni(e.batchId,"removed")===0,55003),this.mutationQueue.shift();let r=this.Zr;return S.forEach(e.mutations,(s=>{const o=new ut(s.key,e.batchId);return r=r.delete(o),this.referenceDelegate.markPotentiallyOrphaned(t,s.key)})).next((()=>{this.Zr=r}))}ir(t){}containsKey(t,e){const r=new ut(e,0),s=this.Zr.firstAfterOrEqual(r);return S.resolve(e.isEqual(s&&s.key))}performConsistencyCheck(t){return this.mutationQueue.length,S.resolve()}ni(t,e){return this.ei(t)}ei(t){return this.mutationQueue.length===0?0:t-this.mutationQueue[0].batchId}Xr(t){const e=this.ei(t);return e<0||e>=this.mutationQueue.length?null:this.mutationQueue[e]}}class Em{constructor(t){this.ri=t,this.docs=(function(){return new J(x.comparator)})(),this.size=0}setIndexManager(t){this.indexManager=t}addEntry(t,e){const r=e.key,s=this.docs.get(r),o=s?s.size:0,a=this.ri(e);return this.docs=this.docs.insert(r,{document:e.mutableCopy(),size:a}),this.size+=a-o,this.indexManager.addToCollectionParentIndex(t,r.path.popLast())}removeEntry(t){const e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}getEntry(t,e){const r=this.docs.get(e);return S.resolve(r?r.document.mutableCopy():gt.newInvalidDocument(e))}getEntries(t,e){let r=zt();return e.forEach((s=>{const o=this.docs.get(s);r=r.insert(s,o?o.document.mutableCopy():gt.newInvalidDocument(s))})),S.resolve(r)}getDocumentsMatchingQuery(t,e,r,s){let o=zt();const a=e.path,u=new x(a.child("__id-9223372036854775808__")),h=this.docs.getIteratorFrom(u);for(;h.hasNext();){const{key:d,value:{document:m}}=h.getNext();if(!a.isPrefixOf(d.path))break;d.path.length>a.length+1||Hd(Gd(m),r)<=0||(s.has(m.key)||Dr(e,m))&&(o=o.insert(m.key,m.mutableCopy()))}return S.resolve(o)}getAllFromCollectionGroup(t,e,r,s){O(9500)}ii(t,e){return S.forEach(this.docs,(r=>e(r)))}newChangeBuffer(t){return new Tm(this)}getSize(t){return S.resolve(this.size)}}class Tm extends dm{constructor(t){super(),this.Nr=t}applyChanges(t){const e=[];return this.changes.forEach(((r,s)=>{s.isValidDocument()?e.push(this.Nr.addEntry(t,s)):this.Nr.removeEntry(r)})),S.waitFor(e)}getFromCache(t,e){return this.Nr.getEntry(t,e)}getAllFromCache(t,e){return this.Nr.getEntries(t,e)}}class Im{constructor(t){this.persistence=t,this.si=new Ce((e=>ci(e)),ui),this.lastRemoteSnapshotVersion=L.min(),this.highestTargetId=0,this.oi=0,this._i=new pi,this.targetCount=0,this.ai=qe.ur()}forEachTarget(t,e){return this.si.forEach(((r,s)=>e(s))),S.resolve()}getLastRemoteSnapshotVersion(t){return S.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(t){return S.resolve(this.oi)}allocateTargetId(t){return this.highestTargetId=this.ai.next(),S.resolve(this.highestTargetId)}setTargetsMetadata(t,e,r){return r&&(this.lastRemoteSnapshotVersion=r),e>this.oi&&(this.oi=e),S.resolve()}Pr(t){this.si.set(t.target,t);const e=t.targetId;e>this.highestTargetId&&(this.ai=new qe(e),this.highestTargetId=e),t.sequenceNumber>this.oi&&(this.oi=t.sequenceNumber)}addTargetData(t,e){return this.Pr(e),this.targetCount+=1,S.resolve()}updateTargetData(t,e){return this.Pr(e),S.resolve()}removeTargetData(t,e){return this.si.delete(e.target),this._i.jr(e.targetId),this.targetCount-=1,S.resolve()}removeTargets(t,e,r){let s=0;const o=[];return this.si.forEach(((a,u)=>{u.sequenceNumber<=e&&r.get(u.targetId)===null&&(this.si.delete(a),o.push(this.removeMatchingKeysForTargetId(t,u.targetId)),s++)})),S.waitFor(o).next((()=>s))}getTargetCount(t){return S.resolve(this.targetCount)}getTargetData(t,e){const r=this.si.get(e)||null;return S.resolve(r)}addMatchingKeys(t,e,r){return this._i.Wr(e,r),S.resolve()}removeMatchingKeys(t,e,r){this._i.zr(e,r);const s=this.persistence.referenceDelegate,o=[];return s&&e.forEach((a=>{o.push(s.markPotentiallyOrphaned(t,a))})),S.waitFor(o)}removeMatchingKeysForTargetId(t,e){return this._i.jr(e),S.resolve()}getMatchingKeysForTargetId(t,e){const r=this._i.Hr(e);return S.resolve(r)}containsKey(t,e){return S.resolve(this._i.containsKey(e))}}class hu{constructor(t,e){this.ui={},this.overlays={},this.ci=new Sr(0),this.li=!1,this.li=!0,this.hi=new _m,this.referenceDelegate=t(this),this.Pi=new Im(this),this.indexManager=new im,this.remoteDocumentCache=(function(s){return new Em(s)})((r=>this.referenceDelegate.Ti(r))),this.serializer=new rm(e),this.Ii=new pm(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.li=!1,Promise.resolve()}get started(){return this.li}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(t){return this.indexManager}getDocumentOverlayCache(t){let e=this.overlays[t.toKey()];return e||(e=new gm,this.overlays[t.toKey()]=e),e}getMutationQueue(t,e){let r=this.ui[t.toKey()];return r||(r=new ym(e,this.referenceDelegate),this.ui[t.toKey()]=r),r}getGlobalsCache(){return this.hi}getTargetCache(){return this.Pi}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ii}runTransaction(t,e,r){D("MemoryPersistence","Starting transaction:",t);const s=new wm(this.ci.next());return this.referenceDelegate.Ei(),r(s).next((o=>this.referenceDelegate.di(s).next((()=>o)))).toPromise().then((o=>(s.raiseOnCommittedEvent(),o)))}Ai(t,e){return S.or(Object.values(this.ui).map((r=>()=>r.containsKey(t,e))))}}class wm extends Wd{constructor(t){super(),this.currentSequenceNumber=t}}class gi{constructor(t){this.persistence=t,this.Ri=new pi,this.Vi=null}static mi(t){return new gi(t)}get fi(){if(this.Vi)return this.Vi;throw O(60996)}addReference(t,e,r){return this.Ri.addReference(r,e),this.fi.delete(r.toString()),S.resolve()}removeReference(t,e,r){return this.Ri.removeReference(r,e),this.fi.add(r.toString()),S.resolve()}markPotentiallyOrphaned(t,e){return this.fi.add(e.toString()),S.resolve()}removeTarget(t,e){this.Ri.jr(e.targetId).forEach((s=>this.fi.add(s.toString())));const r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(t,e.targetId).next((s=>{s.forEach((o=>this.fi.add(o.toString())))})).next((()=>r.removeTargetData(t,e)))}Ei(){this.Vi=new Set}di(t){const e=this.persistence.getRemoteDocumentCache().newChangeBuffer();return S.forEach(this.fi,(r=>{const s=x.fromPath(r);return this.gi(t,s).next((o=>{o||e.removeEntry(s,L.min())}))})).next((()=>(this.Vi=null,e.apply(t))))}updateLimboDocument(t,e){return this.gi(t,e).next((r=>{r?this.fi.delete(e.toString()):this.fi.add(e.toString())}))}Ti(t){return 0}gi(t,e){return S.or([()=>S.resolve(this.Ri.containsKey(e)),()=>this.persistence.getTargetCache().containsKey(t,e),()=>this.persistence.Ai(t,e)])}}class yr{constructor(t,e){this.persistence=t,this.pi=new Ce((r=>Yd(r.path)),((r,s)=>r.isEqual(s))),this.garbageCollector=hm(this,e)}static mi(t,e){return new yr(t,e)}Ei(){}di(t){return S.resolve()}forEachTarget(t,e){return this.persistence.getTargetCache().forEachTarget(t,e)}gr(t){const e=this.wr(t);return this.persistence.getTargetCache().getTargetCount(t).next((r=>e.next((s=>r+s))))}wr(t){let e=0;return this.pr(t,(r=>{e++})).next((()=>e))}pr(t,e){return S.forEach(this.pi,((r,s)=>this.br(t,r,s).next((o=>o?S.resolve():e(s)))))}removeTargets(t,e,r){return this.persistence.getTargetCache().removeTargets(t,e,r)}removeOrphanedDocuments(t,e){let r=0;const s=this.persistence.getRemoteDocumentCache(),o=s.newChangeBuffer();return s.ii(t,(a=>this.br(t,a,e).next((u=>{u||(r++,o.removeEntry(a,L.min()))})))).next((()=>o.apply(t))).next((()=>r))}markPotentiallyOrphaned(t,e){return this.pi.set(e,t.currentSequenceNumber),S.resolve()}removeTarget(t,e){const r=e.withSequenceNumber(t.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(t,r)}addReference(t,e,r){return this.pi.set(r,t.currentSequenceNumber),S.resolve()}removeReference(t,e,r){return this.pi.set(r,t.currentSequenceNumber),S.resolve()}updateLimboDocument(t,e){return this.pi.set(e,t.currentSequenceNumber),S.resolve()}Ti(t){let e=t.key.toString().length;return t.isFoundDocument()&&(e+=sr(t.data.value)),e}br(t,e,r){return S.or([()=>this.persistence.Ai(t,e),()=>this.persistence.getTargetCache().containsKey(t,e),()=>{const s=this.pi.get(e);return S.resolve(s!==void 0&&s>r)}])}getCacheSize(t){return this.persistence.getRemoteDocumentCache().getSize(t)}}class _i{constructor(t,e,r,s){this.targetId=t,this.fromCache=e,this.Es=r,this.ds=s}static As(t,e){let r=j(),s=j();for(const o of e.docChanges)switch(o.type){case 0:r=r.add(o.doc.key);break;case 1:s=s.add(o.doc.key)}return new _i(t,e.fromCache,r,s)}}class vm{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(t){this._documentReadCount+=t}}class Am{constructor(){this.Rs=!1,this.Vs=!1,this.fs=100,this.gs=(function(){return dh()?8:Qd(uh())>0?6:4})()}initialize(t,e){this.ps=t,this.indexManager=e,this.Rs=!0}getDocumentsMatchingQuery(t,e,r,s){const o={result:null};return this.ys(t,e).next((a=>{o.result=a})).next((()=>{if(!o.result)return this.ws(t,e,s,r).next((a=>{o.result=a}))})).next((()=>{if(o.result)return;const a=new vm;return this.Ss(t,e,a).next((u=>{if(o.result=u,this.Vs)return this.bs(t,e,a,u.size)}))})).next((()=>o.result))}bs(t,e,r,s){return r.documentReadCount<this.fs?(ke()<=$.DEBUG&&D("QueryEngine","SDK will not create cache indexes for query:",Ne(e),"since it only creates cache indexes for collection contains","more than or equal to",this.fs,"documents"),S.resolve()):(ke()<=$.DEBUG&&D("QueryEngine","Query:",Ne(e),"scans",r.documentReadCount,"local documents and returns",s,"documents as results."),r.documentReadCount>this.gs*s?(ke()<=$.DEBUG&&D("QueryEngine","The SDK decides to create cache indexes for query:",Ne(e),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(t,Nt(e))):S.resolve())}ys(t,e){if(ya(e))return S.resolve(null);let r=Nt(e);return this.indexManager.getIndexType(t,r).next((s=>s===0?null:(e.limit!==null&&s===1&&(e=Fs(e,null,"F"),r=Nt(e)),this.indexManager.getDocumentsMatchingTarget(t,r).next((o=>{const a=j(...o);return this.ps.getDocuments(t,a).next((u=>this.indexManager.getMinOffset(t,r).next((h=>{const d=this.Ds(e,u);return this.Cs(e,d,a,h.readTime)?this.ys(t,Fs(e,null,"F")):this.vs(t,d,e,h)}))))})))))}ws(t,e,r,s){return ya(e)||s.isEqual(L.min())?S.resolve(null):this.ps.getDocuments(t,r).next((o=>{const a=this.Ds(e,o);return this.Cs(e,a,r,s)?S.resolve(null):(ke()<=$.DEBUG&&D("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Ne(e)),this.vs(t,a,e,zd(s,vn)).next((u=>u)))}))}Ds(t,e){let r=new ot(jc(t));return e.forEach(((s,o)=>{Dr(t,o)&&(r=r.add(o))})),r}Cs(t,e,r,s){if(t.limit===null)return!1;if(r.size!==e.size)return!0;const o=t.limitType==="F"?e.last():e.first();return!!o&&(o.hasPendingWrites||o.version.compareTo(s)>0)}Ss(t,e,r){return ke()<=$.DEBUG&&D("QueryEngine","Using full collection scan to execute query:",Ne(e)),this.ps.getDocumentsMatchingQuery(t,e,re.min(),r)}vs(t,e,r,s){return this.ps.getDocumentsMatchingQuery(t,r,s).next((o=>(e.forEach((a=>{o=o.insert(a.key,a)})),o)))}}const yi="LocalStore",Rm=3e8;class Sm{constructor(t,e,r,s){this.persistence=t,this.Fs=e,this.serializer=s,this.Ms=new J(B),this.xs=new Ce((o=>ci(o)),ui),this.Os=new Map,this.Ns=t.getRemoteDocumentCache(),this.Pi=t.getTargetCache(),this.Ii=t.getBundleCache(),this.Bs(r)}Bs(t){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(t),this.indexManager=this.persistence.getIndexManager(t),this.mutationQueue=this.persistence.getMutationQueue(t,this.indexManager),this.localDocuments=new mm(this.Ns,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Ns.setIndexManager(this.indexManager),this.Fs.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(e=>t.collect(e,this.Ms)))}}function Cm(n,t,e,r){return new Sm(n,t,e,r)}async function du(n,t){const e=F(n);return await e.persistence.runTransaction("Handle user change","readonly",(r=>{let s;return e.mutationQueue.getAllMutationBatches(r).next((o=>(s=o,e.Bs(t),e.mutationQueue.getAllMutationBatches(r)))).next((o=>{const a=[],u=[];let h=j();for(const d of s){a.push(d.batchId);for(const m of d.mutations)h=h.add(m.key)}for(const d of o){u.push(d.batchId);for(const m of d.mutations)h=h.add(m.key)}return e.localDocuments.getDocuments(r,h).next((d=>({Ls:d,removedBatchIds:a,addedBatchIds:u})))}))}))}function bm(n,t){const e=F(n);return e.persistence.runTransaction("Acknowledge batch","readwrite-primary",(r=>{const s=t.batch.keys(),o=e.Ns.newChangeBuffer({trackRemovals:!0});return(function(u,h,d,m){const T=d.batch,v=T.keys();let b=S.resolve();return v.forEach((k=>{b=b.next((()=>m.getEntry(h,k))).next((M=>{const V=d.docVersions.get(k);K(V!==null,48541),M.version.compareTo(V)<0&&(T.applyToRemoteDocument(M,d),M.isValidDocument()&&(M.setReadTime(d.commitVersion),m.addEntry(M)))}))})),b.next((()=>u.mutationQueue.removeMutationBatch(h,T)))})(e,r,t,o).next((()=>o.apply(r))).next((()=>e.mutationQueue.performConsistencyCheck(r))).next((()=>e.documentOverlayCache.removeOverlaysForBatchId(r,s,t.batch.batchId))).next((()=>e.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(r,(function(u){let h=j();for(let d=0;d<u.mutationResults.length;++d)u.mutationResults[d].transformResults.length>0&&(h=h.add(u.batch.mutations[d].key));return h})(t)))).next((()=>e.localDocuments.getDocuments(r,s)))}))}function fu(n){const t=F(n);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Pi.getLastRemoteSnapshotVersion(e)))}function Pm(n,t){const e=F(n),r=t.snapshotVersion;let s=e.Ms;return e.persistence.runTransaction("Apply remote event","readwrite-primary",(o=>{const a=e.Ns.newChangeBuffer({trackRemovals:!0});s=e.Ms;const u=[];t.targetChanges.forEach(((m,T)=>{const v=s.get(T);if(!v)return;u.push(e.Pi.removeMatchingKeys(o,m.removedDocuments,T).next((()=>e.Pi.addMatchingKeys(o,m.addedDocuments,T))));let b=v.withSequenceNumber(o.currentSequenceNumber);t.targetMismatches.get(T)!==null?b=b.withResumeToken(dt.EMPTY_BYTE_STRING,L.min()).withLastLimboFreeSnapshotVersion(L.min()):m.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(m.resumeToken,r)),s=s.insert(T,b),(function(M,V,z){return M.resumeToken.approximateByteSize()===0||V.snapshotVersion.toMicroseconds()-M.snapshotVersion.toMicroseconds()>=Rm?!0:z.addedDocuments.size+z.modifiedDocuments.size+z.removedDocuments.size>0})(v,b,m)&&u.push(e.Pi.updateTargetData(o,b))}));let h=zt(),d=j();if(t.documentUpdates.forEach((m=>{t.resolvedLimboDocuments.has(m)&&u.push(e.persistence.referenceDelegate.updateLimboDocument(o,m))})),u.push(Vm(o,a,t.documentUpdates).next((m=>{h=m.ks,d=m.qs}))),!r.isEqual(L.min())){const m=e.Pi.getLastRemoteSnapshotVersion(o).next((T=>e.Pi.setTargetsMetadata(o,o.currentSequenceNumber,r)));u.push(m)}return S.waitFor(u).next((()=>a.apply(o))).next((()=>e.localDocuments.getLocalViewOfDocuments(o,h,d))).next((()=>h))})).then((o=>(e.Ms=s,o)))}function Vm(n,t,e){let r=j(),s=j();return e.forEach((o=>r=r.add(o))),t.getEntries(n,r).next((o=>{let a=zt();return e.forEach(((u,h)=>{const d=o.get(u);h.isFoundDocument()!==d.isFoundDocument()&&(s=s.add(u)),h.isNoDocument()&&h.version.isEqual(L.min())?(t.removeEntry(u,h.readTime),a=a.insert(u,h)):!d.isValidDocument()||h.version.compareTo(d.version)>0||h.version.compareTo(d.version)===0&&d.hasPendingWrites?(t.addEntry(h),a=a.insert(u,h)):D(yi,"Ignoring outdated watch update for ",u,". Current version:",d.version," Watch version:",h.version)})),{ks:a,qs:s}}))}function Dm(n,t){const e=F(n);return e.persistence.runTransaction("Get next mutation batch","readonly",(r=>(t===void 0&&(t=ii),e.mutationQueue.getNextMutationBatchAfterBatchId(r,t))))}function km(n,t){const e=F(n);return e.persistence.runTransaction("Allocate target","readwrite",(r=>{let s;return e.Pi.getTargetData(r,t).next((o=>o?(s=o,S.resolve(s)):e.Pi.allocateTargetId(r).next((a=>(s=new Yt(t,a,"TargetPurposeListen",r.currentSequenceNumber),e.Pi.addTargetData(r,s).next((()=>s)))))))})).then((r=>{const s=e.Ms.get(r.targetId);return(s===null||r.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(e.Ms=e.Ms.insert(r.targetId,r),e.xs.set(t,r.targetId)),r}))}async function $s(n,t,e){const r=F(n),s=r.Ms.get(t),o=e?"readwrite":"readwrite-primary";try{e||await r.persistence.runTransaction("Release target",o,(a=>r.persistence.referenceDelegate.removeTarget(a,s)))}catch(a){if(!He(a))throw a;D(yi,`Failed to update sequence numbers for target ${t}: ${a}`)}r.Ms=r.Ms.remove(t),r.xs.delete(s.target)}function Da(n,t,e){const r=F(n);let s=L.min(),o=j();return r.persistence.runTransaction("Execute query","readwrite",(a=>(function(h,d,m){const T=F(h),v=T.xs.get(m);return v!==void 0?S.resolve(T.Ms.get(v)):T.Pi.getTargetData(d,m)})(r,a,Nt(t)).next((u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,r.Pi.getMatchingKeysForTargetId(a,u.targetId).next((h=>{o=h}))})).next((()=>r.Fs.getDocumentsMatchingQuery(a,t,e?s:L.min(),e?o:j()))).next((u=>(Nm(r,yf(t),u),{documents:u,Qs:o})))))}function Nm(n,t,e){let r=n.Os.get(t)||L.min();e.forEach(((s,o)=>{o.readTime.compareTo(r)>0&&(r=o.readTime)})),n.Os.set(t,r)}class ka{constructor(){this.activeTargetIds=Af()}zs(t){this.activeTargetIds=this.activeTargetIds.add(t)}js(t){this.activeTargetIds=this.activeTargetIds.delete(t)}Gs(){const t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)}}class Mm{constructor(){this.Mo=new ka,this.xo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(t){}updateMutationState(t,e,r){}addLocalQueryTarget(t,e=!0){return e&&this.Mo.zs(t),this.xo[t]||"not-current"}updateQueryState(t,e,r){this.xo[t]=e}removeLocalQueryTarget(t){this.Mo.js(t)}isLocalQueryTarget(t){return this.Mo.activeTargetIds.has(t)}clearQueryState(t){delete this.xo[t]}getAllActiveQueryTargets(){return this.Mo.activeTargetIds}isActiveQueryTarget(t){return this.Mo.activeTargetIds.has(t)}start(){return this.Mo=new ka,Promise.resolve()}handleUserChange(t,e,r){}setOnlineState(t){}shutdown(){}writeSequenceNumber(t){}notifyBundleLoaded(t){}}class xm{Oo(t){}shutdown(){}}const Na="ConnectivityMonitor";class Ma{constructor(){this.No=()=>this.Bo(),this.Lo=()=>this.ko(),this.qo=[],this.Qo()}Oo(t){this.qo.push(t)}shutdown(){window.removeEventListener("online",this.No),window.removeEventListener("offline",this.Lo)}Qo(){window.addEventListener("online",this.No),window.addEventListener("offline",this.Lo)}Bo(){D(Na,"Network connectivity changed: AVAILABLE");for(const t of this.qo)t(0)}ko(){D(Na,"Network connectivity changed: UNAVAILABLE");for(const t of this.qo)t(1)}static v(){return typeof window<"u"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}}let nr=null;function zs(){return nr===null?nr=(function(){return 268435456+Math.round(2147483648*Math.random())})():nr++,"0x"+nr.toString(16)}const Is="RestConnection",Om={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Lm{get $o(){return!1}constructor(t){this.databaseInfo=t,this.databaseId=t.databaseId;const e=t.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.Uo=e+"://"+t.host,this.Ko=`projects/${r}/databases/${s}`,this.Wo=this.databaseId.database===dr?`project_id=${r}`:`project_id=${r}&database_id=${s}`}Go(t,e,r,s,o){const a=zs(),u=this.zo(t,e.toUriEncodedString());D(Is,`Sending RPC '${t}' ${a}:`,u,r);const h={"google-cloud-resource-prefix":this.Ko,"x-goog-request-params":this.Wo};this.jo(h,s,o);const{host:d}=new URL(u),m=Zs(d);return this.Jo(t,u,h,r,m).then((T=>(D(Is,`Received RPC '${t}' ${a}: `,T),T)),(T=>{throw Fe(Is,`RPC '${t}' ${a} failed with error: `,T,"url: ",u,"request:",r),T}))}Ho(t,e,r,s,o,a){return this.Go(t,e,r,s,o)}jo(t,e,r){t["X-Goog-Api-Client"]=(function(){return"gl-js/ fire/"+ze})(),t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach(((s,o)=>t[o]=s)),r&&r.headers.forEach(((s,o)=>t[o]=s))}zo(t,e){const r=Om[t];return`${this.Uo}/v1/${e}:${r}`}terminate(){}}class Fm{constructor(t){this.Yo=t.Yo,this.Zo=t.Zo}Xo(t){this.e_=t}t_(t){this.n_=t}r_(t){this.i_=t}onMessage(t){this.s_=t}close(){this.Zo()}send(t){this.Yo(t)}o_(){this.e_()}__(){this.n_()}a_(t){this.i_(t)}u_(t){this.s_(t)}}const mt="WebChannelConnection";class Um extends Lm{constructor(t){super(t),this.c_=[],this.forceLongPolling=t.forceLongPolling,this.autoDetectLongPolling=t.autoDetectLongPolling,this.useFetchStreams=t.useFetchStreams,this.longPollingOptions=t.longPollingOptions}Jo(t,e,r,s,o){const a=zs();return new Promise(((u,h)=>{const d=new gc;d.setWithCredentials(!0),d.listenOnce(_c.COMPLETE,(()=>{try{switch(d.getLastErrorCode()){case rr.NO_ERROR:const T=d.getResponseJson();D(mt,`XHR for RPC '${t}' ${a} received:`,JSON.stringify(T)),u(T);break;case rr.TIMEOUT:D(mt,`RPC '${t}' ${a} timed out`),h(new N(C.DEADLINE_EXCEEDED,"Request time out"));break;case rr.HTTP_ERROR:const v=d.getStatus();if(D(mt,`RPC '${t}' ${a} failed with status:`,v,"response text:",d.getResponseText()),v>0){let b=d.getResponseJson();Array.isArray(b)&&(b=b[0]);const k=b?.error;if(k&&k.status&&k.message){const M=(function(z){const G=z.toLowerCase().replace(/_/g,"-");return Object.values(C).indexOf(G)>=0?G:C.UNKNOWN})(k.status);h(new N(M,k.message))}else h(new N(C.UNKNOWN,"Server responded with status "+d.getStatus()))}else h(new N(C.UNAVAILABLE,"Connection failed."));break;default:O(9055,{l_:t,streamId:a,h_:d.getLastErrorCode(),P_:d.getLastError()})}}finally{D(mt,`RPC '${t}' ${a} completed.`)}}));const m=JSON.stringify(s);D(mt,`RPC '${t}' ${a} sending request:`,s),d.send(e,"POST",m,r,15)}))}T_(t,e,r){const s=zs(),o=[this.Uo,"/","google.firestore.v1.Firestore","/",t,"/channel"],a=Tc(),u=Ec(),h={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},d=this.longPollingOptions.timeoutSeconds;d!==void 0&&(h.longPollingTimeout=Math.round(1e3*d)),this.useFetchStreams&&(h.useFetchStreams=!0),this.jo(h.initMessageHeaders,e,r),h.encodeInitMessageHeaders=!0;const m=o.join("");D(mt,`Creating RPC '${t}' stream ${s}: ${m}`,h);const T=a.createWebChannel(m,h);this.I_(T);let v=!1,b=!1;const k=new Fm({Yo:V=>{b?D(mt,`Not sending because RPC '${t}' stream ${s} is closed:`,V):(v||(D(mt,`Opening RPC '${t}' stream ${s} transport.`),T.open(),v=!0),D(mt,`RPC '${t}' stream ${s} sending:`,V),T.send(V))},Zo:()=>T.close()}),M=(V,z,G)=>{V.listen(z,(H=>{try{G(H)}catch(_t){setTimeout((()=>{throw _t}),0)}}))};return M(T,hn.EventType.OPEN,(()=>{b||(D(mt,`RPC '${t}' stream ${s} transport opened.`),k.o_())})),M(T,hn.EventType.CLOSE,(()=>{b||(b=!0,D(mt,`RPC '${t}' stream ${s} transport closed`),k.a_(),this.E_(T))})),M(T,hn.EventType.ERROR,(V=>{b||(b=!0,Fe(mt,`RPC '${t}' stream ${s} transport errored. Name:`,V.name,"Message:",V.message),k.a_(new N(C.UNAVAILABLE,"The operation could not be completed")))})),M(T,hn.EventType.MESSAGE,(V=>{if(!b){const z=V.data[0];K(!!z,16349);const G=z,H=G?.error||G[0]?.error;if(H){D(mt,`RPC '${t}' stream ${s} received error:`,H);const _t=H.status;let It=(function(p){const _=et[p];if(_!==void 0)return tu(_)})(_t),at=H.message;It===void 0&&(It=C.INTERNAL,at="Unknown error status: "+_t+" with message "+H.message),b=!0,k.a_(new N(It,at)),T.close()}else D(mt,`RPC '${t}' stream ${s} received:`,z),k.u_(z)}})),M(u,yc.STAT_EVENT,(V=>{V.stat===ks.PROXY?D(mt,`RPC '${t}' stream ${s} detected buffering proxy`):V.stat===ks.NOPROXY&&D(mt,`RPC '${t}' stream ${s} detected no buffering proxy`)})),setTimeout((()=>{k.__()}),0),k}terminate(){this.c_.forEach((t=>t.close())),this.c_=[]}I_(t){this.c_.push(t)}E_(t){this.c_=this.c_.filter((e=>e===t))}}function ws(){return typeof document<"u"?document:null}function xr(n){return new $f(n,!0)}class mu{constructor(t,e,r=1e3,s=1.5,o=6e4){this.Mi=t,this.timerId=e,this.d_=r,this.A_=s,this.R_=o,this.V_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.V_=0}g_(){this.V_=this.R_}p_(t){this.cancel();const e=Math.floor(this.V_+this.y_()),r=Math.max(0,Date.now()-this.f_),s=Math.max(0,e-r);s>0&&D("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.V_} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`),this.m_=this.Mi.enqueueAfterDelay(this.timerId,s,(()=>(this.f_=Date.now(),t()))),this.V_*=this.A_,this.V_<this.d_&&(this.V_=this.d_),this.V_>this.R_&&(this.V_=this.R_)}w_(){this.m_!==null&&(this.m_.skipDelay(),this.m_=null)}cancel(){this.m_!==null&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.V_}}const xa="PersistentStream";class pu{constructor(t,e,r,s,o,a,u,h){this.Mi=t,this.S_=r,this.b_=s,this.connection=o,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=u,this.listener=h,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new mu(t,e)}x_(){return this.state===1||this.state===5||this.O_()}O_(){return this.state===2||this.state===3}start(){this.F_=0,this.state!==4?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&this.C_===null&&(this.C_=this.Mi.enqueueAfterDelay(this.S_,6e4,(()=>this.k_())))}q_(t){this.Q_(),this.stream.send(t)}async k_(){if(this.O_())return this.close(0)}Q_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(t,e){this.Q_(),this.U_(),this.M_.cancel(),this.D_++,t!==4?this.M_.reset():e&&e.code===C.RESOURCE_EXHAUSTED?($t(e.toString()),$t("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):e&&e.code===C.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.K_(),this.stream.close(),this.stream=null),this.state=t,await this.listener.r_(e)}K_(){}auth(){this.state=1;const t=this.W_(this.D_),e=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([r,s])=>{this.D_===e&&this.G_(r,s)}),(r=>{t((()=>{const s=new N(C.UNKNOWN,"Fetching auth token failed: "+r.message);return this.z_(s)}))}))}G_(t,e){const r=this.W_(this.D_);this.stream=this.j_(t,e),this.stream.Xo((()=>{r((()=>this.listener.Xo()))})),this.stream.t_((()=>{r((()=>(this.state=2,this.v_=this.Mi.enqueueAfterDelay(this.b_,1e4,(()=>(this.O_()&&(this.state=3),Promise.resolve()))),this.listener.t_())))})),this.stream.r_((s=>{r((()=>this.z_(s)))})),this.stream.onMessage((s=>{r((()=>++this.F_==1?this.J_(s):this.onNext(s)))}))}N_(){this.state=5,this.M_.p_((async()=>{this.state=0,this.start()}))}z_(t){return D(xa,`close with error: ${t}`),this.stream=null,this.close(4,t)}W_(t){return e=>{this.Mi.enqueueAndForget((()=>this.D_===t?e():(D(xa,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class Bm extends pu{constructor(t,e,r,s,o,a){super(t,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",e,r,s,a),this.serializer=o}j_(t,e){return this.connection.T_("Listen",t,e)}J_(t){return this.onNext(t)}onNext(t){this.M_.reset();const e=Hf(this.serializer,t),r=(function(o){if(!("targetChange"in o))return L.min();const a=o.targetChange;return a.targetIds&&a.targetIds.length?L.min():a.readTime?xt(a.readTime):L.min()})(t);return this.listener.H_(e,r)}Y_(t){const e={};e.database=qs(this.serializer),e.addTarget=(function(o,a){let u;const h=a.target;if(u=Ls(h)?{documents:Qf(o,h)}:{query:Xf(o,h).ft},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=ru(o,a.resumeToken);const d=Us(o,a.expectedCount);d!==null&&(u.expectedCount=d)}else if(a.snapshotVersion.compareTo(L.min())>0){u.readTime=_r(o,a.snapshotVersion.toTimestamp());const d=Us(o,a.expectedCount);d!==null&&(u.expectedCount=d)}return u})(this.serializer,t);const r=Jf(this.serializer,t);r&&(e.labels=r),this.q_(e)}Z_(t){const e={};e.database=qs(this.serializer),e.removeTarget=t,this.q_(e)}}class jm extends pu{constructor(t,e,r,s,o,a){super(t,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",e,r,s,a),this.serializer=o}get X_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}K_(){this.X_&&this.ea([])}j_(t,e){return this.connection.T_("Write",t,e)}J_(t){return K(!!t.streamToken,31322),this.lastStreamToken=t.streamToken,K(!t.writeResults||t.writeResults.length===0,55816),this.listener.ta()}onNext(t){K(!!t.streamToken,12678),this.lastStreamToken=t.streamToken,this.M_.reset();const e=Wf(t.writeResults,t.commitTime),r=xt(t.commitTime);return this.listener.na(r,e)}ra(){const t={};t.database=qs(this.serializer),this.q_(t)}ea(t){const e={streamToken:this.lastStreamToken,writes:t.map((r=>Kf(this.serializer,r)))};this.q_(e)}}class qm{}class $m extends qm{constructor(t,e,r,s){super(),this.authCredentials=t,this.appCheckCredentials=e,this.connection=r,this.serializer=s,this.ia=!1}sa(){if(this.ia)throw new N(C.FAILED_PRECONDITION,"The client has already been terminated.")}Go(t,e,r,s){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([o,a])=>this.connection.Go(t,Bs(e,r),s,o,a))).catch((o=>{throw o.name==="FirebaseError"?(o.code===C.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),o):new N(C.UNKNOWN,o.toString())}))}Ho(t,e,r,s,o){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([a,u])=>this.connection.Ho(t,Bs(e,r),s,a,u,o))).catch((a=>{throw a.name==="FirebaseError"?(a.code===C.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new N(C.UNKNOWN,a.toString())}))}terminate(){this.ia=!0,this.connection.terminate()}}class zm{constructor(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){this.oa===0&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve()))))}ha(t){this.state==="Online"?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${t.toString()}`),this.ca("Offline")))}set(t){this.Pa(),this.oa=0,t==="Online"&&(this.aa=!1),this.ca(t)}ca(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))}la(t){const e=`Could not reach Cloud Firestore backend. ${t}
32
+ This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.aa?($t(e),this.aa=!1):D("OnlineStateTracker",e)}Pa(){this._a!==null&&(this._a.cancel(),this._a=null)}}const Ae="RemoteStore";class Gm{constructor(t,e,r,s,o){this.localStore=t,this.datastore=e,this.asyncQueue=r,this.remoteSyncer={},this.Ta=[],this.Ia=new Map,this.Ea=new Set,this.da=[],this.Aa=o,this.Aa.Oo((a=>{r.enqueueAndForget((async()=>{be(this)&&(D(Ae,"Restarting streams for network reachability change."),await(async function(h){const d=F(h);d.Ea.add(4),await xn(d),d.Ra.set("Unknown"),d.Ea.delete(4),await Or(d)})(this))}))})),this.Ra=new zm(r,s)}}async function Or(n){if(be(n))for(const t of n.da)await t(!0)}async function xn(n){for(const t of n.da)await t(!1)}function gu(n,t){const e=F(n);e.Ia.has(t.targetId)||(e.Ia.set(t.targetId,t),wi(e)?Ii(e):Ke(e).O_()&&Ti(e,t))}function Ei(n,t){const e=F(n),r=Ke(e);e.Ia.delete(t),r.O_()&&_u(e,t),e.Ia.size===0&&(r.O_()?r.L_():be(e)&&e.Ra.set("Unknown"))}function Ti(n,t){if(n.Va.Ue(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(L.min())>0){const e=n.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(e)}Ke(n).Y_(t)}function _u(n,t){n.Va.Ue(t),Ke(n).Z_(t)}function Ii(n){n.Va=new Uf({getRemoteKeysForTarget:t=>n.remoteSyncer.getRemoteKeysForTarget(t),At:t=>n.Ia.get(t)||null,ht:()=>n.datastore.serializer.databaseId}),Ke(n).start(),n.Ra.ua()}function wi(n){return be(n)&&!Ke(n).x_()&&n.Ia.size>0}function be(n){return F(n).Ea.size===0}function yu(n){n.Va=void 0}async function Hm(n){n.Ra.set("Online")}async function Km(n){n.Ia.forEach(((t,e)=>{Ti(n,t)}))}async function Wm(n,t){yu(n),wi(n)?(n.Ra.ha(t),Ii(n)):n.Ra.set("Unknown")}async function Qm(n,t,e){if(n.Ra.set("Online"),t instanceof nu&&t.state===2&&t.cause)try{await(async function(s,o){const a=o.cause;for(const u of o.targetIds)s.Ia.has(u)&&(await s.remoteSyncer.rejectListen(u,a),s.Ia.delete(u),s.Va.removeTarget(u))})(n,t)}catch(r){D(Ae,"Failed to remove targets %s: %s ",t.targetIds.join(","),r),await Er(n,r)}else if(t instanceof ar?n.Va.Ze(t):t instanceof eu?n.Va.st(t):n.Va.tt(t),!e.isEqual(L.min()))try{const r=await fu(n.localStore);e.compareTo(r)>=0&&await(function(o,a){const u=o.Va.Tt(a);return u.targetChanges.forEach(((h,d)=>{if(h.resumeToken.approximateByteSize()>0){const m=o.Ia.get(d);m&&o.Ia.set(d,m.withResumeToken(h.resumeToken,a))}})),u.targetMismatches.forEach(((h,d)=>{const m=o.Ia.get(h);if(!m)return;o.Ia.set(h,m.withResumeToken(dt.EMPTY_BYTE_STRING,m.snapshotVersion)),_u(o,h);const T=new Yt(m.target,h,d,m.sequenceNumber);Ti(o,T)})),o.remoteSyncer.applyRemoteEvent(u)})(n,e)}catch(r){D(Ae,"Failed to raise snapshot:",r),await Er(n,r)}}async function Er(n,t,e){if(!He(t))throw t;n.Ea.add(1),await xn(n),n.Ra.set("Offline"),e||(e=()=>fu(n.localStore)),n.asyncQueue.enqueueRetryable((async()=>{D(Ae,"Retrying IndexedDB access"),await e(),n.Ea.delete(1),await Or(n)}))}function Eu(n,t){return t().catch((e=>Er(n,e,t)))}async function Lr(n){const t=F(n),e=ae(t);let r=t.Ta.length>0?t.Ta[t.Ta.length-1].batchId:ii;for(;Xm(t);)try{const s=await Dm(t.localStore,r);if(s===null){t.Ta.length===0&&e.L_();break}r=s.batchId,Ym(t,s)}catch(s){await Er(t,s)}Tu(t)&&Iu(t)}function Xm(n){return be(n)&&n.Ta.length<10}function Ym(n,t){n.Ta.push(t);const e=ae(n);e.O_()&&e.X_&&e.ea(t.mutations)}function Tu(n){return be(n)&&!ae(n).x_()&&n.Ta.length>0}function Iu(n){ae(n).start()}async function Jm(n){ae(n).ra()}async function Zm(n){const t=ae(n);for(const e of n.Ta)t.ea(e.mutations)}async function tp(n,t,e){const r=n.Ta.shift(),s=di.from(r,t,e);await Eu(n,(()=>n.remoteSyncer.applySuccessfulWrite(s))),await Lr(n)}async function ep(n,t){t&&ae(n).X_&&await(async function(r,s){if((function(a){return Of(a)&&a!==C.ABORTED})(s.code)){const o=r.Ta.shift();ae(r).B_(),await Eu(r,(()=>r.remoteSyncer.rejectFailedWrite(o.batchId,s))),await Lr(r)}})(n,t),Tu(n)&&Iu(n)}async function Oa(n,t){const e=F(n);e.asyncQueue.verifyOperationInProgress(),D(Ae,"RemoteStore received new credentials");const r=be(e);e.Ea.add(3),await xn(e),r&&e.Ra.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ea.delete(3),await Or(e)}async function np(n,t){const e=F(n);t?(e.Ea.delete(2),await Or(e)):t||(e.Ea.add(2),await xn(e),e.Ra.set("Unknown"))}function Ke(n){return n.ma||(n.ma=(function(e,r,s){const o=F(e);return o.sa(),new Bm(r,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)})(n.datastore,n.asyncQueue,{Xo:Hm.bind(null,n),t_:Km.bind(null,n),r_:Wm.bind(null,n),H_:Qm.bind(null,n)}),n.da.push((async t=>{t?(n.ma.B_(),wi(n)?Ii(n):n.Ra.set("Unknown")):(await n.ma.stop(),yu(n))}))),n.ma}function ae(n){return n.fa||(n.fa=(function(e,r,s){const o=F(e);return o.sa(),new jm(r,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)})(n.datastore,n.asyncQueue,{Xo:()=>Promise.resolve(),t_:Jm.bind(null,n),r_:ep.bind(null,n),ta:Zm.bind(null,n),na:tp.bind(null,n)}),n.da.push((async t=>{t?(n.fa.B_(),await Lr(n)):(await n.fa.stop(),n.Ta.length>0&&(D(Ae,`Stopping write stream with ${n.Ta.length} pending writes`),n.Ta=[]))}))),n.fa}class vi{constructor(t,e,r,s,o){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=r,this.op=s,this.removalCallback=o,this.deferred=new ee,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((a=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(t,e,r,s,o){const a=Date.now()+r,u=new vi(t,e,a,s,o);return u.start(r),u}start(t){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),t)}skipDelay(){return this.handleDelayElapsed()}cancel(t){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new N(C.CANCELLED,"Operation cancelled"+(t?": "+t:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then((t=>this.deferred.resolve(t)))):Promise.resolve()))}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Ai(n,t){if($t("AsyncQueue",`${t}: ${n}`),He(n))return new N(C.UNAVAILABLE,`${t}: ${n}`);throw n}class Oe{static emptySet(t){return new Oe(t.comparator)}constructor(t){this.comparator=t?(e,r)=>t(e,r)||x.comparator(e.key,r.key):(e,r)=>x.comparator(e.key,r.key),this.keyedMap=dn(),this.sortedSet=new J(this.comparator)}has(t){return this.keyedMap.get(t)!=null}get(t){return this.keyedMap.get(t)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(t){const e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1}get size(){return this.sortedSet.size}forEach(t){this.sortedSet.inorderTraversal(((e,r)=>(t(e),!1)))}add(t){const e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))}delete(t){const e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this}isEqual(t){if(!(t instanceof Oe)||this.size!==t.size)return!1;const e=this.sortedSet.getIterator(),r=t.sortedSet.getIterator();for(;e.hasNext();){const s=e.getNext().key,o=r.getNext().key;if(!s.isEqual(o))return!1}return!0}toString(){const t=[];return this.forEach((e=>{t.push(e.toString())})),t.length===0?"DocumentSet ()":`DocumentSet (
33
+ `+t.join(`
34
+ `)+`
35
+ )`}copy(t,e){const r=new Oe;return r.comparator=this.comparator,r.keyedMap=t,r.sortedSet=e,r}}class La{constructor(){this.ga=new J(x.comparator)}track(t){const e=t.doc.key,r=this.ga.get(e);r?t.type!==0&&r.type===3?this.ga=this.ga.insert(e,t):t.type===3&&r.type!==1?this.ga=this.ga.insert(e,{type:r.type,doc:t.doc}):t.type===2&&r.type===2?this.ga=this.ga.insert(e,{type:2,doc:t.doc}):t.type===2&&r.type===0?this.ga=this.ga.insert(e,{type:0,doc:t.doc}):t.type===1&&r.type===0?this.ga=this.ga.remove(e):t.type===1&&r.type===2?this.ga=this.ga.insert(e,{type:1,doc:r.doc}):t.type===0&&r.type===1?this.ga=this.ga.insert(e,{type:2,doc:t.doc}):O(63341,{Rt:t,pa:r}):this.ga=this.ga.insert(e,t)}ya(){const t=[];return this.ga.inorderTraversal(((e,r)=>{t.push(r)})),t}}class $e{constructor(t,e,r,s,o,a,u,h,d){this.query=t,this.docs=e,this.oldDocs=r,this.docChanges=s,this.mutatedKeys=o,this.fromCache=a,this.syncStateChanged=u,this.excludesMetadataChanges=h,this.hasCachedResults=d}static fromInitialDocuments(t,e,r,s,o){const a=[];return e.forEach((u=>{a.push({type:0,doc:u})})),new $e(t,e,Oe.emptySet(e),a,r,s,!0,!1,o)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.hasCachedResults===t.hasCachedResults&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&Vr(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;const e=this.docChanges,r=t.docChanges;if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s].type!==r[s].type||!e[s].doc.isEqual(r[s].doc))return!1;return!0}}class rp{constructor(){this.wa=void 0,this.Sa=[]}ba(){return this.Sa.some((t=>t.Da()))}}class sp{constructor(){this.queries=Fa(),this.onlineState="Unknown",this.Ca=new Set}terminate(){(function(e,r){const s=F(e),o=s.queries;s.queries=Fa(),o.forEach(((a,u)=>{for(const h of u.Sa)h.onError(r)}))})(this,new N(C.ABORTED,"Firestore shutting down"))}}function Fa(){return new Ce((n=>Bc(n)),Vr)}async function ip(n,t){const e=F(n);let r=3;const s=t.query;let o=e.queries.get(s);o?!o.ba()&&t.Da()&&(r=2):(o=new rp,r=t.Da()?0:1);try{switch(r){case 0:o.wa=await e.onListen(s,!0);break;case 1:o.wa=await e.onListen(s,!1);break;case 2:await e.onFirstRemoteStoreListen(s)}}catch(a){const u=Ai(a,`Initialization of query '${Ne(t.query)}' failed`);return void t.onError(u)}e.queries.set(s,o),o.Sa.push(t),t.va(e.onlineState),o.wa&&t.Fa(o.wa)&&Ri(e)}async function op(n,t){const e=F(n),r=t.query;let s=3;const o=e.queries.get(r);if(o){const a=o.Sa.indexOf(t);a>=0&&(o.Sa.splice(a,1),o.Sa.length===0?s=t.Da()?0:1:!o.ba()&&t.Da()&&(s=2))}switch(s){case 0:return e.queries.delete(r),e.onUnlisten(r,!0);case 1:return e.queries.delete(r),e.onUnlisten(r,!1);case 2:return e.onLastRemoteStoreUnlisten(r);default:return}}function ap(n,t){const e=F(n);let r=!1;for(const s of t){const o=s.query,a=e.queries.get(o);if(a){for(const u of a.Sa)u.Fa(s)&&(r=!0);a.wa=s}}r&&Ri(e)}function cp(n,t,e){const r=F(n),s=r.queries.get(t);if(s)for(const o of s.Sa)o.onError(e);r.queries.delete(t)}function Ri(n){n.Ca.forEach((t=>{t.next()}))}var Gs,Ua;(Ua=Gs||(Gs={})).Ma="default",Ua.Cache="cache";class up{constructor(t,e,r){this.query=t,this.xa=e,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=r||{}}Fa(t){if(!this.options.includeMetadataChanges){const r=[];for(const s of t.docChanges)s.type!==3&&r.push(s);t=new $e(t.query,t.docs,t.oldDocs,r,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0,t.hasCachedResults)}let e=!1;return this.Oa?this.Ba(t)&&(this.xa.next(t),e=!0):this.La(t,this.onlineState)&&(this.ka(t),e=!0),this.Na=t,e}onError(t){this.xa.error(t)}va(t){this.onlineState=t;let e=!1;return this.Na&&!this.Oa&&this.La(this.Na,t)&&(this.ka(this.Na),e=!0),e}La(t,e){if(!t.fromCache||!this.Da())return!0;const r=e!=="Offline";return(!this.options.qa||!r)&&(!t.docs.isEmpty()||t.hasCachedResults||e==="Offline")}Ba(t){if(t.docChanges.length>0)return!0;const e=this.Na&&this.Na.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&this.options.includeMetadataChanges===!0}ka(t){t=$e.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache,t.hasCachedResults),this.Oa=!0,this.xa.next(t)}Da(){return this.options.source!==Gs.Cache}}class wu{constructor(t){this.key=t}}class vu{constructor(t){this.key=t}}class lp{constructor(t,e){this.query=t,this.Ya=e,this.Za=null,this.hasCachedResults=!1,this.current=!1,this.Xa=j(),this.mutatedKeys=j(),this.eu=jc(t),this.tu=new Oe(this.eu)}get nu(){return this.Ya}ru(t,e){const r=e?e.iu:new La,s=e?e.tu:this.tu;let o=e?e.mutatedKeys:this.mutatedKeys,a=s,u=!1;const h=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,d=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(t.inorderTraversal(((m,T)=>{const v=s.get(m),b=Dr(this.query,T)?T:null,k=!!v&&this.mutatedKeys.has(v.key),M=!!b&&(b.hasLocalMutations||this.mutatedKeys.has(b.key)&&b.hasCommittedMutations);let V=!1;v&&b?v.data.isEqual(b.data)?k!==M&&(r.track({type:3,doc:b}),V=!0):this.su(v,b)||(r.track({type:2,doc:b}),V=!0,(h&&this.eu(b,h)>0||d&&this.eu(b,d)<0)&&(u=!0)):!v&&b?(r.track({type:0,doc:b}),V=!0):v&&!b&&(r.track({type:1,doc:v}),V=!0,(h||d)&&(u=!0)),V&&(b?(a=a.add(b),o=M?o.add(m):o.delete(m)):(a=a.delete(m),o=o.delete(m)))})),this.query.limit!==null)for(;a.size>this.query.limit;){const m=this.query.limitType==="F"?a.last():a.first();a=a.delete(m.key),o=o.delete(m.key),r.track({type:1,doc:m})}return{tu:a,iu:r,Cs:u,mutatedKeys:o}}su(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations}applyChanges(t,e,r,s){const o=this.tu;this.tu=t.tu,this.mutatedKeys=t.mutatedKeys;const a=t.iu.ya();a.sort(((m,T)=>(function(b,k){const M=V=>{switch(V){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return O(20277,{Rt:V})}};return M(b)-M(k)})(m.type,T.type)||this.eu(m.doc,T.doc))),this.ou(r),s=s??!1;const u=e&&!s?this._u():[],h=this.Xa.size===0&&this.current&&!s?1:0,d=h!==this.Za;return this.Za=h,a.length!==0||d?{snapshot:new $e(this.query,t.tu,o,a,t.mutatedKeys,h===0,d,!1,!!r&&r.resumeToken.approximateByteSize()>0),au:u}:{au:u}}va(t){return this.current&&t==="Offline"?(this.current=!1,this.applyChanges({tu:this.tu,iu:new La,mutatedKeys:this.mutatedKeys,Cs:!1},!1)):{au:[]}}uu(t){return!this.Ya.has(t)&&!!this.tu.has(t)&&!this.tu.get(t).hasLocalMutations}ou(t){t&&(t.addedDocuments.forEach((e=>this.Ya=this.Ya.add(e))),t.modifiedDocuments.forEach((e=>{})),t.removedDocuments.forEach((e=>this.Ya=this.Ya.delete(e))),this.current=t.current)}_u(){if(!this.current)return[];const t=this.Xa;this.Xa=j(),this.tu.forEach((r=>{this.uu(r.key)&&(this.Xa=this.Xa.add(r.key))}));const e=[];return t.forEach((r=>{this.Xa.has(r)||e.push(new vu(r))})),this.Xa.forEach((r=>{t.has(r)||e.push(new wu(r))})),e}cu(t){this.Ya=t.Qs,this.Xa=j();const e=this.ru(t.documents);return this.applyChanges(e,!0)}lu(){return $e.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,this.Za===0,this.hasCachedResults)}}const Si="SyncEngine";class hp{constructor(t,e,r){this.query=t,this.targetId=e,this.view=r}}class dp{constructor(t){this.key=t,this.hu=!1}}class fp{constructor(t,e,r,s,o,a){this.localStore=t,this.remoteStore=e,this.eventManager=r,this.sharedClientState=s,this.currentUser=o,this.maxConcurrentLimboResolutions=a,this.Pu={},this.Tu=new Ce((u=>Bc(u)),Vr),this.Iu=new Map,this.Eu=new Set,this.du=new J(x.comparator),this.Au=new Map,this.Ru=new pi,this.Vu={},this.mu=new Map,this.fu=qe.cr(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return this.gu===!0}}async function mp(n,t,e=!0){const r=Pu(n);let s;const o=r.Tu.get(t);return o?(r.sharedClientState.addLocalQueryTarget(o.targetId),s=o.view.lu()):s=await Au(r,t,e,!0),s}async function pp(n,t){const e=Pu(n);await Au(e,t,!0,!1)}async function Au(n,t,e,r){const s=await km(n.localStore,Nt(t)),o=s.targetId,a=n.sharedClientState.addLocalQueryTarget(o,e);let u;return r&&(u=await gp(n,t,o,a==="current",s.resumeToken)),n.isPrimaryClient&&e&&gu(n.remoteStore,s),u}async function gp(n,t,e,r,s){n.pu=(T,v,b)=>(async function(M,V,z,G){let H=V.view.ru(z);H.Cs&&(H=await Da(M.localStore,V.query,!1).then((({documents:E})=>V.view.ru(E,H))));const _t=G&&G.targetChanges.get(V.targetId),It=G&&G.targetMismatches.get(V.targetId)!=null,at=V.view.applyChanges(H,M.isPrimaryClient,_t,It);return ja(M,V.targetId,at.au),at.snapshot})(n,T,v,b);const o=await Da(n.localStore,t,!0),a=new lp(t,o.Qs),u=a.ru(o.documents),h=Mn.createSynthesizedTargetChangeForCurrentChange(e,r&&n.onlineState!=="Offline",s),d=a.applyChanges(u,n.isPrimaryClient,h);ja(n,e,d.au);const m=new hp(t,e,a);return n.Tu.set(t,m),n.Iu.has(e)?n.Iu.get(e).push(t):n.Iu.set(e,[t]),d.snapshot}async function _p(n,t,e){const r=F(n),s=r.Tu.get(t),o=r.Iu.get(s.targetId);if(o.length>1)return r.Iu.set(s.targetId,o.filter((a=>!Vr(a,t)))),void r.Tu.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(s.targetId),r.sharedClientState.isActiveQueryTarget(s.targetId)||await $s(r.localStore,s.targetId,!1).then((()=>{r.sharedClientState.clearQueryState(s.targetId),e&&Ei(r.remoteStore,s.targetId),Hs(r,s.targetId)})).catch(Ge)):(Hs(r,s.targetId),await $s(r.localStore,s.targetId,!0))}async function yp(n,t){const e=F(n),r=e.Tu.get(t),s=e.Iu.get(r.targetId);e.isPrimaryClient&&s.length===1&&(e.sharedClientState.removeLocalQueryTarget(r.targetId),Ei(e.remoteStore,r.targetId))}async function Ep(n,t,e){const r=Sp(n);try{const s=await(function(a,u){const h=F(a),d=X.now(),m=u.reduce(((b,k)=>b.add(k.key)),j());let T,v;return h.persistence.runTransaction("Locally write mutations","readwrite",(b=>{let k=zt(),M=j();return h.Ns.getEntries(b,m).next((V=>{k=V,k.forEach(((z,G)=>{G.isValidDocument()||(M=M.add(z))}))})).next((()=>h.localDocuments.getOverlayedDocuments(b,k))).next((V=>{T=V;const z=[];for(const G of u){const H=Df(G,T.get(G.key).overlayedDocument);H!=null&&z.push(new he(G.key,H,Nc(H.value.mapValue),Mt.exists(!0)))}return h.mutationQueue.addMutationBatch(b,d,z,u)})).next((V=>{v=V;const z=V.applyToLocalDocumentSet(T,M);return h.documentOverlayCache.saveOverlays(b,V.batchId,z)}))})).then((()=>({batchId:v.batchId,changes:$c(T)})))})(r.localStore,t);r.sharedClientState.addPendingMutation(s.batchId),(function(a,u,h){let d=a.Vu[a.currentUser.toKey()];d||(d=new J(B)),d=d.insert(u,h),a.Vu[a.currentUser.toKey()]=d})(r,s.batchId,e),await On(r,s.changes),await Lr(r.remoteStore)}catch(s){const o=Ai(s,"Failed to persist write");e.reject(o)}}async function Ru(n,t){const e=F(n);try{const r=await Pm(e.localStore,t);t.targetChanges.forEach(((s,o)=>{const a=e.Au.get(o);a&&(K(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?a.hu=!0:s.modifiedDocuments.size>0?K(a.hu,14607):s.removedDocuments.size>0&&(K(a.hu,42227),a.hu=!1))})),await On(e,r,t)}catch(r){await Ge(r)}}function Ba(n,t,e){const r=F(n);if(r.isPrimaryClient&&e===0||!r.isPrimaryClient&&e===1){const s=[];r.Tu.forEach(((o,a)=>{const u=a.view.va(t);u.snapshot&&s.push(u.snapshot)})),(function(a,u){const h=F(a);h.onlineState=u;let d=!1;h.queries.forEach(((m,T)=>{for(const v of T.Sa)v.va(u)&&(d=!0)})),d&&Ri(h)})(r.eventManager,t),s.length&&r.Pu.H_(s),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Tp(n,t,e){const r=F(n);r.sharedClientState.updateQueryState(t,"rejected",e);const s=r.Au.get(t),o=s&&s.key;if(o){let a=new J(x.comparator);a=a.insert(o,gt.newNoDocument(o,L.min()));const u=j().add(o),h=new Mr(L.min(),new Map,new J(B),a,u);await Ru(r,h),r.du=r.du.remove(o),r.Au.delete(t),Ci(r)}else await $s(r.localStore,t,!1).then((()=>Hs(r,t,e))).catch(Ge)}async function Ip(n,t){const e=F(n),r=t.batch.batchId;try{const s=await bm(e.localStore,t);Cu(e,r,null),Su(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await On(e,s)}catch(s){await Ge(s)}}async function wp(n,t,e){const r=F(n);try{const s=await(function(a,u){const h=F(a);return h.persistence.runTransaction("Reject batch","readwrite-primary",(d=>{let m;return h.mutationQueue.lookupMutationBatch(d,u).next((T=>(K(T!==null,37113),m=T.keys(),h.mutationQueue.removeMutationBatch(d,T)))).next((()=>h.mutationQueue.performConsistencyCheck(d))).next((()=>h.documentOverlayCache.removeOverlaysForBatchId(d,m,u))).next((()=>h.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(d,m))).next((()=>h.localDocuments.getDocuments(d,m)))}))})(r.localStore,t);Cu(r,t,e),Su(r,t),r.sharedClientState.updateMutationState(t,"rejected",e),await On(r,s)}catch(s){await Ge(s)}}function Su(n,t){(n.mu.get(t)||[]).forEach((e=>{e.resolve()})),n.mu.delete(t)}function Cu(n,t,e){const r=F(n);let s=r.Vu[r.currentUser.toKey()];if(s){const o=s.get(t);o&&(e?o.reject(e):o.resolve(),s=s.remove(t)),r.Vu[r.currentUser.toKey()]=s}}function Hs(n,t,e=null){n.sharedClientState.removeLocalQueryTarget(t);for(const r of n.Iu.get(t))n.Tu.delete(r),e&&n.Pu.yu(r,e);n.Iu.delete(t),n.isPrimaryClient&&n.Ru.jr(t).forEach((r=>{n.Ru.containsKey(r)||bu(n,r)}))}function bu(n,t){n.Eu.delete(t.path.canonicalString());const e=n.du.get(t);e!==null&&(Ei(n.remoteStore,e),n.du=n.du.remove(t),n.Au.delete(e),Ci(n))}function ja(n,t,e){for(const r of e)r instanceof wu?(n.Ru.addReference(r.key,t),vp(n,r)):r instanceof vu?(D(Si,"Document no longer in limbo: "+r.key),n.Ru.removeReference(r.key,t),n.Ru.containsKey(r.key)||bu(n,r.key)):O(19791,{wu:r})}function vp(n,t){const e=t.key,r=e.path.canonicalString();n.du.get(e)||n.Eu.has(r)||(D(Si,"New document in limbo: "+e),n.Eu.add(r),Ci(n))}function Ci(n){for(;n.Eu.size>0&&n.du.size<n.maxConcurrentLimboResolutions;){const t=n.Eu.values().next().value;n.Eu.delete(t);const e=new x(Y.fromString(t)),r=n.fu.next();n.Au.set(r,new dp(e)),n.du=n.du.insert(e,r),gu(n.remoteStore,new Yt(Nt(li(e.path)),r,"TargetPurposeLimboResolution",Sr.ce))}}async function On(n,t,e){const r=F(n),s=[],o=[],a=[];r.Tu.isEmpty()||(r.Tu.forEach(((u,h)=>{a.push(r.pu(h,t,e).then((d=>{if((d||e)&&r.isPrimaryClient){const m=d?!d.fromCache:e?.targetChanges.get(h.targetId)?.current;r.sharedClientState.updateQueryState(h.targetId,m?"current":"not-current")}if(d){s.push(d);const m=_i.As(h.targetId,d);o.push(m)}})))})),await Promise.all(a),r.Pu.H_(s),await(async function(h,d){const m=F(h);try{await m.persistence.runTransaction("notifyLocalViewChanges","readwrite",(T=>S.forEach(d,(v=>S.forEach(v.Es,(b=>m.persistence.referenceDelegate.addReference(T,v.targetId,b))).next((()=>S.forEach(v.ds,(b=>m.persistence.referenceDelegate.removeReference(T,v.targetId,b)))))))))}catch(T){if(!He(T))throw T;D(yi,"Failed to update sequence numbers: "+T)}for(const T of d){const v=T.targetId;if(!T.fromCache){const b=m.Ms.get(v),k=b.snapshotVersion,M=b.withLastLimboFreeSnapshotVersion(k);m.Ms=m.Ms.insert(v,M)}}})(r.localStore,o))}async function Ap(n,t){const e=F(n);if(!e.currentUser.isEqual(t)){D(Si,"User change. New user:",t.toKey());const r=await du(e.localStore,t);e.currentUser=t,(function(o,a){o.mu.forEach((u=>{u.forEach((h=>{h.reject(new N(C.CANCELLED,a))}))})),o.mu.clear()})(e,"'waitForPendingWrites' promise is rejected due to a user change."),e.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await On(e,r.Ls)}}function Rp(n,t){const e=F(n),r=e.Au.get(t);if(r&&r.hu)return j().add(r.key);{let s=j();const o=e.Iu.get(t);if(!o)return s;for(const a of o){const u=e.Tu.get(a);s=s.unionWith(u.view.nu)}return s}}function Pu(n){const t=F(n);return t.remoteStore.remoteSyncer.applyRemoteEvent=Ru.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Rp.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Tp.bind(null,t),t.Pu.H_=ap.bind(null,t.eventManager),t.Pu.yu=cp.bind(null,t.eventManager),t}function Sp(n){const t=F(n);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Ip.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=wp.bind(null,t),t}class Tr{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(t){this.serializer=xr(t.databaseInfo.databaseId),this.sharedClientState=this.Du(t),this.persistence=this.Cu(t),await this.persistence.start(),this.localStore=this.vu(t),this.gcScheduler=this.Fu(t,this.localStore),this.indexBackfillerScheduler=this.Mu(t,this.localStore)}Fu(t,e){return null}Mu(t,e){return null}vu(t){return Cm(this.persistence,new Am,t.initialUser,this.serializer)}Cu(t){return new hu(gi.mi,this.serializer)}Du(t){return new Mm}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}Tr.provider={build:()=>new Tr};class Cp extends Tr{constructor(t){super(),this.cacheSizeBytes=t}Fu(t,e){K(this.persistence.referenceDelegate instanceof yr,46915);const r=this.persistence.referenceDelegate.garbageCollector;return new um(r,t.asyncQueue,e)}Cu(t){const e=this.cacheSizeBytes!==void 0?vt.withCacheSize(this.cacheSizeBytes):vt.DEFAULT;return new hu((r=>yr.mi(r,e)),this.serializer)}}class Ks{async initialize(t,e){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=r=>Ba(this.syncEngine,r,1),this.remoteStore.remoteSyncer.handleCredentialChange=Ap.bind(null,this.syncEngine),await np(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return(function(){return new sp})()}createDatastore(t){const e=xr(t.databaseInfo.databaseId),r=(function(o){return new Um(o)})(t.databaseInfo);return(function(o,a,u,h){return new $m(o,a,u,h)})(t.authCredentials,t.appCheckCredentials,r,e)}createRemoteStore(t){return(function(r,s,o,a,u){return new Gm(r,s,o,a,u)})(this.localStore,this.datastore,t.asyncQueue,(e=>Ba(this.syncEngine,e,0)),(function(){return Ma.v()?new Ma:new xm})())}createSyncEngine(t,e){return(function(s,o,a,u,h,d,m){const T=new fp(s,o,a,u,h,d);return m&&(T.gu=!0),T})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,e)}async terminate(){await(async function(e){const r=F(e);D(Ae,"RemoteStore shutting down."),r.Ea.add(5),await xn(r),r.Aa.shutdown(),r.Ra.set("Unknown")})(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}Ks.provider={build:()=>new Ks};class bp{constructor(t){this.observer=t,this.muted=!1}next(t){this.muted||this.observer.next&&this.Ou(this.observer.next,t)}error(t){this.muted||(this.observer.error?this.Ou(this.observer.error,t):$t("Uncaught Error in snapshot listener:",t.toString()))}Nu(){this.muted=!0}Ou(t,e){setTimeout((()=>{this.muted||t(e)}),0)}}const ce="FirestoreClient";class Pp{constructor(t,e,r,s,o){this.authCredentials=t,this.appCheckCredentials=e,this.asyncQueue=r,this.databaseInfo=s,this.user=pt.UNAUTHENTICATED,this.clientId=ri.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=o,this.authCredentials.start(r,(async a=>{D(ce,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a})),this.appCheckCredentials.start(r,(a=>(D(ce,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user))))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(t){this.authCredentialListener=t}setAppCheckTokenChangeListener(t){this.appCheckCredentialListener=t}terminate(){this.asyncQueue.enterRestrictedMode();const t=new ee;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),t.resolve()}catch(e){const r=Ai(e,"Failed to shutdown persistence");t.reject(r)}})),t.promise}}async function vs(n,t){n.asyncQueue.verifyOperationInProgress(),D(ce,"Initializing OfflineComponentProvider");const e=n.configuration;await t.initialize(e);let r=e.initialUser;n.setCredentialChangeListener((async s=>{r.isEqual(s)||(await du(t.localStore,s),r=s)})),t.persistence.setDatabaseDeletedListener((()=>n.terminate())),n._offlineComponents=t}async function qa(n,t){n.asyncQueue.verifyOperationInProgress();const e=await Vp(n);D(ce,"Initializing OnlineComponentProvider"),await t.initialize(e,n.configuration),n.setCredentialChangeListener((r=>Oa(t.remoteStore,r))),n.setAppCheckTokenChangeListener(((r,s)=>Oa(t.remoteStore,s))),n._onlineComponents=t}async function Vp(n){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){D(ce,"Using user provided OfflineComponentProvider");try{await vs(n,n._uninitializedComponentsProvider._offline)}catch(t){const e=t;if(!(function(s){return s.name==="FirebaseError"?s.code===C.FAILED_PRECONDITION||s.code===C.UNIMPLEMENTED:!(typeof DOMException<"u"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11})(e))throw e;Fe("Error using user provided cache. Falling back to memory cache: "+e),await vs(n,new Tr)}}else D(ce,"Using default OfflineComponentProvider"),await vs(n,new Cp(void 0));return n._offlineComponents}async function Vu(n){return n._onlineComponents||(n._uninitializedComponentsProvider?(D(ce,"Using user provided OnlineComponentProvider"),await qa(n,n._uninitializedComponentsProvider._online)):(D(ce,"Using default OnlineComponentProvider"),await qa(n,new Ks))),n._onlineComponents}function Dp(n){return Vu(n).then((t=>t.syncEngine))}async function kp(n){const t=await Vu(n),e=t.eventManager;return e.onListen=mp.bind(null,t.syncEngine),e.onUnlisten=_p.bind(null,t.syncEngine),e.onFirstRemoteStoreListen=pp.bind(null,t.syncEngine),e.onLastRemoteStoreUnlisten=yp.bind(null,t.syncEngine),e}function Np(n,t,e={}){const r=new ee;return n.asyncQueue.enqueueAndForget((async()=>(function(o,a,u,h,d){const m=new bp({next:v=>{m.Nu(),a.enqueueAndForget((()=>op(o,T)));const b=v.docs.has(u);!b&&v.fromCache?d.reject(new N(C.UNAVAILABLE,"Failed to get document because the client is offline.")):b&&v.fromCache&&h&&h.source==="server"?d.reject(new N(C.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):d.resolve(v)},error:v=>d.reject(v)}),T=new up(li(u.path),m,{includeMetadataChanges:!0,qa:!0});return ip(o,T)})(await kp(n),n.asyncQueue,t,e,r))),r.promise}function Du(n){const t={};return n.timeoutSeconds!==void 0&&(t.timeoutSeconds=n.timeoutSeconds),t}const $a=new Map;const ku="firestore.googleapis.com",za=!0;class Ga{constructor(t){if(t.host===void 0){if(t.ssl!==void 0)throw new N(C.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=ku,this.ssl=za}else this.host=t.host,this.ssl=t.ssl??za;if(this.isUsingEmulator=t.emulatorOptions!==void 0,this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,this.localCache=t.localCache,t.cacheSizeBytes===void 0)this.cacheSizeBytes=lu;else{if(t.cacheSizeBytes!==-1&&t.cacheSizeBytes<am)throw new N(C.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}$d("experimentalForceLongPolling",t.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",t.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:t.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Du(t.experimentalLongPollingOptions??{}),(function(r){if(r.timeoutSeconds!==void 0){if(isNaN(r.timeoutSeconds))throw new N(C.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<5)throw new N(C.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is 5)`);if(r.timeoutSeconds>30)throw new N(C.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!t.useFetchStreams}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.experimentalForceLongPolling===t.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===t.experimentalAutoDetectLongPolling&&(function(r,s){return r.timeoutSeconds===s.timeoutSeconds})(this.experimentalLongPollingOptions,t.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===t.ignoreUndefinedProperties&&this.useFetchStreams===t.useFetchStreams}}class bi{constructor(t,e,r,s){this._authCredentials=t,this._appCheckCredentials=e,this._databaseId=r,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Ga({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new N(C.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!=="notTerminated"}_setSettings(t){if(this._settingsFrozen)throw new N(C.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Ga(t),this._emulatorOptions=t.emulatorOptions||{},t.credentials!==void 0&&(this._authCredentials=(function(r){if(!r)return new kd;switch(r.type){case"firstParty":return new Od(r.sessionIndex||"0",r.iamToken||null,r.authTokenFactory||null);case"provider":return r.client;default:throw new N(C.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(t.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(e){const r=$a.get(e);r&&(D("ComponentProvider","Removing Datastore"),$a.delete(e),r.terminate())})(this),Promise.resolve()}}function Mp(n,t,e,r={}){n=ve(n,bi);const s=Zs(t),o=n._getSettings(),a={...o,emulatorOptions:n._getEmulatorOptions()},u=`${t}:${e}`;s&&(sh(`https://${u}`),ch("Firestore",!0)),o.host!==ku&&o.host!==u&&Fe("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");const h={...o,host:u,ssl:s,emulatorOptions:r};if(!In(h,a)&&(n._setSettings(h),r.mockUserToken)){let d,m;if(typeof r.mockUserToken=="string")d=r.mockUserToken,m=pt.MOCK_USER;else{d=ih(r.mockUserToken,n._app?.options.projectId);const T=r.mockUserToken.sub||r.mockUserToken.user_id;if(!T)throw new N(C.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");m=new pt(T)}n._authCredentials=new Nd(new wc(d,m))}}class Pi{constructor(t,e,r){this.converter=e,this._query=r,this.type="query",this.firestore=t}withConverter(t){return new Pi(this.firestore,t,this._query)}}class it{constructor(t,e,r){this.converter=e,this._key=r,this.type="document",this.firestore=t}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Vn(this.firestore,this.converter,this._key.path.popLast())}withConverter(t){return new it(this.firestore,t,this._key)}toJSON(){return{type:it._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(t,e,r){if(kn(e,it._jsonSchema))return new it(t,r||null,new x(Y.fromString(e.referencePath)))}}it._jsonSchemaVersion="firestore/documentReference/1.0",it._jsonSchema={type:nt("string",it._jsonSchemaVersion),referencePath:nt("string")};class Vn extends Pi{constructor(t,e,r){super(t,e,li(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const t=this._path.popLast();return t.isEmpty()?null:new it(this.firestore,null,new x(t))}withConverter(t){return new Vn(this.firestore,t,this._path)}}function xp(n,t,...e){if(n=Ft(n),arguments.length===1&&(t=ri.newId()),qd("doc","path",t),n instanceof bi){const r=Y.fromString(t,...e);return ia(r),new it(n,null,new x(r))}{if(!(n instanceof it||n instanceof Vn))throw new N(C.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=n._path.child(Y.fromString(t,...e));return ia(r),new it(n.firestore,n instanceof Vn?n.converter:null,new x(r))}}const Ha="AsyncQueue";class Ka{constructor(t=Promise.resolve()){this.Xu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new mu(this,"async_queue_retry"),this._c=()=>{const r=ws();r&&D(Ha,"Visibility state changed to "+r.visibilityState),this.M_.w_()},this.ac=t;const e=ws();e&&typeof e.addEventListener=="function"&&e.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.uc(),this.cc(t)}enterRestrictedMode(t){if(!this.ec){this.ec=!0,this.sc=t||!1;const e=ws();e&&typeof e.removeEventListener=="function"&&e.removeEventListener("visibilitychange",this._c)}}enqueue(t){if(this.uc(),this.ec)return new Promise((()=>{}));const e=new ee;return this.cc((()=>this.ec&&this.sc?Promise.resolve():(t().then(e.resolve,e.reject),e.promise))).then((()=>e.promise))}enqueueRetryable(t){this.enqueueAndForget((()=>(this.Xu.push(t),this.lc())))}async lc(){if(this.Xu.length!==0){try{await this.Xu[0](),this.Xu.shift(),this.M_.reset()}catch(t){if(!He(t))throw t;D(Ha,"Operation failed with retryable error: "+t)}this.Xu.length>0&&this.M_.p_((()=>this.lc()))}}cc(t){const e=this.ac.then((()=>(this.rc=!0,t().catch((r=>{throw this.nc=r,this.rc=!1,$t("INTERNAL UNHANDLED ERROR: ",Wa(r)),r})).then((r=>(this.rc=!1,r))))));return this.ac=e,e}enqueueAfterDelay(t,e,r){this.uc(),this.oc.indexOf(t)>-1&&(e=0);const s=vi.createAndSchedule(this,t,e,r,(o=>this.hc(o)));return this.tc.push(s),s}uc(){this.nc&&O(47125,{Pc:Wa(this.nc)})}verifyOperationInProgress(){}async Tc(){let t;do t=this.ac,await t;while(t!==this.ac)}Ic(t){for(const e of this.tc)if(e.timerId===t)return!0;return!1}Ec(t){return this.Tc().then((()=>{this.tc.sort(((e,r)=>e.targetTimeMs-r.targetTimeMs));for(const e of this.tc)if(e.skipDelay(),t!=="all"&&e.timerId===t)break;return this.Tc()}))}dc(t){this.oc.push(t)}hc(t){const e=this.tc.indexOf(t);this.tc.splice(e,1)}}function Wa(n){let t=n.message||"";return n.stack&&(t=n.stack.includes(n.message)?n.stack:n.message+`
36
+ `+n.stack),t}class Fr extends bi{constructor(t,e,r,s){super(t,e,r,s),this.type="firestore",this._queue=new Ka,this._persistenceKey=s?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const t=this._firestoreClient.terminate();this._queue=new Ka(t),this._firestoreClient=void 0,await t}}}function Op(n,t){const e=typeof n=="object"?n:dc(),r=typeof n=="string"?n:dr,s=Dn(e,"firestore").getImmediate({identifier:r});if(!s._initialized){const o=nh("firestore");o&&Mp(s,...o)}return s}function Nu(n){if(n._terminated)throw new N(C.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||Lp(n),n._firestoreClient}function Lp(n){const t=n._freezeSettings(),e=(function(s,o,a,u){return new tf(s,o,a,u.host,u.ssl,u.experimentalForceLongPolling,u.experimentalAutoDetectLongPolling,Du(u.experimentalLongPollingOptions),u.useFetchStreams,u.isUsingEmulator)})(n._databaseId,n._app?.options.appId||"",n._persistenceKey,t);n._componentsProvider||t.localCache?._offlineComponentProvider&&t.localCache?._onlineComponentProvider&&(n._componentsProvider={_offline:t.localCache._offlineComponentProvider,_online:t.localCache._onlineComponentProvider}),n._firestoreClient=new Pp(n._authCredentials,n._appCheckCredentials,n._queue,e,n._componentsProvider&&(function(s){const o=s?._online.build();return{_offline:s?._offline.build(o),_online:o}})(n._componentsProvider))}class bt{constructor(t){this._byteString=t}static fromBase64String(t){try{return new bt(dt.fromBase64String(t))}catch(e){throw new N(C.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(t){return new bt(dt.fromUint8Array(t))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(t){return this._byteString.isEqual(t._byteString)}toJSON(){return{type:bt._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(t){if(kn(t,bt._jsonSchema))return bt.fromBase64String(t.bytes)}}bt._jsonSchemaVersion="firestore/bytes/1.0",bt._jsonSchema={type:nt("string",bt._jsonSchemaVersion),bytes:nt("string")};class Ur{constructor(...t){for(let e=0;e<t.length;++e)if(t[e].length===0)throw new N(C.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ht(t)}isEqual(t){return this._internalPath.isEqual(t._internalPath)}}class Br{constructor(t){this._methodName=t}}class Ot{constructor(t,e){if(!isFinite(t)||t<-90||t>90)throw new N(C.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new N(C.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}_compareTo(t){return B(this._lat,t._lat)||B(this._long,t._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:Ot._jsonSchemaVersion}}static fromJSON(t){if(kn(t,Ot._jsonSchema))return new Ot(t.latitude,t.longitude)}}Ot._jsonSchemaVersion="firestore/geoPoint/1.0",Ot._jsonSchema={type:nt("string",Ot._jsonSchemaVersion),latitude:nt("number"),longitude:nt("number")};class Lt{constructor(t){this._values=(t||[]).map((e=>e))}toArray(){return this._values.map((t=>t))}isEqual(t){return(function(r,s){if(r.length!==s.length)return!1;for(let o=0;o<r.length;++o)if(r[o]!==s[o])return!1;return!0})(this._values,t._values)}toJSON(){return{type:Lt._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(t){if(kn(t,Lt._jsonSchema)){if(Array.isArray(t.vectorValues)&&t.vectorValues.every((e=>typeof e=="number")))return new Lt(t.vectorValues);throw new N(C.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}Lt._jsonSchemaVersion="firestore/vectorValue/1.0",Lt._jsonSchema={type:nt("string",Lt._jsonSchemaVersion),vectorValues:nt("object")};const Fp=/^__.*__$/;class Up{constructor(t,e,r){this.data=t,this.fieldMask=e,this.fieldTransforms=r}toMutation(t,e){return this.fieldMask!==null?new he(t,this.data,this.fieldMask,e,this.fieldTransforms):new Nn(t,this.data,e,this.fieldTransforms)}}class Mu{constructor(t,e,r){this.data=t,this.fieldMask=e,this.fieldTransforms=r}toMutation(t,e){return new he(t,this.data,this.fieldMask,e,this.fieldTransforms)}}function xu(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw O(40011,{Ac:n})}}class Vi{constructor(t,e,r,s,o,a){this.settings=t,this.databaseId=e,this.serializer=r,this.ignoreUndefinedProperties=s,o===void 0&&this.Rc(),this.fieldTransforms=o||[],this.fieldMask=a||[]}get path(){return this.settings.path}get Ac(){return this.settings.Ac}Vc(t){return new Vi({...this.settings,...t},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}mc(t){const e=this.path?.child(t),r=this.Vc({path:e,fc:!1});return r.gc(t),r}yc(t){const e=this.path?.child(t),r=this.Vc({path:e,fc:!1});return r.Rc(),r}wc(t){return this.Vc({path:void 0,fc:!0})}Sc(t){return Ir(t,this.settings.methodName,this.settings.bc||!1,this.path,this.settings.Dc)}contains(t){return this.fieldMask.find((e=>t.isPrefixOf(e)))!==void 0||this.fieldTransforms.find((e=>t.isPrefixOf(e.field)))!==void 0}Rc(){if(this.path)for(let t=0;t<this.path.length;t++)this.gc(this.path.get(t))}gc(t){if(t.length===0)throw this.Sc("Document fields must not be empty");if(xu(this.Ac)&&Fp.test(t))throw this.Sc('Document fields cannot begin and end with "__"')}}class Bp{constructor(t,e,r){this.databaseId=t,this.ignoreUndefinedProperties=e,this.serializer=r||xr(t)}Cc(t,e,r,s=!1){return new Vi({Ac:t,methodName:e,Dc:r,path:ht.emptyPath(),fc:!1,bc:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function Ou(n){const t=n._freezeSettings(),e=xr(n._databaseId);return new Bp(n._databaseId,!!t.ignoreUndefinedProperties,e)}function jp(n,t,e,r,s,o={}){const a=n.Cc(o.merge||o.mergeFields?2:0,t,e,s);ki("Data must be an object, but it was:",a,r);const u=Lu(r,a);let h,d;if(o.merge)h=new St(a.fieldMask),d=a.fieldTransforms;else if(o.mergeFields){const m=[];for(const T of o.mergeFields){const v=Ws(t,T,e);if(!a.contains(v))throw new N(C.INVALID_ARGUMENT,`Field '${v}' is specified in your field mask but missing from your input data.`);Uu(m,v)||m.push(v)}h=new St(m),d=a.fieldTransforms.filter((T=>h.covers(T.field)))}else h=null,d=a.fieldTransforms;return new Up(new At(u),h,d)}class jr extends Br{_toFieldTransform(t){if(t.Ac!==2)throw t.Ac===1?t.Sc(`${this._methodName}() can only appear at the top level of your update data`):t.Sc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return t.fieldMask.push(t.path),null}isEqual(t){return t instanceof jr}}class Di extends Br{constructor(t,e){super(t),this.Fc=e}_toFieldTransform(t){const e=new Pn(t.serializer,Hc(t.serializer,this.Fc));return new Cf(t.path,e)}isEqual(t){return t instanceof Di&&this.Fc===t.Fc}}function qp(n,t,e,r){const s=n.Cc(1,t,e);ki("Data must be an object, but it was:",s,r);const o=[],a=At.empty();le(r,((h,d)=>{const m=Ni(t,h,e);d=Ft(d);const T=s.yc(m);if(d instanceof jr)o.push(m);else{const v=qr(d,T);v!=null&&(o.push(m),a.set(m,v))}}));const u=new St(o);return new Mu(a,u,s.fieldTransforms)}function $p(n,t,e,r,s,o){const a=n.Cc(1,t,e),u=[Ws(t,r,e)],h=[s];if(o.length%2!=0)throw new N(C.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let v=0;v<o.length;v+=2)u.push(Ws(t,o[v])),h.push(o[v+1]);const d=[],m=At.empty();for(let v=u.length-1;v>=0;--v)if(!Uu(d,u[v])){const b=u[v];let k=h[v];k=Ft(k);const M=a.yc(b);if(k instanceof jr)d.push(b);else{const V=qr(k,M);V!=null&&(d.push(b),m.set(b,V))}}const T=new St(d);return new Mu(m,T,a.fieldTransforms)}function qr(n,t){if(Fu(n=Ft(n)))return ki("Unsupported field value:",t,n),Lu(n,t);if(n instanceof Br)return(function(r,s){if(!xu(s.Ac))throw s.Sc(`${r._methodName}() can only be used with update() and set()`);if(!s.path)throw s.Sc(`${r._methodName}() is not currently supported inside arrays`);const o=r._toFieldTransform(s);o&&s.fieldTransforms.push(o)})(n,t),null;if(n===void 0&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),n instanceof Array){if(t.settings.fc&&t.Ac!==4)throw t.Sc("Nested arrays are not supported");return(function(r,s){const o=[];let a=0;for(const u of r){let h=qr(u,s.wc(a));h==null&&(h={nullValue:"NULL_VALUE"}),o.push(h),a++}return{arrayValue:{values:o}}})(n,t)}return(function(r,s){if((r=Ft(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return Hc(s.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){const o=X.fromDate(r);return{timestampValue:_r(s.serializer,o)}}if(r instanceof X){const o=new X(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:_r(s.serializer,o)}}if(r instanceof Ot)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof bt)return{bytesValue:ru(s.serializer,r._byteString)};if(r instanceof it){const o=s.databaseId,a=r.firestore._databaseId;if(!a.isEqual(o))throw s.Sc(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:mi(r.firestore._databaseId||s.databaseId,r._key.path)}}if(r instanceof Lt)return(function(a,u){return{mapValue:{fields:{[Dc]:{stringValue:kc},[fr]:{arrayValue:{values:a.toArray().map((d=>{if(typeof d!="number")throw u.Sc("VectorValues must only contain numeric values.");return hi(u.serializer,d)}))}}}}}})(r,s);throw s.Sc(`Unsupported field value: ${si(r)}`)})(n,t)}function Lu(n,t){const e={};return Rc(n)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):le(n,((r,s)=>{const o=qr(s,t.mc(r));o!=null&&(e[r]=o)})),{mapValue:{fields:e}}}function Fu(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof X||n instanceof Ot||n instanceof bt||n instanceof it||n instanceof Br||n instanceof Lt)}function ki(n,t,e){if(!Fu(e)||!vc(e)){const r=si(e);throw r==="an object"?t.Sc(n+" a custom object"):t.Sc(n+" "+r)}}function Ws(n,t,e){if((t=Ft(t))instanceof Ur)return t._internalPath;if(typeof t=="string")return Ni(n,t);throw Ir("Field path arguments must be of type string or ",n,!1,void 0,e)}const zp=new RegExp("[~\\*/\\[\\]]");function Ni(n,t,e){if(t.search(zp)>=0)throw Ir(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,e);try{return new Ur(...t.split("."))._internalPath}catch{throw Ir(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,e)}}function Ir(n,t,e,r,s){const o=r&&!r.isEmpty(),a=s!==void 0;let u=`Function ${t}() called with invalid data`;e&&(u+=" (via `toFirestore()`)"),u+=". ";let h="";return(o||a)&&(h+=" (found",o&&(h+=` in field ${r}`),a&&(h+=` in document ${s}`),h+=")"),new N(C.INVALID_ARGUMENT,u+n+h)}function Uu(n,t){return n.some((e=>e.isEqual(t)))}class Bu{constructor(t,e,r,s,o){this._firestore=t,this._userDataWriter=e,this._key=r,this._document=s,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new it(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){const t=new Gp(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}return this._userDataWriter.convertValue(this._document.data.value)}}get(t){if(this._document){const e=this._document.data.field(ju("DocumentSnapshot.get",t));if(e!==null)return this._userDataWriter.convertValue(e)}}}class Gp extends Bu{data(){return super.data()}}function ju(n,t){return typeof t=="string"?Ni(n,t):t instanceof Ur?t._internalPath:t._delegate._internalPath}class Hp{convertValue(t,e="none"){switch(oe(t)){case 0:return null;case 1:return t.booleanValue;case 2:return tt(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(ie(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 11:return this.convertObject(t.mapValue,e);case 10:return this.convertVectorValue(t.mapValue);default:throw O(62114,{value:t})}}convertObject(t,e){return this.convertObjectMap(t.fields,e)}convertObjectMap(t,e="none"){const r={};return le(t,((s,o)=>{r[s]=this.convertValue(o,e)})),r}convertVectorValue(t){const e=t.fields?.[fr].arrayValue?.values?.map((r=>tt(r.doubleValue)));return new Lt(e)}convertGeoPoint(t){return new Ot(tt(t.latitude),tt(t.longitude))}convertArray(t,e){return(t.values||[]).map((r=>this.convertValue(r,e)))}convertServerTimestamp(t,e){switch(e){case"previous":const r=br(t);return r==null?null:this.convertValue(r,e);case"estimate":return this.convertTimestamp(An(t));default:return null}}convertTimestamp(t){const e=se(t);return new X(e.seconds,e.nanos)}convertDocumentKey(t,e){const r=Y.fromString(t);K(uu(r),9688,{name:t});const s=new Rn(r.get(1),r.get(3)),o=new x(r.popFirst(5));return s.isEqual(e)||$t(`Document ${o} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),o}}function Kp(n,t,e){let r;return r=n?n.toFirestore(t):t,r}class mn{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class Ie extends Bu{constructor(t,e,r,s,o,a){super(t,e,r,s,a),this._firestore=t,this._firestoreImpl=t,this.metadata=o}exists(){return super.exists()}data(t={}){if(this._document){if(this._converter){const e=new cr(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(e,t)}return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps)}}get(t,e={}){if(this._document){const r=this._document.data.field(ju("DocumentSnapshot.get",t));if(r!==null)return this._userDataWriter.convertValue(r,e.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new N(C.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const t=this._document,e={};return e.type=Ie._jsonSchemaVersion,e.bundle="",e.bundleSource="DocumentSnapshot",e.bundleName=this._key.toString(),!t||!t.isValidDocument()||!t.isFoundDocument()?e:(this._userDataWriter.convertObjectMap(t.data.value.mapValue.fields,"previous"),e.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),e)}}Ie._jsonSchemaVersion="firestore/documentSnapshot/1.0",Ie._jsonSchema={type:nt("string",Ie._jsonSchemaVersion),bundleSource:nt("string","DocumentSnapshot"),bundleName:nt("string"),bundle:nt("string")};class cr extends Ie{data(t={}){return super.data(t)}}class Tn{constructor(t,e,r,s){this._firestore=t,this._userDataWriter=e,this._snapshot=s,this.metadata=new mn(s.hasPendingWrites,s.fromCache),this.query=r}get docs(){const t=[];return this.forEach((e=>t.push(e))),t}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(t,e){this._snapshot.docs.forEach((r=>{t.call(e,new cr(this._firestore,this._userDataWriter,r.key,r,new mn(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(t={}){const e=!!t.includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new N(C.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=(function(s,o){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map((u=>{const h=new cr(s._firestore,s._userDataWriter,u.doc.key,u.doc,new mn(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:h,oldIndex:-1,newIndex:a++}}))}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter((u=>o||u.type!==3)).map((u=>{const h=new cr(s._firestore,s._userDataWriter,u.doc.key,u.doc,new mn(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);let d=-1,m=-1;return u.type!==0&&(d=a.indexOf(u.doc.key),a=a.delete(u.doc.key)),u.type!==1&&(a=a.add(u.doc),m=a.indexOf(u.doc.key)),{type:Wp(u.type),doc:h,oldIndex:d,newIndex:m}}))}})(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new N(C.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const t={};t.type=Tn._jsonSchemaVersion,t.bundleSource="QuerySnapshot",t.bundleName=ri.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;const e=[],r=[],s=[];return this.docs.forEach((o=>{o._document!==null&&(e.push(o._document),r.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),s.push(o.ref.path))})),t.bundle=(this._firestore,this.query._query,t.bundleName,"NOT SUPPORTED"),t}}function Wp(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return O(61501,{type:n})}}function Qp(n){n=ve(n,it);const t=ve(n.firestore,Fr);return Np(Nu(t),n._key).then((e=>Zp(t,n,e)))}Tn._jsonSchemaVersion="firestore/querySnapshot/1.0",Tn._jsonSchema={type:nt("string",Tn._jsonSchemaVersion),bundleSource:nt("string","QuerySnapshot"),bundleName:nt("string"),bundle:nt("string")};class Xp extends Hp{constructor(t){super(),this.firestore=t}convertBytes(t){return new bt(t)}convertReference(t){const e=this.convertDocumentKey(t,this.firestore._databaseId);return new it(this.firestore,null,e)}}function Yp(n,t,e){n=ve(n,it);const r=ve(n.firestore,Fr),s=Kp(n.converter,t);return qu(r,[jp(Ou(r),"setDoc",n._key,s,n.converter!==null,e).toMutation(n._key,Mt.none())])}function Jp(n,t,e,...r){n=ve(n,it);const s=ve(n.firestore,Fr),o=Ou(s);let a;return a=typeof(t=Ft(t))=="string"||t instanceof Ur?$p(o,"updateDoc",n._key,t,e,r):qp(o,"updateDoc",n._key,t),qu(s,[a.toMutation(n._key,Mt.exists(!0))])}function qu(n,t){return(function(r,s){const o=new ee;return r.asyncQueue.enqueueAndForget((async()=>Ep(await Dp(r),s,o))),o.promise})(Nu(n),t)}function Zp(n,t,e){const r=e.docs.get(t._key),s=new Xp(n);return new Ie(n,s,t._key,r,new mn(e.hasPendingWrites,e.fromCache),t.converter)}function tg(n){return new Di("increment",n)}(function(t,e=!0){(function(s){ze=s})(Ed),ne(new jt("firestore",((r,{instanceIdentifier:s,options:o})=>{const a=r.getProvider("app").getImmediate(),u=new Fr(new Md(r.getProvider("auth-internal")),new Ld(a,r.getProvider("app-check-internal")),(function(d,m){if(!Object.prototype.hasOwnProperty.apply(d.options,["projectId"]))throw new N(C.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Rn(d.options.projectId,m)})(a,s),a);return o={useFetchStreams:e,...o},u._setSettings(o),u}),"PUBLIC").setMultipleInstances(!0)),kt(ea,na,t),kt(ea,na,"esm2020")})();const $u="@firebase/installations",Mi="0.6.19";const zu=1e4,Gu=`w:${Mi}`,Hu="FIS_v2",eg="https://firebaseinstallations.googleapis.com/v1",ng=3600*1e3,rg="installations",sg="Installations";const ig={"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."},Re=new Rr(rg,sg,ig);function Ku(n){return n instanceof ue&&n.code.includes("request-failed")}function Wu({projectId:n}){return`${eg}/projects/${n}/installations`}function Qu(n){return{token:n.token,requestStatus:2,expiresIn:ag(n.expiresIn),creationTime:Date.now()}}async function Xu(n,t){const r=(await t.json()).error;return Re.create("request-failed",{requestName:n,serverCode:r.code,serverMessage:r.message,serverStatus:r.status})}function Yu({apiKey:n}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":n})}function og(n,{refreshToken:t}){const e=Yu(n);return e.append("Authorization",cg(t)),e}async function Ju(n){const t=await n();return t.status>=500&&t.status<600?n():t}function ag(n){return Number(n.replace("s","000"))}function cg(n){return`${Hu} ${n}`}async function ug({appConfig:n,heartbeatServiceProvider:t},{fid:e}){const r=Wu(n),s=Yu(n),o=t.getImmediate({optional:!0});if(o){const d=await o.getHeartbeatsHeader();d&&s.append("x-firebase-client",d)}const a={fid:e,authVersion:Hu,appId:n.appId,sdkVersion:Gu},u={method:"POST",headers:s,body:JSON.stringify(a)},h=await Ju(()=>fetch(r,u));if(h.ok){const d=await h.json();return{fid:d.fid||e,registrationStatus:2,refreshToken:d.refreshToken,authToken:Qu(d.authToken)}}else throw await Xu("Create Installation",h)}function Zu(n){return new Promise(t=>{setTimeout(t,n)})}function lg(n){return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_")}const hg=/^[cdef][\w-]{21}$/,Qs="";function dg(){try{const n=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(n),n[0]=112+n[0]%16;const e=fg(n);return hg.test(e)?e:Qs}catch{return Qs}}function fg(n){return lg(n).substr(0,22)}function $r(n){return`${n.appName}!${n.appId}`}const tl=new Map;function el(n,t){const e=$r(n);nl(e,t),mg(e,t)}function nl(n,t){const e=tl.get(n);if(e)for(const r of e)r(t)}function mg(n,t){const e=pg();e&&e.postMessage({key:n,fid:t}),gg()}let Te=null;function pg(){return!Te&&"BroadcastChannel"in self&&(Te=new BroadcastChannel("[Firebase] FID Change"),Te.onmessage=n=>{nl(n.data.key,n.data.fid)}),Te}function gg(){tl.size===0&&Te&&(Te.close(),Te=null)}const _g="firebase-installations-database",yg=1,Se="firebase-installations-store";let As=null;function xi(){return As||(As=lc(_g,yg,{upgrade:(n,t)=>{t===0&&n.createObjectStore(Se)}})),As}async function wr(n,t){const e=$r(n),s=(await xi()).transaction(Se,"readwrite"),o=s.objectStore(Se),a=await o.get(e);return await o.put(t,e),await s.done,(!a||a.fid!==t.fid)&&el(n,t.fid),t}async function rl(n){const t=$r(n),r=(await xi()).transaction(Se,"readwrite");await r.objectStore(Se).delete(t),await r.done}async function zr(n,t){const e=$r(n),s=(await xi()).transaction(Se,"readwrite"),o=s.objectStore(Se),a=await o.get(e),u=t(a);return u===void 0?await o.delete(e):await o.put(u,e),await s.done,u&&(!a||a.fid!==u.fid)&&el(n,u.fid),u}async function Oi(n){let t;const e=await zr(n.appConfig,r=>{const s=Eg(r),o=Tg(n,s);return t=o.registrationPromise,o.installationEntry});return e.fid===Qs?{installationEntry:await t}:{installationEntry:e,registrationPromise:t}}function Eg(n){const t=n||{fid:dg(),registrationStatus:0};return sl(t)}function Tg(n,t){if(t.registrationStatus===0){if(!navigator.onLine){const s=Promise.reject(Re.create("app-offline"));return{installationEntry:t,registrationPromise:s}}const e={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=Ig(n,e);return{installationEntry:e,registrationPromise:r}}else return t.registrationStatus===1?{installationEntry:t,registrationPromise:wg(n)}:{installationEntry:t}}async function Ig(n,t){try{const e=await ug(n,t);return wr(n.appConfig,e)}catch(e){throw Ku(e)&&e.customData.serverCode===409?await rl(n.appConfig):await wr(n.appConfig,{fid:t.fid,registrationStatus:0}),e}}async function wg(n){let t=await Qa(n.appConfig);for(;t.registrationStatus===1;)await Zu(100),t=await Qa(n.appConfig);if(t.registrationStatus===0){const{installationEntry:e,registrationPromise:r}=await Oi(n);return r||e}return t}function Qa(n){return zr(n,t=>{if(!t)throw Re.create("installation-not-found");return sl(t)})}function sl(n){return vg(n)?{fid:n.fid,registrationStatus:0}:n}function vg(n){return n.registrationStatus===1&&n.registrationTime+zu<Date.now()}async function Ag({appConfig:n,heartbeatServiceProvider:t},e){const r=Rg(n,e),s=og(n,e),o=t.getImmediate({optional:!0});if(o){const d=await o.getHeartbeatsHeader();d&&s.append("x-firebase-client",d)}const a={installation:{sdkVersion:Gu,appId:n.appId}},u={method:"POST",headers:s,body:JSON.stringify(a)},h=await Ju(()=>fetch(r,u));if(h.ok){const d=await h.json();return Qu(d)}else throw await Xu("Generate Auth Token",h)}function Rg(n,{fid:t}){return`${Wu(n)}/${t}/authTokens:generate`}async function Li(n,t=!1){let e;const r=await zr(n.appConfig,o=>{if(!il(o))throw Re.create("not-registered");const a=o.authToken;if(!t&&bg(a))return o;if(a.requestStatus===1)return e=Sg(n,t),o;{if(!navigator.onLine)throw Re.create("app-offline");const u=Vg(o);return e=Cg(n,u),u}});return e?await e:r.authToken}async function Sg(n,t){let e=await Xa(n.appConfig);for(;e.authToken.requestStatus===1;)await Zu(100),e=await Xa(n.appConfig);const r=e.authToken;return r.requestStatus===0?Li(n,t):r}function Xa(n){return zr(n,t=>{if(!il(t))throw Re.create("not-registered");const e=t.authToken;return Dg(e)?{...t,authToken:{requestStatus:0}}:t})}async function Cg(n,t){try{const e=await Ag(n,t),r={...t,authToken:e};return await wr(n.appConfig,r),e}catch(e){if(Ku(e)&&(e.customData.serverCode===401||e.customData.serverCode===404))await rl(n.appConfig);else{const r={...t,authToken:{requestStatus:0}};await wr(n.appConfig,r)}throw e}}function il(n){return n!==void 0&&n.registrationStatus===2}function bg(n){return n.requestStatus===2&&!Pg(n)}function Pg(n){const t=Date.now();return t<n.creationTime||n.creationTime+n.expiresIn<t+ng}function Vg(n){const t={requestStatus:1,requestTime:Date.now()};return{...n,authToken:t}}function Dg(n){return n.requestStatus===1&&n.requestTime+zu<Date.now()}async function kg(n){const t=n,{installationEntry:e,registrationPromise:r}=await Oi(t);return r?r.catch(console.error):Li(t).catch(console.error),e.fid}async function Ng(n,t=!1){const e=n;return await Mg(e),(await Li(e,t)).token}async function Mg(n){const{registrationPromise:t}=await Oi(n);t&&await t}function xg(n){if(!n||!n.options)throw Rs("App Configuration");if(!n.name)throw Rs("App Name");const t=["projectId","apiKey","appId"];for(const e of t)if(!n.options[e])throw Rs(e);return{appName:n.name,projectId:n.options.projectId,apiKey:n.options.apiKey,appId:n.options.appId}}function Rs(n){return Re.create("missing-app-config-values",{valueName:n})}const ol="installations",Og="installations-internal",Lg=n=>{const t=n.getProvider("app").getImmediate(),e=xg(t),r=Dn(t,"heartbeat");return{app:t,appConfig:e,heartbeatServiceProvider:r,_delete:()=>Promise.resolve()}},Fg=n=>{const t=n.getProvider("app").getImmediate(),e=Dn(t,ol).getImmediate();return{getId:()=>kg(e),getToken:s=>Ng(e,s)}};function Ug(){ne(new jt(ol,Lg,"PUBLIC")),ne(new jt(Og,Fg,"PRIVATE"))}Ug();kt($u,Mi);kt($u,Mi,"esm2020");const vr="analytics",Bg="firebase_id",jg="origin",qg=60*1e3,$g="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Fi="https://www.googletagmanager.com/gtag/js";const Tt=new ti("@firebase/analytics");const zg={"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-initialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."},Ct=new Rr("analytics","Analytics",zg);function Gg(n){if(!n.startsWith(Fi)){const t=Ct.create("invalid-gtag-resource",{gtagURL:n});return Tt.warn(t.message),""}return n}function al(n){return Promise.all(n.map(t=>t.catch(e=>e)))}function Hg(n,t){let e;return window.trustedTypes&&(e=window.trustedTypes.createPolicy(n,t)),e}function Kg(n,t){const e=Hg("firebase-js-sdk-policy",{createScriptURL:Gg}),r=document.createElement("script"),s=`${Fi}?l=${n}&id=${t}`;r.src=e?e?.createScriptURL(s):s,r.async=!0,document.head.appendChild(r)}function Wg(n){let t=[];return Array.isArray(window[n])?t=window[n]:window[n]=t,t}async function Qg(n,t,e,r,s,o){const a=r[s];try{if(a)await t[a];else{const h=(await al(e)).find(d=>d.measurementId===s);h&&await t[h.appId]}}catch(u){Tt.error(u)}n("config",s,o)}async function Xg(n,t,e,r,s){try{let o=[];if(s&&s.send_to){let a=s.send_to;Array.isArray(a)||(a=[a]);const u=await al(e);for(const h of a){const d=u.find(T=>T.measurementId===h),m=d&&t[d.appId];if(m)o.push(m);else{o=[];break}}}o.length===0&&(o=Object.values(t)),await Promise.all(o),n("event",r,s||{})}catch(o){Tt.error(o)}}function Yg(n,t,e,r){async function s(o,...a){try{if(o==="event"){const[u,h]=a;await Xg(n,t,e,u,h)}else if(o==="config"){const[u,h]=a;await Qg(n,t,e,r,u,h)}else if(o==="consent"){const[u,h]=a;n("consent",u,h)}else if(o==="get"){const[u,h,d]=a;n("get",u,h,d)}else if(o==="set"){const[u]=a;n("set",u)}else n(o,...a)}catch(u){Tt.error(u)}}return s}function Jg(n,t,e,r,s){let o=function(...a){window[r].push(arguments)};return window[s]&&typeof window[s]=="function"&&(o=window[s]),window[s]=Yg(o,n,t,e),{gtagCore:o,wrappedGtag:window[s]}}function Zg(n){const t=window.document.getElementsByTagName("script");for(const e of Object.values(t))if(e.src&&e.src.includes(Fi)&&e.src.includes(n))return e;return null}const t_=30,e_=1e3;class n_{constructor(t={},e=e_){this.throttleMetadata=t,this.intervalMillis=e}getThrottleMetadata(t){return this.throttleMetadata[t]}setThrottleMetadata(t,e){this.throttleMetadata[t]=e}deleteThrottleMetadata(t){delete this.throttleMetadata[t]}}const cl=new n_;function r_(n){return new Headers({Accept:"application/json","x-goog-api-key":n})}async function s_(n){const{appId:t,apiKey:e}=n,r={method:"GET",headers:r_(e)},s=$g.replace("{app-id}",t),o=await fetch(s,r);if(o.status!==200&&o.status!==304){let a="";try{const u=await o.json();u.error?.message&&(a=u.error.message)}catch{}throw Ct.create("config-fetch-failed",{httpStatus:o.status,responseMessage:a})}return o.json()}async function i_(n,t=cl,e){const{appId:r,apiKey:s,measurementId:o}=n.options;if(!r)throw Ct.create("no-app-id");if(!s){if(o)return{measurementId:o,appId:r};throw Ct.create("no-api-key")}const a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},u=new c_;return setTimeout(async()=>{u.abort()},qg),ul({appId:r,apiKey:s,measurementId:o},a,u,t)}async function ul(n,{throttleEndTimeMillis:t,backoffCount:e},r,s=cl){const{appId:o,measurementId:a}=n;try{await o_(r,t)}catch(u){if(a)return Tt.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${a} provided in the "measurementId" field in the local Firebase config. [${u?.message}]`),{appId:o,measurementId:a};throw u}try{const u=await s_(n);return s.deleteThrottleMetadata(o),u}catch(u){const h=u;if(!a_(h)){if(s.deleteThrottleMetadata(o),a)return Tt.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${a} provided in the "measurementId" field in the local Firebase config. [${h?.message}]`),{appId:o,measurementId:a};throw u}const d=Number(h?.customData?.httpStatus)===503?Go(e,s.intervalMillis,t_):Go(e,s.intervalMillis),m={throttleEndTimeMillis:Date.now()+d,backoffCount:e+1};return s.setThrottleMetadata(o,m),Tt.debug(`Calling attemptFetch again in ${d} millis`),ul(n,m,r,s)}}function o_(n,t){return new Promise((e,r)=>{const s=Math.max(t-Date.now(),0),o=setTimeout(e,s);n.addEventListener(()=>{clearTimeout(o),r(Ct.create("fetch-throttle",{throttleEndTimeMillis:t}))})})}function a_(n){if(!(n instanceof ue)||!n.customData)return!1;const t=Number(n.customData.httpStatus);return t===429||t===500||t===503||t===504}class c_{constructor(){this.listeners=[]}addEventListener(t){this.listeners.push(t)}abort(){this.listeners.forEach(t=>t())}}async function u_(n,t,e,r,s){if(s&&s.global){n("event",e,r);return}else{const o=await t,a={...r,send_to:o};n("event",e,a)}}async function l_(n,t,e,r){if(r&&r.global){const s={};for(const o of Object.keys(e))s[`user_properties.${o}`]=e[o];return n("set",s),Promise.resolve()}else{const s=await t;n("config",s,{update:!0,user_properties:e})}}async function h_(){if(oc())try{await ac()}catch(n){return Tt.warn(Ct.create("indexeddb-unavailable",{errorInfo:n?.toString()}).message),!1}else return Tt.warn(Ct.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;return!0}async function d_(n,t,e,r,s,o,a){const u=i_(n);u.then(v=>{e[v.measurementId]=v.appId,n.options.measurementId&&v.measurementId!==n.options.measurementId&&Tt.warn(`The measurement ID in the local Firebase config (${n.options.measurementId}) does not match the measurement ID fetched from the server (${v.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)}).catch(v=>Tt.error(v)),t.push(u);const h=h_().then(v=>{if(v)return r.getId()}),[d,m]=await Promise.all([u,h]);Zg(o)||Kg(o,d.measurementId),s("js",new Date);const T=a?.config??{};return T[jg]="firebase",T.update=!0,m!=null&&(T[Bg]=m),s("config",d.measurementId,T),d.measurementId}class f_{constructor(t){this.app=t}_delete(){return delete Le[this.app.options.appId],Promise.resolve()}}let Le={},Ya=[];const Ja={};let Ss="dataLayer",m_="gtag",Za,Ui,tc=!1;function p_(){const n=[];if(hh()&&n.push("This is a browser extension environment."),fh()||n.push("Cookies are not available."),n.length>0){const t=n.map((r,s)=>`(${s+1}) ${r}`).join(" "),e=Ct.create("invalid-analytics-context",{errorInfo:t});Tt.warn(e.message)}}function g_(n,t,e){p_();const r=n.options.appId;if(!r)throw Ct.create("no-app-id");if(!n.options.apiKey)if(n.options.measurementId)Tt.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${n.options.measurementId} provided in the "measurementId" field in the local Firebase config.`);else throw Ct.create("no-api-key");if(Le[r]!=null)throw Ct.create("already-exists",{id:r});if(!tc){Wg(Ss);const{wrappedGtag:o,gtagCore:a}=Jg(Le,Ya,Ja,Ss,m_);Ui=o,Za=a,tc=!0}return Le[r]=d_(n,Ya,Ja,t,Za,Ss,e),new f_(n)}function __(n=dc()){n=Ft(n);const t=Dn(n,vr);return t.isInitialized()?t.getImmediate():y_(n)}function y_(n,t={}){const e=Dn(n,vr);if(e.isInitialized()){const s=e.getImmediate();if(In(t,e.getOptions()))return s;throw Ct.create("already-initialized")}return e.initialize({options:t})}function E_(n,t,e){n=Ft(n),l_(Ui,Le[n.app.options.appId],t,e).catch(r=>Tt.error(r))}function Ar(n,t,e,r){n=Ft(n),u_(Ui,Le[n.app.options.appId],t,e,r).catch(s=>Tt.error(s))}const ec="@firebase/analytics",nc="0.10.19";function T_(){ne(new jt(vr,(t,{options:e})=>{const r=t.getProvider("app").getImmediate(),s=t.getProvider("installations-internal").getImmediate();return g_(r,s,e)},"PUBLIC")),ne(new jt("analytics-internal",n,"PRIVATE")),kt(ec,nc),kt(ec,nc,"esm2020");function n(t){try{const e=t.getProvider(vr).getImmediate();return{logEvent:(r,s,o)=>Ar(e,r,s,o),setUserProperties:(r,s)=>E_(e,r,s)}}catch(e){throw Ct.create("interop-component-reg-failed",{reason:e})}}}T_();const Xs={apiKey:"AIzaSyCkhjgtsyiiEgMAY8aCUlQflwyqnlG0dfs",authDomain:"christmas-tree-d8a85.firebaseapp.com",projectId:"christmas-tree-d8a85",storageBucket:"christmas-tree-d8a85.firebasestorage.app",messagingSenderId:"644462860826",appId:"1:644462860826:web:6f0fbf3d216eb075374fa3",measurementId:"G-M9DS2FV48Y"},ll=hc(Xs),I_=Op(ll),Ys=__(ll);Ar(Ys,"app_open");const w_=async()=>{const n=xp(I_,"stats","global");try{const t=await Qp(n);return t.exists()?(await Jp(n,{installs:tg(1)}),Ar(Ys,"install_incremented"),t.data().installs+1):(console.log("Document does not exist. Creating new..."),await Yp(n,{installs:1}),Ar(Ys,"first_install_created"),1)}catch(t){return console.error("Firebase Details:",{projectId:Xs.projectId,apiKey:Xs.apiKey?"Present":"Missing"}),console.error("Firestore Error:",t.code,t.message),t.code==="permission-denied"&&(console.warn("⚠️ PERMISSION DENIED: Please check your Firestore Security Rules in the Firebase Console."),console.warn("Try setting rules to: allow read, write: if true; (for development)")),1337}};class v_{constructor(t={}){this.options={terminalId:t.terminalId||"terminal",typewriterId:t.typewriterId||"typewriter",logsId:t.logsId||"logs",treeCanvasId:t.treeCanvasId||"tree-canvas",snowCanvasId:t.snowCanvasId||"snow-canvas",installCountId:t.installCountId||"install-count",...t}}start(){this.terminalPhase()}terminalPhase(){new $l(this.options.typewriterId,this.options.logsId,()=>{const e=document.getElementById(this.options.terminalId);e&&e.classList.add("fade-out"),w_().then(r=>{const s=document.getElementById(this.options.installCountId);s&&(s.textContent=r.toLocaleString())}),setTimeout(()=>{this.startScene()},1e3)}).start()}startScene(){this.tree=new zl(this.options.treeCanvasId),this.tree.animate(),this.snow=new Gl(this.options.snowCanvasId),this.snow.animate(),this.showUI()}showUI(){["title","stats","reset-btn","share-btn","footer"].forEach((e,r)=>{const s=document.getElementById(e);s&&setTimeout(()=>{s.classList.remove("hidden"),s.offsetWidth,s.classList.add("visible")},r*500)}),this.initEventListeners()}initEventListeners(){const t=document.getElementById(this.options.shareBtnId||"share-btn"),e=document.getElementById(this.options.resetBtnId||"reset-btn");t&&t.addEventListener("click",async()=>{const r={title:"npm install christmas-tree",text:"Installs the most advanced Christmas tree directly to your browser. #coding #christmas #javascript",url:window.location.href};if(navigator.share)try{await navigator.share(r)}catch{console.log("Share canceled")}else{navigator.clipboard.writeText(window.location.href);const s=t.textContent;t.textContent="Copied!",setTimeout(()=>{t.textContent=s},2e3)}}),e&&e.addEventListener("click",()=>{location.reload()})}}const A_=new v_({terminalId:"terminal",typewriterId:"typewriter",logsId:"logs",treeCanvasId:"tree-canvas",snowCanvasId:"snow-canvas",installCountId:"install-count"});A_.start();
@@ -0,0 +1,47 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>npm install christmas-tree</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <link
10
+ href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&family=Orbitron:wght@400;700&display=swap"
11
+ rel="stylesheet"
12
+ />
13
+ <script type="module" crossorigin src="/assets/index-Ce4du7Q6.js"></script>
14
+ <link rel="stylesheet" crossorigin href="/assets/index-C89fMKDr.css">
15
+ </head>
16
+ <body>
17
+ <div id="app" class="crt scanline">
18
+ <div id="terminal" class="terminal-overlay">
19
+ <div class="terminal-content">
20
+ <span class="prompt">user@dev:~$</span> <span id="typewriter"></span
21
+ ><span class="cursor">█</span>
22
+ <div id="logs"></div>
23
+ </div>
24
+ </div>
25
+ <div id="scene">
26
+ <canvas id="bg-canvas"></canvas>
27
+ <canvas id="tree-canvas"></canvas>
28
+ <canvas id="snow-canvas"></canvas>
29
+ </div>
30
+ <div id="ui-top">
31
+ <h1 id="title" class="hidden glitch">MERRY CHRISTMAS</h1>
32
+ <div id="stats" class="hidden">
33
+ Global Installs: <span id="install-count">Loading...</span>
34
+ </div>
35
+ </div>
36
+ <div id="ui-bottom">
37
+ <div class="action-buttons">
38
+ <button id="share-btn" class="hidden">Share</button>
39
+ <button id="reset-btn" class="hidden">Run Again</button>
40
+ </div>
41
+ <div id="footer" class="hidden">
42
+ developed by <a href="https://www.instagram.com/dev_seochan/" target="_blank">seochan</a>
43
+ </div>
44
+ </div>
45
+ </div>
46
+ </body>
47
+ </html>
package/dist/vite.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "npm-christmas-tree",
3
+ "version": "1.0.0",
4
+ "description": "A hyper-realistic, terminal-based Christmas tree experience for developers.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "bin": {
8
+ "npm-christmas-tree": "bin/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "bin",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "dev": "vite",
18
+ "build": "vite build",
19
+ "preview": "vite preview",
20
+ "prepare": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "christmas",
24
+ "tree",
25
+ "matrix",
26
+ "terminal",
27
+ "npx",
28
+ "holiday"
29
+ ],
30
+ "author": "seochan",
31
+ "license": "MIT",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/seochan99/npm-christmas-tree.git"
35
+ },
36
+ "devDependencies": {
37
+ "vite": "^7.2.4"
38
+ },
39
+ "dependencies": {
40
+ "firebase": "^12.7.0",
41
+ "open": "^10.1.0"
42
+ }
43
+ }