@tushar-br/desktop 1.0.248 → 1.0.249

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.

Potentially problematic release.


This version of @tushar-br/desktop might be problematic. Click here for more details.

Files changed (147) hide show
  1. package/package.json +1 -1
  2. package/staging_area/desktop/resume web/dist/assets/KaliLinux-B8gJf7kt.js +26 -0
  3. package/staging_area/desktop/resume web/dist/assets/MobileViewSimulator-aeGEZ5cs.js +5 -0
  4. package/staging_area/desktop/resume web/dist/assets/SecretNotes-oMDnic6h.js +16 -0
  5. package/staging_area/desktop/resume web/dist/assets/images/1769177455986_screenshot_2026_01_23_194039.png +0 -0
  6. package/staging_area/desktop/resume web/dist/assets/images/1770625084592_screenshot_2026_02_09_134633.png +0 -0
  7. package/staging_area/desktop/resume web/dist/assets/images/1770625157233_screenshot_2026_02_08_200105.png +0 -0
  8. package/staging_area/desktop/resume web/dist/assets/images/1770625318954_screenshot_2026_02_09_135032.png +0 -0
  9. package/staging_area/desktop/resume web/dist/assets/images/1771471211893_screenshot_2026_02_19_084940.png +0 -0
  10. package/staging_area/desktop/resume web/dist/assets/images/1771471268955_screenshot_2026_02_19_085052.png +0 -0
  11. package/staging_area/desktop/resume web/dist/assets/images/1771471360160_screenshot_2026_02_18_15_57_31_33_b783bf344239542886fee7b48fa4b892.jpg +0 -0
  12. package/staging_area/desktop/resume web/dist/assets/images/1771471388247_screenshot_2026_02_18_15_57_31_33_b783bf344239542886fee7b48fa4b892.jpg +0 -0
  13. package/staging_area/desktop/resume web/dist/assets/images/1771471567331_screenshot_2026_02_19_085459.png +0 -0
  14. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (1).jpeg +0 -0
  15. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (2).jpeg +0 -0
  16. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (3).jpeg +0 -0
  17. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (4).jpeg +0 -0
  18. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (5).jpeg +0 -0
  19. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (6).jpeg +0 -0
  20. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (7).jpeg +0 -0
  21. package/staging_area/desktop/resume web/dist/assets/images/Tushar/tushar (8).jpeg +0 -0
  22. package/staging_area/desktop/resume web/dist/assets/images/apk-laptop-wp.png +0 -0
  23. package/staging_area/desktop/resume web/dist/assets/images/apk-mobile-wp.png +0 -0
  24. package/staging_area/desktop/resume web/dist/assets/images/avatar.png +0 -0
  25. package/staging_area/desktop/resume web/dist/assets/images/blog-1.png +0 -0
  26. package/staging_area/desktop/resume web/dist/assets/images/cover-tusharbr.jpg +0 -0
  27. package/staging_area/desktop/resume web/dist/assets/images/cursor.png +0 -0
  28. package/staging_area/desktop/resume web/dist/assets/images/cursor.svg +3 -0
  29. package/staging_area/desktop/resume web/dist/assets/images/cyber-bg-smooth.png +0 -0
  30. package/staging_area/desktop/resume web/dist/assets/images/features/desktop_file_explorer.jpg +0 -0
  31. package/staging_area/desktop/resume web/dist/assets/images/features/desktop_home.jpg +0 -0
  32. package/staging_area/desktop/resume web/dist/assets/images/features/desktop_os.jpg +0 -0
  33. package/staging_area/desktop/resume web/dist/assets/images/features/mobile_home.jpg +0 -0
  34. package/staging_area/desktop/resume web/dist/assets/images/global-bg-v2.png +0 -0
  35. package/staging_area/desktop/resume web/dist/assets/images/global-bg-v3.png +0 -0
  36. package/staging_area/desktop/resume web/dist/assets/images/global-bg-v4.png +0 -0
  37. package/staging_area/desktop/resume web/dist/assets/images/global-bg-v5.png +0 -0
  38. package/staging_area/desktop/resume web/dist/assets/images/global-bg.png +0 -0
  39. package/staging_area/desktop/resume web/dist/assets/images/grid/1.png +0 -0
  40. package/staging_area/desktop/resume web/dist/assets/images/grid/10.png +0 -0
  41. package/staging_area/desktop/resume web/dist/assets/images/grid/11.png +0 -0
  42. package/staging_area/desktop/resume web/dist/assets/images/grid/12.png +0 -0
  43. package/staging_area/desktop/resume web/dist/assets/images/grid/13.png +0 -0
  44. package/staging_area/desktop/resume web/dist/assets/images/grid/14.png +0 -0
  45. package/staging_area/desktop/resume web/dist/assets/images/grid/15.png +0 -0
  46. package/staging_area/desktop/resume web/dist/assets/images/grid/16.png +0 -0
  47. package/staging_area/desktop/resume web/dist/assets/images/grid/2.png +0 -0
  48. package/staging_area/desktop/resume web/dist/assets/images/grid/3.png +0 -0
  49. package/staging_area/desktop/resume web/dist/assets/images/grid/4.png +0 -0
  50. package/staging_area/desktop/resume web/dist/assets/images/grid/5.png +0 -0
  51. package/staging_area/desktop/resume web/dist/assets/images/grid/6.png +0 -0
  52. package/staging_area/desktop/resume web/dist/assets/images/grid/7.png +0 -0
  53. package/staging_area/desktop/resume web/dist/assets/images/grid/8.png +0 -0
  54. package/staging_area/desktop/resume web/dist/assets/images/grid/9.png +0 -0
  55. package/staging_area/desktop/resume web/dist/assets/images/home-avatar.png +0 -0
  56. package/staging_area/desktop/resume web/dist/assets/images/kali-icon.png +0 -0
  57. package/staging_area/desktop/resume web/dist/assets/images/kali-logo.png +0 -0
  58. package/staging_area/desktop/resume web/dist/assets/images/logo--.png +0 -0
  59. package/staging_area/desktop/resume web/dist/assets/images/logo-icon.png +0 -0
  60. package/staging_area/desktop/resume web/dist/assets/images/logo.png +0 -0
  61. package/staging_area/desktop/resume web/dist/assets/images/logo.svg +23 -0
  62. package/staging_area/desktop/resume web/dist/assets/images/og-image.png +0 -0
  63. package/staging_area/desktop/resume web/dist/assets/images/portfolio-bg-new.png +0 -0
  64. package/staging_area/desktop/resume web/dist/assets/images/profilecard cover video.mp4 +0 -0
  65. package/staging_area/desktop/resume web/dist/assets/images/project-1.png +0 -0
  66. package/staging_area/desktop/resume web/dist/assets/images/project-2.png +0 -0
  67. package/staging_area/desktop/resume web/dist/assets/images/promo-banner.png +0 -0
  68. package/staging_area/desktop/resume web/dist/assets/images/resume-preview.svg +65 -0
  69. package/staging_area/desktop/resume web/dist/assets/images/simulator-bg.png +0 -0
  70. package/staging_area/desktop/resume web/dist/assets/images/site-bg.png +0 -0
  71. package/staging_area/desktop/resume web/dist/assets/images/smooth-bg.png +0 -0
  72. package/staging_area/desktop/resume web/dist/assets/images/social-card.png +0 -0
  73. package/staging_area/desktop/resume web/dist/assets/images/status-v1.png +0 -0
  74. package/staging_area/desktop/resume web/dist/assets/images/status-v2.png +0 -0
  75. package/staging_area/desktop/resume web/dist/assets/images/status-v3.png +0 -0
  76. package/staging_area/desktop/resume web/dist/assets/images/timeline-code.png +0 -0
  77. package/staging_area/desktop/resume web/dist/assets/images/timeline-edu.png +0 -0
  78. package/staging_area/desktop/resume web/dist/assets/images/timeline-exp.png +0 -0
  79. package/staging_area/desktop/resume web/dist/assets/index-CBjHCN3v.css +1 -0
  80. package/staging_area/desktop/resume web/dist/assets/index-CRxB_GjQ.js +1 -0
  81. package/staging_area/desktop/resume web/dist/assets/js/script.js +184 -0
  82. package/staging_area/desktop/resume web/dist/assets/main-CgEgbzKB.css +1 -0
  83. package/staging_area/desktop/resume web/dist/assets/main-DoBlDLsb.js +366 -0
  84. package/staging_area/desktop/resume web/dist/assets/os-B_E4AY-V.css +1 -0
  85. package/staging_area/desktop/resume web/dist/assets/os-Bq4xD0id.js +46 -0
  86. package/staging_area/desktop/resume web/dist/assets/pdf-CxPl5vKc.js +211 -0
  87. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615599147_DM_GTU_Study_Material_e-Notes_Unit-1.pdf +0 -0
  88. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615618735_Practical-10.pdf +0 -0
  89. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615618963_Preactical-5.pdf +0 -0
  90. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619156_Precatical-2.pdf +0 -0
  91. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619285_Precatical-3.pdf +0 -0
  92. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619392_Precatical-4.pdf +0 -0
  93. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619488_Precatical-8.pdf +0 -0
  94. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619569_Prectical-1.pdf +0 -0
  95. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619648_Prectical-6.pdf +0 -0
  96. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619791_prectical-7.pdf +0 -0
  97. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615619908_Practical-9.pdf +0 -0
  98. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615648322_4331603_-_database_management__labmanual_.pdf +0 -0
  99. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615648489_4631603-DM__ASSIEMENT_.pdf +0 -0
  100. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615648563_micro_project_list_sem_3.pdf +0 -0
  101. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615675037_4300002.pdf +0 -0
  102. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615675252_4311601.pdf +0 -0
  103. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615675450_4311602__1_.pdf +0 -0
  104. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615675557_4300001__maths.pdf +0 -0
  105. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615684225_data_structure_with_python_sem-3___mid-1.pdf +10 -1689
  106. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615684451_database_management_sem_3_mid_1.pdf +6 -2332
  107. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615684614_FOSD_sem_3_mid_1.pdf +4 -1848
  108. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615684759_linux_os_sem-3__mid-1.pdf +3 -1675
  109. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615700452_DM_sem_3___mid_2___diplomaitmorbi.pdf +3 -2269
  110. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615700607_DSWP_sem_3___mid_2___diplomaitmorbi.pdf +6 -2052
  111. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615700750_Sem_3___mid_2___FOSD__-diplomaitmorbi.pdf +3 -1539
  112. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615700931_sem_3___mid_2_Linux_OD_-_diplomaitmorbi.pdf +7 -1493
  113. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615719950_FOSD_Lab_Manual.pdf +0 -0
  114. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615720082_FOSD_4331604__MICRO_PROJECT_LIST.docx +0 -0
  115. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615745886_4331602-LOS__lab_manual_.pdf +0 -0
  116. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615746174_4331602-LOS-lab_manual.pdf +0 -0
  117. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615746541_linuxcommands.pdf +0 -0
  118. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615751586_4331602_OS_GTU_Chap-1.pdf +0 -0
  119. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615760809_Practical-1.pptx +0 -0
  120. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615760986_Practical-4.pptx +0 -0
  121. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615761108_Practical-5.pptx +0 -0
  122. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615829373_FOML_4341603__-Lab_manual.pdf +0 -0
  123. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615829493_FOML-Assignement-SEM-4.docx +0 -0
  124. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615842311_4341602-OOPJ-Assignments.docx +0 -0
  125. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615842837_4341602-OOPJ-Lab_Manual.pdf +0 -0
  126. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615842866_JAVA_Micro_projectList.pdf +0 -0
  127. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615842942_OOPJ_4341602_-IMP_question_bank-SEM-4.docx.pdf +0 -0
  128. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615843027_OOPJ_4341602syllabus.pdf +0 -0
  129. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615884484_4341604-WDPHP-LM.pdf +0 -0
  130. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771615898911_LECD-IT-Student_List-SEM-4-S25.pdf +0 -0
  131. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616070919_ops.png +0 -0
  132. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616421057_4361601_Sem_6_Lab_Manual.pdf +0 -0
  133. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616421192_Cyber_Security_4361601.pdf +0 -0
  134. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616421247_436161_Cyber_Security-Micro_Project-SEM-6_Final.doc +0 -0
  135. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616460753_4361603-FBC-LM.pdf +0 -0
  136. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616468911_SD_Report_writing_format.docx +0 -0
  137. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616475903_WhatsApp_Image_2025-12-22_at_10.34.28_AM.jpeg +0 -0
  138. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616491976_YUVA_WEEK-2026_REGISTRATION_NOTICE___RULES.pdf +0 -0
  139. package/staging_area/desktop/resume web/dist/assets/explorer/thispc/1771616499647_DDCET-2026_Key_Dates.pdf +0 -0
  140. package/staging_area/desktop/resume web/dist/assets/file-icons/java.png +0 -0
  141. package/staging_area/desktop/resume web/dist/assets/file-icons/python.png +0 -0
  142. package/staging_area/desktop/resume web/dist/assets/firebase-B_lZQArn.js +0 -18
  143. package/staging_area/desktop/resume web/dist/assets/images/1767528834957_screenshot_2026_01_04_174340.png +0 -0
  144. package/staging_area/desktop/resume web/dist/assets/images/1767529008170_screenshot_2026_01_04_174340.png +0 -0
  145. package/staging_area/desktop/resume web/dist/assets/images/1767529381960_screenshot_2026_01_04_174340.png +0 -0
  146. package/staging_area/desktop/resume web/dist/assets/images/1767530228238_screenshot_2026_01_04_175337.png +0 -0
  147. package/staging_area/desktop/resume web/dist/assets/images/1767530338616_screenshot_2026_01_04_174340.png +0 -0
@@ -1,18 +0,0 @@
1
- const xa=()=>{};var Es={};const Pr={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};const f=function(n,e){if(!n)throw st(e)},st=function(n){return new Error("Firebase Database ("+Pr.SDK_VERSION+") INTERNAL ASSERT FAILED: "+n)};const Or=function(n){const e=[];let t=0;for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&i+1<n.length&&(n.charCodeAt(i+1)&64512)===56320?(s=65536+((s&1023)<<10)+(n.charCodeAt(++i)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},La=function(n){const e=[];let t=0,i=0;for(;t<n.length;){const s=n[t++];if(s<128)e[i++]=String.fromCharCode(s);else if(s>191&&s<224){const r=n[t++];e[i++]=String.fromCharCode((s&31)<<6|r&63)}else if(s>239&&s<365){const r=n[t++],o=n[t++],a=n[t++],c=((s&7)<<18|(r&63)<<12|(o&63)<<6|a&63)-65536;e[i++]=String.fromCharCode(55296+(c>>10)),e[i++]=String.fromCharCode(56320+(c&1023))}else{const r=n[t++],o=n[t++];e[i++]=String.fromCharCode((s&15)<<12|(r&63)<<6|o&63)}}return e.join("")},ki={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,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();const t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let s=0;s<n.length;s+=3){const r=n[s],o=s+1<n.length,a=o?n[s+1]:0,c=s+2<n.length,l=c?n[s+2]:0,d=r>>2,h=(r&3)<<4|a>>4;let u=(a&15)<<2|l>>6,p=l&63;c||(p=64,o||(u=64)),i.push(t[d],t[h],t[u],t[p])}return i.join("")},encodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(n):this.encodeByteArray(Or(n),e)},decodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(n):La(this.decodeStringToByteArray(n,e))},decodeStringToByteArray(n,e){this.init_();const t=e?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let s=0;s<n.length;){const r=t[n.charAt(s++)],a=s<n.length?t[n.charAt(s)]:0;++s;const l=s<n.length?t[n.charAt(s)]:64;++s;const h=s<n.length?t[n.charAt(s)]:64;if(++s,r==null||a==null||l==null||h==null)throw new Fa;const u=r<<2|a>>4;if(i.push(u),l!==64){const p=a<<4&240|l>>2;if(i.push(p),h!==64){const _=l<<6&192|h;i.push(_)}}}return i},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 Fa extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const Dr=function(n){const e=Or(n);return ki.encodeByteArray(e,!0)},tn=function(n){return Dr(n).replace(/\./g,"")},nn=function(n){try{return ki.decodeString(n,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function Ua(n){return Mr(void 0,n)}function Mr(n,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const t=e;return new Date(t.getTime());case Object:n===void 0&&(n={});break;case Array:n=[];break;default:return e}for(const t in e)!e.hasOwnProperty(t)||!Wa(t)||(n[t]=Mr(n[t],e[t]));return n}function Wa(n){return n!=="__proto__"}function Ba(){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 Ha=()=>Ba().__FIREBASE_DEFAULTS__,Va=()=>{if(typeof process>"u"||typeof Es>"u")return;const n=Es.__FIREBASE_DEFAULTS__;if(n)return JSON.parse(n)},$a=()=>{if(typeof document>"u")return;let n;try{n=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=n&&nn(n[1]);return e&&JSON.parse(e)},Rn=()=>{try{return xa()||Ha()||Va()||$a()}catch(n){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${n}`);return}},xr=n=>Rn()?.emulatorHosts?.[n],Ga=n=>{const e=xr(n);if(!e)return;const t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const i=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),i]:[e.substring(0,t),i]},Lr=()=>Rn()?.config,Fr=n=>Rn()?.[`_${n}`];class j{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,i)=>{t?this.reject(t):this.resolve(i),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,i))}}}function rt(n){try{return(n.startsWith("http://")||n.startsWith("https://")?new URL(n).hostname:n).endsWith(".cloudworkstations.dev")}catch{return!1}}async function Ur(n){return(await fetch(n,{credentials:"include"})).ok}function za(n,e){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 t={alg:"none",type:"JWT"},i=e||"demo-project",s=n.iat||0,r=n.sub||n.user_id;if(!r)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o={iss:`https://securetoken.google.com/${i}`,aud:i,iat:s,exp:s+3600,auth_time:s,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}},...n};return[tn(JSON.stringify(t)),tn(JSON.stringify(o)),""].join(".")}const mt={};function ja(){const n={prod:[],emulator:[]};for(const e of Object.keys(mt))mt[e]?n.emulator.push(e):n.prod.push(e);return n}function qa(n){let e=document.getElementById(n),t=!1;return e||(e=document.createElement("div"),e.setAttribute("id",n),t=!0),{created:t,element:e}}let ws=!1;function Wr(n,e){if(typeof window>"u"||typeof document>"u"||!rt(window.location.host)||mt[n]===e||mt[n]||ws)return;mt[n]=e;function t(u){return`__firebase__banner__${u}`}const i="__firebase__banner",r=ja().prod.length>0;function o(){const u=document.getElementById(i);u&&u.remove()}function a(u){u.style.display="flex",u.style.background="#7faaf0",u.style.position="fixed",u.style.bottom="5px",u.style.left="5px",u.style.padding=".5em",u.style.borderRadius="5px",u.style.alignItems="center"}function c(u,p){u.setAttribute("width","24"),u.setAttribute("id",p),u.setAttribute("height","24"),u.setAttribute("viewBox","0 0 24 24"),u.setAttribute("fill","none"),u.style.marginLeft="-6px"}function l(){const u=document.createElement("span");return u.style.cursor="pointer",u.style.marginLeft="16px",u.style.fontSize="24px",u.innerHTML=" &times;",u.onclick=()=>{ws=!0,o()},u}function d(u,p){u.setAttribute("id",p),u.innerText="Learn more",u.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",u.setAttribute("target","__blank"),u.style.paddingLeft="5px",u.style.textDecoration="underline"}function h(){const u=qa(i),p=t("text"),_=document.getElementById(p)||document.createElement("span"),E=t("learnmore"),A=document.getElementById(E)||document.createElement("a"),H=t("preprendIcon"),z=document.getElementById(H)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(u.created){const ke=u.element;a(ke),d(A,E);const jn=l();c(z,H),ke.append(z,_,A,jn),document.body.appendChild(ke)}r?(_.innerText="Preview backend disconnected.",z.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>`):(z.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>`,_.innerText="Preview backend running in this workspace."),_.setAttribute("id",p)}document.readyState==="loading"?window.addEventListener("DOMContentLoaded",h):h()}function W(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Ni(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(W())}function Ka(){const n=Rn()?.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 Ya(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Qa(){const n=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof n=="object"&&n.id!==void 0}function Br(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Ja(){const n=W();return n.indexOf("MSIE ")>=0||n.indexOf("Trident/")>=0}function Xa(){return Pr.NODE_ADMIN===!0}function Lp(){return!Ka()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function Za(){try{return typeof indexedDB=="object"}catch{return!1}}function ec(){return new Promise((n,e)=>{try{let t=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),t||self.indexedDB.deleteDatabase(i),n(!0)},s.onupgradeneeded=()=>{t=!1},s.onerror=()=>{e(s.error?.message||"")}}catch(t){e(t)}})}const tc="FirebaseError";class Re extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name=tc,Object.setPrototypeOf(this,Re.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,xt.prototype.create)}}class xt{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,r=this.errors[e],o=r?nc(r,i):"Error",a=`${this.serviceName}: ${o} (${s}).`;return new Re(s,a,i)}}function nc(n,e){return n.replace(ic,(t,i)=>{const s=e[i];return s!=null?String(s):`<${i}?>`})}const ic=/\{\$([^}]+)}/g;function Tt(n){return JSON.parse(n)}function P(n){return JSON.stringify(n)}const Hr=function(n){let e={},t={},i={},s="";try{const r=n.split(".");e=Tt(nn(r[0])||""),t=Tt(nn(r[1])||""),s=r[2],i=t.d||{},delete t.d}catch{}return{header:e,claims:t,data:i,signature:s}},sc=function(n){const e=Hr(n),t=e.claims;return!!t&&typeof t=="object"&&t.hasOwnProperty("iat")},rc=function(n){const e=Hr(n).claims;return typeof e=="object"&&e.admin===!0};function X(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function De(n,e){if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}function sn(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}function rn(n,e,t){const i={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=e.call(t,n[s],s,n));return i}function Me(n,e){if(n===e)return!0;const t=Object.keys(n),i=Object.keys(e);for(const s of t){if(!i.includes(s))return!1;const r=n[s],o=e[s];if(Cs(r)&&Cs(o)){if(!Me(r,o))return!1}else if(r!==o)return!1}for(const s of i)if(!t.includes(s))return!1;return!0}function Cs(n){return n!==null&&typeof n=="object"}function ot(n){const e=[];for(const[t,i]of Object.entries(n))Array.isArray(i)?i.forEach(s=>{e.push(encodeURIComponent(t)+"="+encodeURIComponent(s))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(i));return e.length?"&"+e.join("&"):""}class oc{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const i=this.W_;if(typeof e=="string")for(let h=0;h<16;h++)i[h]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let h=0;h<16;h++)i[h]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let h=16;h<80;h++){const u=i[h-3]^i[h-8]^i[h-14]^i[h-16];i[h]=(u<<1|u>>>31)&4294967295}let s=this.chain_[0],r=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,d;for(let h=0;h<80;h++){h<40?h<20?(l=a^r&(o^a),d=1518500249):(l=r^o^a,d=1859775393):h<60?(l=r&o|a&(r|o),d=2400959708):(l=r^o^a,d=3395469782);const u=(s<<5|s>>>27)+l+c+d+i[h]&4294967295;c=a,a=o,o=(r<<30|r>>>2)&4294967295,r=s,s=u}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+r&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,t){if(e==null)return;t===void 0&&(t=e.length);const i=t-this.blockSize;let s=0;const r=this.buf_;let o=this.inbuf_;for(;s<t;){if(o===0)for(;s<=i;)this.compress_(e,s),s+=this.blockSize;if(typeof e=="string"){for(;s<t;)if(r[o]=e.charCodeAt(s),++o,++s,o===this.blockSize){this.compress_(r),o=0;break}}else for(;s<t;)if(r[o]=e[s],++o,++s,o===this.blockSize){this.compress_(r),o=0;break}}this.inbuf_=o,this.total_+=t}digest(){const e=[];let t=this.total_*8;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let s=this.blockSize-1;s>=56;s--)this.buf_[s]=t&255,t/=256;this.compress_(this.buf_);let i=0;for(let s=0;s<5;s++)for(let r=24;r>=0;r-=8)e[i]=this.chain_[s]>>r&255,++i;return e}}function ac(n,e){const t=new cc(n,e);return t.subscribe.bind(t)}class cc{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(i=>{this.error(i)})}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,i){let s;if(e===void 0&&t===void 0&&i===void 0)throw new Error("Missing Observer.");lc(e,["next","error","complete"])?s=e:s={next:e,error:t,complete:i},s.next===void 0&&(s.next=qn),s.error===void 0&&(s.error=qn),s.complete===void 0&&(s.complete=qn);const r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?s.error(this.finalError):s.complete()}catch{}}),this.observers.push(s),r}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{t(this.observers[e])}catch(i){typeof console<"u"&&console.error&&console.error(i)}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function lc(n,e){if(typeof n!="object"||n===null)return!1;for(const t of e)if(t in n&&typeof n[t]=="function")return!0;return!1}function qn(){}function Qe(n,e){return`${n} failed: ${e} argument `}const hc=function(n){const e=[];let t=0;for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s>=55296&&s<=56319){const r=s-55296;i++,f(i<n.length,"Surrogate pair missing trail surrogate.");const o=n.charCodeAt(i)-56320;s=65536+(r<<10)+o}s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):s<65536?(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},kn=function(n){let e=0;for(let t=0;t<n.length;t++){const i=n.charCodeAt(t);i<128?e++:i<2048?e+=2:i>=55296&&i<=56319?(e+=4,t++):e+=3}return e};function L(n){return n&&n._delegate?n._delegate:n}class xe{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const Ne="[DEFAULT]";class uc{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const i=new j;if(this.instancesDeferred.set(t,i),this.isInitialized(t)||this.shouldAutoInitialize())try{const s=this.getOrInitializeService({instanceIdentifier:t});s&&i.resolve(s)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier),i=e?.optional??!1;if(this.isInitialized(t)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:t})}catch(s){if(i)return null;throw s}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(fc(e))try{this.getOrInitializeService({instanceIdentifier:Ne})}catch{}for(const[t,i]of this.instancesDeferred.entries()){const s=this.normalizeInstanceIdentifier(t);try{const r=this.getOrInitializeService({instanceIdentifier:s});i.resolve(r)}catch{}}}}clearInstance(e=Ne){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=Ne){return this.instances.has(e)}getOptions(e=Ne){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,i=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(i))throw Error(`${this.name}(${i}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:i,options:t});for(const[r,o]of this.instancesDeferred.entries()){const a=this.normalizeInstanceIdentifier(r);i===a&&o.resolve(s)}return s}onInit(e,t){const i=this.normalizeInstanceIdentifier(t),s=this.onInitCallbacks.get(i)??new Set;s.add(e),this.onInitCallbacks.set(i,s);const r=this.instances.get(i);return r&&e(r,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const i=this.onInitCallbacks.get(t);if(i)for(const s of i)try{s(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let i=this.instances.get(e);if(!i&&this.component&&(i=this.component.instanceFactory(this.container,{instanceIdentifier:dc(e),options:t}),this.instances.set(e,i),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(i,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,i)}catch{}return i||null}normalizeInstanceIdentifier(e=Ne){return this.component?this.component.multipleInstances?e:Ne:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function dc(n){return n===Ne?void 0:n}function fc(n){return n.instantiationMode==="EAGER"}class pc{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new uc(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}var T;(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"})(T||(T={}));const _c={debug:T.DEBUG,verbose:T.VERBOSE,info:T.INFO,warn:T.WARN,error:T.ERROR,silent:T.SILENT},gc=T.INFO,mc={[T.DEBUG]:"log",[T.VERBOSE]:"log",[T.INFO]:"info",[T.WARN]:"warn",[T.ERROR]:"error"},yc=(n,e,...t)=>{if(e<n.logLevel)return;const i=new Date().toISOString(),s=mc[e];if(s)console[s](`[${i}] ${n.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class Ai{constructor(e){this.name=e,this._logLevel=gc,this._logHandler=yc,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in T))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?_c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,T.DEBUG,...e),this._logHandler(this,T.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,T.VERBOSE,...e),this._logHandler(this,T.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,T.INFO,...e),this._logHandler(this,T.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,T.WARN,...e),this._logHandler(this,T.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,T.ERROR,...e),this._logHandler(this,T.ERROR,...e)}}const vc=(n,e)=>e.some(t=>n instanceof t);let Ts,Ss;function Ic(){return Ts||(Ts=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ec(){return Ss||(Ss=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Vr=new WeakMap,ai=new WeakMap,$r=new WeakMap,Kn=new WeakMap,Pi=new WeakMap;function wc(n){const e=new Promise((t,i)=>{const s=()=>{n.removeEventListener("success",r),n.removeEventListener("error",o)},r=()=>{t(ge(n.result)),s()},o=()=>{i(n.error),s()};n.addEventListener("success",r),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Vr.set(t,n)}).catch(()=>{}),Pi.set(e,n),e}function Cc(n){if(ai.has(n))return;const e=new Promise((t,i)=>{const s=()=>{n.removeEventListener("complete",r),n.removeEventListener("error",o),n.removeEventListener("abort",o)},r=()=>{t(),s()},o=()=>{i(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",r),n.addEventListener("error",o),n.addEventListener("abort",o)});ai.set(n,e)}let ci={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return ai.get(n);if(e==="objectStoreNames")return n.objectStoreNames||$r.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ge(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function Tc(n){ci=n(ci)}function Sc(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){const i=n.call(Yn(this),e,...t);return $r.set(i,e.sort?e.sort():[e]),ge(i)}:Ec().includes(n)?function(...e){return n.apply(Yn(this),e),ge(Vr.get(this))}:function(...e){return ge(n.apply(Yn(this),e))}}function bc(n){return typeof n=="function"?Sc(n):(n instanceof IDBTransaction&&Cc(n),vc(n,Ic())?new Proxy(n,ci):n)}function ge(n){if(n instanceof IDBRequest)return wc(n);if(Kn.has(n))return Kn.get(n);const e=bc(n);return e!==n&&(Kn.set(n,e),Pi.set(e,n)),e}const Yn=n=>Pi.get(n);function Rc(n,e,{blocked:t,upgrade:i,blocking:s,terminated:r}={}){const o=indexedDB.open(n,e),a=ge(o);return i&&o.addEventListener("upgradeneeded",c=>{i(ge(o.result),c.oldVersion,c.newVersion,ge(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{r&&c.addEventListener("close",()=>r()),s&&c.addEventListener("versionchange",l=>s(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}const kc=["get","getKey","getAll","getAllKeys","count"],Nc=["put","add","delete","clear"],Qn=new Map;function bs(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Qn.get(e))return Qn.get(e);const t=e.replace(/FromIndex$/,""),i=e!==t,s=Nc.includes(t);if(!(t in(i?IDBIndex:IDBObjectStore).prototype)||!(s||kc.includes(t)))return;const r=async function(o,...a){const c=this.transaction(o,s?"readwrite":"readonly");let l=c.store;return i&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return Qn.set(e,r),r}Tc(n=>({...n,get:(e,t,i)=>bs(e,t)||n.get(e,t,i),has:(e,t)=>!!bs(e,t)||n.has(e,t)}));class Ac{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(Pc(t)){const i=t.getImmediate();return`${i.library}/${i.version}`}else return null}).filter(t=>t).join(" ")}}function Pc(n){return n.getComponent()?.type==="VERSION"}const li="@firebase/app",Rs="0.14.6";const oe=new Ai("@firebase/app"),Oc="@firebase/app-compat",Dc="@firebase/analytics-compat",Mc="@firebase/analytics",xc="@firebase/app-check-compat",Lc="@firebase/app-check",Fc="@firebase/auth",Uc="@firebase/auth-compat",Wc="@firebase/database",Bc="@firebase/data-connect",Hc="@firebase/database-compat",Vc="@firebase/functions",$c="@firebase/functions-compat",Gc="@firebase/installations",zc="@firebase/installations-compat",jc="@firebase/messaging",qc="@firebase/messaging-compat",Kc="@firebase/performance",Yc="@firebase/performance-compat",Qc="@firebase/remote-config",Jc="@firebase/remote-config-compat",Xc="@firebase/storage",Zc="@firebase/storage-compat",el="@firebase/firestore",tl="@firebase/ai",nl="@firebase/firestore-compat",il="firebase",sl="12.6.0";const hi="[DEFAULT]",rl={[li]:"fire-core",[Oc]:"fire-core-compat",[Mc]:"fire-analytics",[Dc]:"fire-analytics-compat",[Lc]:"fire-app-check",[xc]:"fire-app-check-compat",[Fc]:"fire-auth",[Uc]:"fire-auth-compat",[Wc]:"fire-rtdb",[Bc]:"fire-data-connect",[Hc]:"fire-rtdb-compat",[Vc]:"fire-fn",[$c]:"fire-fn-compat",[Gc]:"fire-iid",[zc]:"fire-iid-compat",[jc]:"fire-fcm",[qc]:"fire-fcm-compat",[Kc]:"fire-perf",[Yc]:"fire-perf-compat",[Qc]:"fire-rc",[Jc]:"fire-rc-compat",[Xc]:"fire-gcs",[Zc]:"fire-gcs-compat",[el]:"fire-fst",[nl]:"fire-fst-compat",[tl]:"fire-vertex","fire-js":"fire-js",[il]:"fire-js-all"};const on=new Map,ol=new Map,ui=new Map;function ks(n,e){try{n.container.addComponent(e)}catch(t){oe.debug(`Component ${e.name} failed to register with FirebaseApp ${n.name}`,t)}}function Je(n){const e=n.name;if(ui.has(e))return oe.debug(`There were multiple attempts to register component ${e}.`),!1;ui.set(e,n);for(const t of on.values())ks(t,n);for(const t of ol.values())ks(t,n);return!0}function Oi(n,e){const t=n.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),n.container.getProvider(e)}function $(n){return n==null?!1:n.settings!==void 0}const al={"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."},me=new xt("app","Firebase",al);class cl{constructor(e,t,i){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=i,this.container.addComponent(new xe("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}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(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw me.create("app-deleted",{appName:this._name})}}const at=sl;function ll(n,e={}){let t=n;typeof e!="object"&&(e={name:e});const i={name:hi,automaticDataCollectionEnabled:!0,...e},s=i.name;if(typeof s!="string"||!s)throw me.create("bad-app-name",{appName:String(s)});if(t||(t=Lr()),!t)throw me.create("no-options");const r=on.get(s);if(r){if(Me(t,r.options)&&Me(i,r.config))return r;throw me.create("duplicate-app",{appName:s})}const o=new pc(s);for(const c of ui.values())o.addComponent(c);const a=new cl(t,i,o);return on.set(s,a),a}function Gr(n=hi){const e=on.get(n);if(!e&&n===hi&&Lr())return ll();if(!e)throw me.create("no-app",{appName:n});return e}function ye(n,e,t){let i=rl[n]??n;t&&(i+=`-${t}`);const s=i.match(/\s|\//),r=e.match(/\s|\//);if(s||r){const o=[`Unable to register library "${i}" with version "${e}":`];s&&o.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&r&&o.push("and"),r&&o.push(`version name "${e}" contains illegal characters (whitespace or "/")`),oe.warn(o.join(" "));return}Je(new xe(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}const hl="firebase-heartbeat-database",ul=1,St="firebase-heartbeat-store";let Jn=null;function zr(){return Jn||(Jn=Rc(hl,ul,{upgrade:(n,e)=>{switch(e){case 0:try{n.createObjectStore(St)}catch(t){console.warn(t)}}}}).catch(n=>{throw me.create("idb-open",{originalErrorMessage:n.message})})),Jn}async function dl(n){try{const t=(await zr()).transaction(St),i=await t.objectStore(St).get(jr(n));return await t.done,i}catch(e){if(e instanceof Re)oe.warn(e.message);else{const t=me.create("idb-get",{originalErrorMessage:e?.message});oe.warn(t.message)}}}async function Ns(n,e){try{const i=(await zr()).transaction(St,"readwrite");await i.objectStore(St).put(e,jr(n)),await i.done}catch(t){if(t instanceof Re)oe.warn(t.message);else{const i=me.create("idb-set",{originalErrorMessage:t?.message});oe.warn(i.message)}}}function jr(n){return`${n.name}!${n.options.appId}`}const fl=1024,pl=30;class _l{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new ml(t),this._heartbeatsCachePromise=this._storage.read().then(i=>(this._heartbeatsCache=i,i))}async triggerHeartbeat(){try{const t=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=As();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(s=>s.date===i))return;if(this._heartbeatsCache.heartbeats.push({date:i,agent:t}),this._heartbeatsCache.heartbeats.length>pl){const s=yl(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(s,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){oe.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";const e=As(),{heartbeatsToSend:t,unsentEntries:i}=gl(this._heartbeatsCache.heartbeats),s=tn(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(e){return oe.warn(e),""}}}function As(){return new Date().toISOString().substring(0,10)}function gl(n,e=fl){const t=[];let i=n.slice();for(const s of n){const r=t.find(o=>o.agent===s.agent);if(r){if(r.dates.push(s.date),Ps(t)>e){r.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Ps(t)>e){t.pop();break}i=i.slice(1)}return{heartbeatsToSend:t,unsentEntries:i}}class ml{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Za()?ec().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const t=await dl(this.app);return t?.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){const i=await this.read();return Ns(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){const i=await this.read();return Ns(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function Ps(n){return tn(JSON.stringify({version:2,heartbeats:n})).length}function yl(n){if(n.length===0)return-1;let e=0,t=n[0].date;for(let i=1;i<n.length;i++)n[i].date<t&&(t=n[i].date,e=i);return e}function vl(n){Je(new xe("platform-logger",e=>new Ac(e),"PRIVATE")),Je(new xe("heartbeat",e=>new _l(e),"PRIVATE")),ye(li,Rs,n),ye(li,Rs,"esm2020"),ye("fire-js","")}vl("");var Il="firebase",El="12.7.0";ye(Il,El,"app");var Os={};const Ds="@firebase/database",Ms="1.1.0";let qr="";function wl(n){qr=n}class Cl{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){t==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),P(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return t==null?null:Tt(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Tl{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){t==null?delete this.cache_[e]:this.cache_[e]=t}get(e){return X(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const Kr=function(n){try{if(typeof window<"u"&&typeof window[n]<"u"){const e=window[n];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new Cl(e)}}catch{}return new Tl},Pe=Kr("localStorage"),Sl=Kr("sessionStorage");const ze=new Ai("@firebase/database"),Yr=(function(){let n=1;return function(){return n++}})(),Qr=function(n){const e=hc(n),t=new oc;t.update(e);const i=t.digest();return ki.encodeByteArray(i)},Lt=function(...n){let e="";for(let t=0;t<n.length;t++){const i=n[t];Array.isArray(i)||i&&typeof i=="object"&&typeof i.length=="number"?e+=Lt.apply(null,i):typeof i=="object"?e+=P(i):e+=i,e+=" "}return e};let yt=null,xs=!0;const bl=function(n,e){f(!0,"Can't turn on custom loggers persistently."),ze.logLevel=T.VERBOSE,yt=ze.log.bind(ze)},M=function(...n){if(xs===!0&&(xs=!1,yt===null&&Sl.get("logging_enabled")===!0&&bl()),yt){const e=Lt.apply(null,n);yt(e)}},Ft=function(n){return function(...e){M(n,...e)}},di=function(...n){const e="FIREBASE INTERNAL ERROR: "+Lt(...n);ze.error(e)},ae=function(...n){const e=`FIREBASE FATAL ERROR: ${Lt(...n)}`;throw ze.error(e),new Error(e)},U=function(...n){const e="FIREBASE WARNING: "+Lt(...n);ze.warn(e)},Rl=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&U("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Nn=function(n){return typeof n=="number"&&(n!==n||n===Number.POSITIVE_INFINITY||n===Number.NEGATIVE_INFINITY)},kl=function(n){if(document.readyState==="complete")n();else{let e=!1;const t=function(){if(!document.body){setTimeout(t,Math.floor(10));return}e||(e=!0,n())};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&t()}),window.attachEvent("onload",t))}},Xe="[MIN_NAME]",Le="[MAX_NAME]",Be=function(n,e){if(n===e)return 0;if(n===Xe||e===Le)return-1;if(e===Xe||n===Le)return 1;{const t=Ls(n),i=Ls(e);return t!==null?i!==null?t-i===0?n.length-e.length:t-i:-1:i!==null?1:n<e?-1:1}},Nl=function(n,e){return n===e?0:n<e?-1:1},ft=function(n,e){if(e&&n in e)return e[n];throw new Error("Missing required key ("+n+") in object: "+P(e))},Di=function(n){if(typeof n!="object"||n===null)return P(n);const e=[];for(const i in n)e.push(i);e.sort();let t="{";for(let i=0;i<e.length;i++)i!==0&&(t+=","),t+=P(e[i]),t+=":",t+=Di(n[e[i]]);return t+="}",t},Jr=function(n,e){const t=n.length;if(t<=e)return[n];const i=[];for(let s=0;s<t;s+=e)s+e>t?i.push(n.substring(s,t)):i.push(n.substring(s,s+e));return i};function x(n,e){for(const t in n)n.hasOwnProperty(t)&&e(t,n[t])}const Xr=function(n){f(!Nn(n),"Invalid JSON number");const e=11,t=52,i=(1<<e-1)-1;let s,r,o,a,c;n===0?(r=0,o=0,s=1/n===-1/0?1:0):(s=n<0,n=Math.abs(n),n>=Math.pow(2,1-i)?(a=Math.min(Math.floor(Math.log(n)/Math.LN2),i),r=a+i,o=Math.round(n*Math.pow(2,t-a)-Math.pow(2,t))):(r=0,o=Math.round(n/Math.pow(2,1-i-t))));const l=[];for(c=t;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);for(c=e;c;c-=1)l.push(r%2?1:0),r=Math.floor(r/2);l.push(s?1:0),l.reverse();const d=l.join("");let h="";for(c=0;c<64;c+=8){let u=parseInt(d.substr(c,8),2).toString(16);u.length===1&&(u="0"+u),h=h+u}return h.toLowerCase()},Al=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Pl=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function Ol(n,e){let t="Unknown Error";n==="too_big"?t="The data requested exceeds the maximum size that can be accessed with a single request.":n==="permission_denied"?t="Client doesn't have permission to access the desired data.":n==="unavailable"&&(t="The service is unavailable");const i=new Error(n+" at "+e._path.toString()+": "+t);return i.code=n.toUpperCase(),i}const Dl=new RegExp("^-?(0*)\\d{1,10}$"),Ml=-2147483648,xl=2147483647,Ls=function(n){if(Dl.test(n)){const e=Number(n);if(e>=Ml&&e<=xl)return e}return null},ct=function(n){try{n()}catch(e){setTimeout(()=>{const t=e.stack||"";throw U("Exception was thrown by user callback.",t),e},Math.floor(0))}},Ll=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},vt=function(n,e){const t=setTimeout(n,e);return typeof t=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(t):typeof t=="object"&&t.unref&&t.unref(),t};class Fl{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,$(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(i=>this.appCheck=i)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((t,i)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,i):t(null)},0)})}addTokenChangeListener(e){this.appCheckProvider?.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){U(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}class Ul{constructor(e,t,i){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=i,this.auth_=null,this.auth_=i.getImmediate({optional:!0}),this.auth_||i.onInit(s=>this.auth_=s)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(t=>t&&t.code==="auth/token-not-initialized"?(M("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(t)):new Promise((t,i)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,i):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',U(e)}}class Qt{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Qt.OWNER="owner";const Mi="5",Zr="v",eo="s",to="r",no="f",io=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,so="ls",ro="p",fi="ac",oo="websocket",ao="long_polling";class co{constructor(e,t,i,s,r=!1,o="",a=!1,c=!1,l=null){this.secure=t,this.namespace=i,this.webSocketOnly=s,this.nodeAdmin=r,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Pe.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&Pe.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function Wl(n){return n.host!==n.internalHost||n.isCustomHost()||n.includeNamespaceInQueryParams}function lo(n,e,t){f(typeof e=="string","typeof type must == string"),f(typeof t=="object","typeof params must == object");let i;if(e===oo)i=(n.secure?"wss://":"ws://")+n.internalHost+"/.ws?";else if(e===ao)i=(n.secure?"https://":"http://")+n.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);Wl(n)&&(t.ns=n.namespace);const s=[];return x(t,(r,o)=>{s.push(r+"="+o)}),i+s.join("&")}class Bl{constructor(){this.counters_={}}incrementCounter(e,t=1){X(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return Ua(this.counters_)}}const Xn={},Zn={};function xi(n){const e=n.toString();return Xn[e]||(Xn[e]=new Bl),Xn[e]}function Hl(n,e){const t=n.toString();return Zn[t]||(Zn[t]=e()),Zn[t]}class Vl{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const i=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let s=0;s<i.length;++s)i[s]&&ct(()=>{this.onMessage_(i[s])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const Fs="start",$l="close",Gl="pLPCommand",zl="pRTLPCB",ho="id",uo="pw",fo="ser",jl="cb",ql="seg",Kl="ts",Yl="d",Ql="dframe",po=1870,_o=30,Jl=po-_o,Xl=25e3,Zl=3e4;class Ge{constructor(e,t,i,s,r,o,a){this.connId=e,this.repoInfo=t,this.applicationId=i,this.appCheckToken=s,this.authToken=r,this.transportSessionId=o,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ft(e),this.stats_=xi(t),this.urlFn=c=>(this.appCheckToken&&(c[fi]=this.appCheckToken),lo(t,ao,c))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Vl(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Zl)),kl(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Li((...r)=>{const[o,a,c,l,d]=r;if(this.incrementIncomingBytes_(r),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===Fs)this.id=a,this.password=c;else if(o===$l)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...r)=>{const[o,a]=r;this.incrementIncomingBytes_(r),this.myPacketOrderer.handleResponse(o,a)},()=>{this.onClosed_()},this.urlFn);const i={};i[Fs]="t",i[fo]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(i[jl]=this.scriptTagHolder.uniqueCallbackIdentifier),i[Zr]=Mi,this.transportSessionId&&(i[eo]=this.transportSessionId),this.lastSessionId&&(i[so]=this.lastSessionId),this.applicationId&&(i[ro]=this.applicationId),this.appCheckToken&&(i[fi]=this.appCheckToken),typeof location<"u"&&location.hostname&&io.test(location.hostname)&&(i[to]=no);const s=this.urlFn(i);this.log_("Connecting via long-poll to "+s),this.scriptTagHolder.addTag(s,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Ge.forceAllow_=!0}static forceDisallow(){Ge.forceDisallow_=!0}static isAvailable(){return Ge.forceAllow_?!0:!Ge.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!Al()&&!Pl()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=P(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const i=Dr(t),s=Jr(i,Jl);for(let r=0;r<s.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,s.length,s[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const i={};i[Ql]="t",i[ho]=e,i[uo]=t,this.myDisconnFrame.src=this.urlFn(i),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=P(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Li{constructor(e,t,i,s){this.onDisconnect=i,this.urlFn=s,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Yr(),window[Gl+this.uniqueCallbackIdentifier]=e,window[zl+this.uniqueCallbackIdentifier]=t,this.myIFrame=Li.createIFrame_();let r="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(r='<script>document.domain="'+document.domain+'";<\/script>');const o="<html><body>"+r+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(a){M("frame writing exception"),a.stack&&M(a.stack),M(a)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||M("No IE domain setting required")}catch{const i=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+i+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[ho]=this.myID,e[uo]=this.myPW,e[fo]=this.currentSerial;let t=this.urlFn(e),i="",s=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+_o+i.length<=po;){const o=this.pendingSegs.shift();i=i+"&"+ql+s+"="+o.seg+"&"+Kl+s+"="+o.ts+"&"+Yl+s+"="+o.d,s++}return t=t+i,this.addLongPollTag_(t,this.currentSerial),!0}else return!1}enqueueSegment(e,t,i){this.pendingSegs.push({seg:e,ts:t,d:i}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const i=()=>{this.outstandingRequests.delete(t),this.newRequest_()},s=setTimeout(i,Math.floor(Xl)),r=()=>{clearTimeout(s),i()};this.addTag(e,r)}addTag(e,t){setTimeout(()=>{try{if(!this.sendNewPolls)return;const i=this.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){const s=i.readyState;(!s||s==="loaded"||s==="complete")&&(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=()=>{M("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(i)}catch{}},Math.floor(1))}}const eh=16384,th=45e3;let an=null;typeof MozWebSocket<"u"?an=MozWebSocket:typeof WebSocket<"u"&&(an=WebSocket);class q{constructor(e,t,i,s,r,o,a){this.connId=e,this.applicationId=i,this.appCheckToken=s,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ft(this.connId),this.stats_=xi(t),this.connURL=q.connectionURL_(t,o,a,s,i),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,i,s,r){const o={};return o[Zr]=Mi,typeof location<"u"&&location.hostname&&io.test(location.hostname)&&(o[to]=no),t&&(o[eo]=t),i&&(o[so]=i),s&&(o[fi]=s),r&&(o[ro]=r),lo(e,oo,o)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Pe.set("previous_websocket_failure",!0);try{let i;Xa(),this.mySock=new an(this.connURL,[],i)}catch(i){this.log_("Error instantiating WebSocket.");const s=i.message||i.data;s&&this.log_(s),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=i=>{this.handleIncomingFrame(i)},this.mySock.onerror=i=>{this.log_("WebSocket error. Closing connection.");const s=i.message||i.data;s&&this.log_(s),this.onClosed_()}}start(){}static forceDisallow(){q.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,i=navigator.userAgent.match(t);i&&i.length>1&&parseFloat(i[1])<4.4&&(e=!0)}return!e&&an!==null&&!q.forceDisallow_}static previouslyFailed(){return Pe.isInMemoryStorage||Pe.get("previous_websocket_failure")===!0}markConnectionHealthy(){Pe.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const t=this.frames.join("");this.frames=null;const i=Tt(t);this.onMessage(i)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(this.frames===null,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(t);else{const i=this.extractFrameCount_(t);i!==null&&this.appendFrame_(i)}}send(e){this.resetKeepAlive();const t=P(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const i=Jr(t,eh);i.length>1&&this.sendString_(String(i.length));for(let s=0;s<i.length;s++)this.sendString_(i[s])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(th))}sendString_(e){try{this.mySock.send(e)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}q.responsesRequiredToBeHealthy=2;q.healthyTimeout=3e4;class bt{static get ALL_TRANSPORTS(){return[Ge,q]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){const t=q&&q.isAvailable();let i=t&&!q.previouslyFailed();if(e.webSocketOnly&&(t||U("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),i=!0),i)this.transports_=[q];else{const s=this.transports_=[];for(const r of bt.ALL_TRANSPORTS)r&&r.isAvailable()&&s.push(r);bt.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}bt.globalTransportInitialized_=!1;const nh=6e4,ih=5e3,sh=10*1024,rh=100*1024,ei="t",Us="d",oh="s",Ws="r",ah="e",Bs="o",Hs="a",Vs="n",$s="p",ch="h";class lh{constructor(e,t,i,s,r,o,a,c,l,d){this.id=e,this.repoInfo_=t,this.applicationId_=i,this.appCheckToken_=s,this.authToken_=r,this.onMessage_=o,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=d,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Ft("c:"+this.id+":"),this.transportManager_=new bt(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),i=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,i)},Math.floor(0));const s=e.healthyTimeout||0;s>0&&(this.healthyTimeout_=vt(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>rh?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>sh?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(s)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(ei in e){const t=e[ei];t===Hs?this.upgradeIfSecondaryHealthy_():t===Ws?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):t===Bs&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=ft("t",e),i=ft("d",e);if(t==="c")this.onSecondaryControl_(i);else if(t==="d")this.pendingDataMessages.push(i);else throw new Error("Unknown protocol layer: "+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:$s,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:Hs,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Vs,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=ft("t",e),i=ft("d",e);t==="c"?this.onControl_(i):t==="d"&&this.onDataMessage_(i)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=ft(ei,e);if(Us in e){const i=e[Us];if(t===ch){const s={...i};this.repoInfo_.isUsingEmulator&&(s.h=this.repoInfo_.host),this.onHandshake_(s)}else if(t===Vs){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let s=0;s<this.pendingDataMessages.length;++s)this.onDataMessage_(this.pendingDataMessages[s]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===oh?this.onConnectionShutdown_(i):t===Ws?this.onReset_(i):t===ah?di("Server Error: "+i):t===Bs?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):di("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,i=e.v,s=e.h;this.sessionId=e.s,this.repoInfo_.host=s,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),Mi!==i&&U("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),i=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,i),vt(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(nh))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):vt(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(ih))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:$s,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(Pe.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class go{put(e,t,i,s){}merge(e,t,i,s){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,i){}onDisconnectMerge(e,t,i){}onDisconnectCancel(e,t){}reportStats(e){}}class mo{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const i=[...this.listeners_[e]];for(let s=0;s<i.length;s++)i[s].callback.apply(i[s].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let r=0;r<s.length;r++)if(s[r].callback===t&&(!i||i===s[r].context)){s.splice(r,1);return}}validateEventType_(e){f(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class cn extends mo{static getInstance(){return new cn}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!Ni()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return f(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}const Gs=32,zs=768;class C{constructor(e,t){if(t===void 0){this.pieces_=e.split("/");let i=0;for(let s=0;s<this.pieces_.length;s++)this.pieces_[s].length>0&&(this.pieces_[i]=this.pieces_[s],i++);this.pieces_.length=i,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)this.pieces_[t]!==""&&(e+="/"+this.pieces_[t]);return e||"/"}}function w(){return new C("")}function y(n){return n.pieceNum_>=n.pieces_.length?null:n.pieces_[n.pieceNum_]}function we(n){return n.pieces_.length-n.pieceNum_}function S(n){let e=n.pieceNum_;return e<n.pieces_.length&&e++,new C(n.pieces_,e)}function Fi(n){return n.pieceNum_<n.pieces_.length?n.pieces_[n.pieces_.length-1]:null}function hh(n){let e="";for(let t=n.pieceNum_;t<n.pieces_.length;t++)n.pieces_[t]!==""&&(e+="/"+encodeURIComponent(String(n.pieces_[t])));return e||"/"}function Rt(n,e=0){return n.pieces_.slice(n.pieceNum_+e)}function yo(n){if(n.pieceNum_>=n.pieces_.length)return null;const e=[];for(let t=n.pieceNum_;t<n.pieces_.length-1;t++)e.push(n.pieces_[t]);return new C(e,0)}function N(n,e){const t=[];for(let i=n.pieceNum_;i<n.pieces_.length;i++)t.push(n.pieces_[i]);if(e instanceof C)for(let i=e.pieceNum_;i<e.pieces_.length;i++)t.push(e.pieces_[i]);else{const i=e.split("/");for(let s=0;s<i.length;s++)i[s].length>0&&t.push(i[s])}return new C(t,0)}function v(n){return n.pieceNum_>=n.pieces_.length}function F(n,e){const t=y(n),i=y(e);if(t===null)return e;if(t===i)return F(S(n),S(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+n+")")}function uh(n,e){const t=Rt(n,0),i=Rt(e,0);for(let s=0;s<t.length&&s<i.length;s++){const r=Be(t[s],i[s]);if(r!==0)return r}return t.length===i.length?0:t.length<i.length?-1:1}function Ui(n,e){if(we(n)!==we(e))return!1;for(let t=n.pieceNum_,i=e.pieceNum_;t<=n.pieces_.length;t++,i++)if(n.pieces_[t]!==e.pieces_[i])return!1;return!0}function G(n,e){let t=n.pieceNum_,i=e.pieceNum_;if(we(n)>we(e))return!1;for(;t<n.pieces_.length;){if(n.pieces_[t]!==e.pieces_[i])return!1;++t,++i}return!0}class dh{constructor(e,t){this.errorPrefix_=t,this.parts_=Rt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let i=0;i<this.parts_.length;i++)this.byteLength_+=kn(this.parts_[i]);vo(this)}}function fh(n,e){n.parts_.length>0&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=kn(e),vo(n)}function ph(n){const e=n.parts_.pop();n.byteLength_-=kn(e),n.parts_.length>0&&(n.byteLength_-=1)}function vo(n){if(n.byteLength_>zs)throw new Error(n.errorPrefix_+"has a key path longer than "+zs+" bytes ("+n.byteLength_+").");if(n.parts_.length>Gs)throw new Error(n.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Gs+") or object contains a cycle "+Ae(n))}function Ae(n){return n.parts_.length===0?"":"in property '"+n.parts_.join(".")+"'"}class Wi extends mo{static getInstance(){return new Wi}constructor(){super(["visible"]);let e,t;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(t="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(t="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(t="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{const i=!document[e];i!==this.visible_&&(this.visible_=i,this.trigger("visible",i))},!1)}getInitialEvent(e){return f(e==="visible","Unknown event type: "+e),[this.visible_]}}const pt=1e3,_h=300*1e3,js=30*1e3,gh=1.3,mh=3e4,yh="server_kill",qs=3;class re extends go{constructor(e,t,i,s,r,o,a,c){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=i,this.onConnectStatus_=s,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=c,this.id=re.nextPersistentConnectionId_++,this.log_=Ft("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=pt,this.maxReconnectDelay_=_h,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,c)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Wi.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&cn.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,i){const s=++this.requestNumber_,r={r:s,a:e,b:t};this.log_(P(r)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),i&&(this.requestCBHash_[s]=i)}get(e){this.initConnection_();const t=new j,s={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const a=o.d;o.s==="ok"?t.resolve(a):t.reject(a)}};this.outstandingGets_.push(s),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,i,s){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:s,hashFn:t,query:e,tag:i};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,i=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(i)})}sendListen_(e){const t=e.query,i=t._path.toString(),s=t._queryIdentifier;this.log_("Listen on "+i+" for "+s);const r={p:i},o="q";e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest(o,r,a=>{const c=a.d,l=a.s;re.warnOnListenWarnings_(c,t),(this.listens.get(i)&&this.listens.get(i).get(s))===e&&(this.log_("listen response",a),l!=="ok"&&this.removeListen_(i,s),e.onComplete&&e.onComplete(l,c))})}static warnOnListenWarnings_(e,t){if(e&&typeof e=="object"&&X(e,"w")){const i=De(e,"w");if(Array.isArray(i)&&~i.indexOf("no_index")){const s='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString();U(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${s} at ${r} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&e.length===40||rc(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=js)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=sc(e)?"auth":"gauth",i={cred:e};this.authOverride_===null?i.noauth=!0:typeof this.authOverride_=="object"&&(i.authvar=this.authOverride_),this.sendRequest(t,i,s=>{const r=s.s,o=s.d||"error";this.authToken_===e&&(r==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(r,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const t=e.s,i=e.d||"error";t==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,i)})}unlisten(e,t){const i=e._path.toString(),s=e._queryIdentifier;this.log_("Unlisten called for "+i+" "+s),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,s)&&this.connected_&&this.sendUnlisten_(i,s,e._queryObject,t)}sendUnlisten_(e,t,i,s){this.log_("Unlisten on "+e+" for "+t);const r={p:e},o="n";s&&(r.q=i,r.t=s),this.sendRequest(o,r)}onDisconnectPut(e,t,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,i):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:i})}onDisconnectMerge(e,t,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,i):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:i})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,i,s){const r={p:t,d:i};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,o=>{s&&setTimeout(()=>{s(o.s,o.d)},Math.floor(0))})}put(e,t,i,s){this.putInternal("p",e,t,i,s)}merge(e,t,i,s){this.putInternal("m",e,t,i,s)}putInternal(e,t,i,s,r){this.initConnection_();const o={p:t,d:i};r!==void 0&&(o.h=r),this.outstandingPuts_.push({action:e,request:o,onComplete:s}),this.outstandingPutCount_++;const a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,i=this.outstandingPuts_[e].request,s=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,i,r=>{this.log_(t+" response",r),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),s&&s(r.s,r.d)})}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,i=>{if(i.s!=="ok"){const r=i.d;this.log_("reportStats","Error sending stats: "+r)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+P(e));const t=e.r,i=this.requestCBHash_[t];i&&(delete this.requestCBHash_[t],i(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),e==="d"?this.onDataUpdate_(t.p,t.d,!1,t.t):e==="m"?this.onDataUpdate_(t.p,t.d,!0,t.t):e==="c"?this.onListenRevoked_(t.p,t.q):e==="ac"?this.onAuthRevoked_(t.s,t.d):e==="apc"?this.onAppCheckRevoked_(t.s,t.d):e==="sd"?this.onSecurityDebugPacket_(t):di("Unrecognized action received from server: "+P(e)+`
16
- Are you using the latest client?`)}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=pt,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=pt,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>mh&&(this.reconnectDelay_=pt),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_);let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*gh)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),i=this.onRealtimeDisconnect_.bind(this),s=this.id+":"+re.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,i())},l=function(h){f(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(h)};this.realtime_={close:c,sendRequest:l};const d=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[h,u]=await Promise.all([this.authTokenProvider_.getToken(d),this.appCheckTokenProvider_.getToken(d)]);o?M("getToken() completed but was canceled"):(M("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=u&&u.token,a=new lh(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,i,p=>{U(p+" ("+this.repoInfo_.toString()+")"),this.interrupt(yh)},r))}catch(h){this.log_("Failed to get token: "+h),o||(this.repoInfo_.nodeAdmin&&U(h),c())}}}interrupt(e){M("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){M("Resuming connection for reason: "+e),delete this.interruptReasons_[e],sn(this.interruptReasons_)&&(this.reconnectDelay_=pt,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let i;t?i=t.map(r=>Di(r)).join("$"):i="default";const s=this.removeListen_(e,i);s&&s.onComplete&&s.onComplete("permission_denied")}removeListen_(e,t){const i=new C(e).toString();let s;if(this.listens.has(i)){const r=this.listens.get(i);s=r.get(t),r.delete(t),r.size===0&&this.listens.delete(i)}else s=void 0;return s}onAuthRevoked_(e,t){M("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=qs&&(this.reconnectDelay_=js,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){M("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=qs&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(`
17
- `,`
18
- FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let t="js";e["sdk."+t+"."+qr.replace(/\./g,"-")]=1,Ni()?e["framework.cordova"]=1:Br()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=cn.getInstance().currentlyOnline();return sn(this.interruptReasons_)&&e}}re.nextPersistentConnectionId_=0;re.nextConnectionId_=0;class I{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new I(e,t)}}class An{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const i=new I(Xe,e),s=new I(Xe,t);return this.compare(i,s)!==0}minPost(){return I.MIN}}let qt;class Io extends An{static get __EMPTY_NODE(){return qt}static set __EMPTY_NODE(e){qt=e}compare(e,t){return Be(e.name,t.name)}isDefinedOn(e){throw st("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return I.MIN}maxPost(){return new I(Le,qt)}makePost(e,t){return f(typeof e=="string","KeyIndex indexValue must always be a string."),new I(e,qt)}toString(){return".key"}}const je=new Io;class Kt{constructor(e,t,i,s,r=null){this.isReverse_=s,this.resultGenerator_=r,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(e=e,o=t?i(e.key,t):1,s&&(o*=-1),o<0)this.isReverse_?e=e.left:e=e.right;else if(o===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),this.isReverse_?e=e.right:e=e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),t;if(this.resultGenerator_?t=this.resultGenerator_(e.key,e.value):t={key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class D{constructor(e,t,i,s,r){this.key=e,this.value=t,this.color=i??D.RED,this.left=s??B.EMPTY_NODE,this.right=r??B.EMPTY_NODE}copy(e,t,i,s,r){return new D(e??this.key,t??this.value,i??this.color,s??this.left,r??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}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(e,t,i){let s=this;const r=i(e,s.key);return r<0?s=s.copy(null,null,null,s.left.insert(e,t,i),null):r===0?s=s.copy(null,t,null,null,null):s=s.copy(null,null,null,null,s.right.insert(e,t,i)),s.fixUp_()}removeMin_(){if(this.left.isEmpty())return B.EMPTY_NODE;let e=this;return!e.left.isRed_()&&!e.left.left.isRed_()&&(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let i,s;if(i=this,t(e,i.key)<0)!i.left.isEmpty()&&!i.left.isRed_()&&!i.left.left.isRed_()&&(i=i.moveRedLeft_()),i=i.copy(null,null,null,i.left.remove(e,t),null);else{if(i.left.isRed_()&&(i=i.rotateRight_()),!i.right.isEmpty()&&!i.right.isRed_()&&!i.right.left.isRed_()&&(i=i.moveRedRight_()),t(e,i.key)===0){if(i.right.isEmpty())return B.EMPTY_NODE;s=i.right.min_(),i=i.copy(s.key,s.value,null,null,i.right.removeMin_())}i=i.copy(null,null,null,null,i.right.remove(e,t))}return i.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,D.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,D.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}D.RED=!0;D.BLACK=!1;class vh{copy(e,t,i,s,r){return this}insert(e,t,i){return new D(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class B{constructor(e,t=B.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new B(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,D.BLACK,null,null))}remove(e){return new B(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,D.BLACK,null,null))}get(e){let t,i=this.root_;for(;!i.isEmpty();){if(t=this.comparator_(e,i.key),t===0)return i.value;t<0?i=i.left:t>0&&(i=i.right)}return null}getPredecessorKey(e){let t,i=this.root_,s=null;for(;!i.isEmpty();)if(t=this.comparator_(e,i.key),t===0){if(i.left.isEmpty())return s?s.key:null;for(i=i.left;!i.right.isEmpty();)i=i.right;return i.key}else t<0?i=i.left:t>0&&(s=i,i=i.right);throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Kt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Kt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Kt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Kt(this.root_,null,this.comparator_,!0,e)}}B.EMPTY_NODE=new vh;function Ih(n,e){return Be(n.name,e.name)}function Bi(n,e){return Be(n,e)}let pi;function Eh(n){pi=n}const Eo=function(n){return typeof n=="number"?"number:"+Xr(n):"string:"+n},wo=function(n){if(n.isLeafNode()){const e=n.val();f(typeof e=="string"||typeof e=="number"||typeof e=="object"&&X(e,".sv"),"Priority must be a string or number.")}else f(n===pi||n.isEmpty(),"priority of unexpected type.");f(n===pi||n.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Ks;class O{static set __childrenNodeConstructor(e){Ks=e}static get __childrenNodeConstructor(){return Ks}constructor(e,t=O.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),wo(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new O(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:O.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return v(e)?this:y(e)===".priority"?this.priorityNode_:O.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return e===".priority"?this.updatePriority(t):t.isEmpty()&&e!==".priority"?this:O.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const i=y(e);return i===null?t:t.isEmpty()&&i!==".priority"?this:(f(i!==".priority"||we(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(i,O.__childrenNodeConstructor.EMPTY_NODE.updateChild(S(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+Eo(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",t==="number"?e+=Xr(this.value_):e+=this.value_,this.lazyHash_=Qr(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===O.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof O.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,i=typeof this.value_,s=O.VALUE_TYPE_ORDER.indexOf(t),r=O.VALUE_TYPE_ORDER.indexOf(i);return f(s>=0,"Unknown leaf type: "+t),f(r>=0,"Unknown leaf type: "+i),s===r?i==="object"?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-s}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}else return!1}}O.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Co,To;function wh(n){Co=n}function Ch(n){To=n}class Th extends An{compare(e,t){const i=e.node.getPriority(),s=t.node.getPriority(),r=i.compareTo(s);return r===0?Be(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return I.MIN}maxPost(){return new I(Le,new O("[PRIORITY-POST]",To))}makePost(e,t){const i=Co(e);return new I(t,new O("[PRIORITY-POST]",i))}toString(){return".priority"}}const R=new Th;const Sh=Math.log(2);class bh{constructor(e){const t=r=>parseInt(Math.log(r)/Sh,10),i=r=>parseInt(Array(r+1).join("1"),2);this.count=t(e+1),this.current_=this.count-1;const s=i(this.count);this.bits_=e+1&s}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const ln=function(n,e,t,i){n.sort(e);const s=function(c,l){const d=l-c;let h,u;if(d===0)return null;if(d===1)return h=n[c],u=t?t(h):h,new D(u,h.node,D.BLACK,null,null);{const p=parseInt(d/2,10)+c,_=s(c,p),E=s(p+1,l);return h=n[p],u=t?t(h):h,new D(u,h.node,D.BLACK,_,E)}},r=function(c){let l=null,d=null,h=n.length;const u=function(_,E){const A=h-_,H=h;h-=_;const z=s(A+1,H),ke=n[A],jn=t?t(ke):ke;p(new D(jn,ke.node,E,null,z))},p=function(_){l?(l.left=_,l=_):(d=_,l=_)};for(let _=0;_<c.count;++_){const E=c.nextBitIsOne(),A=Math.pow(2,c.count-(_+1));E?u(A,D.BLACK):(u(A,D.BLACK),u(A,D.RED))}return d},o=new bh(n.length),a=r(o);return new B(i||e,a)};let ti;const $e={};class ne{static get Default(){return f($e&&R,"ChildrenNode.ts has not been loaded"),ti=ti||new ne({".priority":$e},{".priority":R}),ti}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){const t=De(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof B?t:null}hasIndex(e){return X(this.indexSet_,e.toString())}addIndex(e,t){f(e!==je,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const i=[];let s=!1;const r=t.getIterator(I.Wrap);let o=r.getNext();for(;o;)s=s||e.isDefinedOn(o.node),i.push(o),o=r.getNext();let a;s?a=ln(i,e.getCompare()):a=$e;const c=e.toString(),l={...this.indexSet_};l[c]=e;const d={...this.indexes_};return d[c]=a,new ne(d,l)}addToIndexes(e,t){const i=rn(this.indexes_,(s,r)=>{const o=De(this.indexSet_,r);if(f(o,"Missing index implementation for "+r),s===$e)if(o.isDefinedOn(e.node)){const a=[],c=t.getIterator(I.Wrap);let l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),ln(a,o.getCompare())}else return $e;else{const a=t.get(e.name);let c=s;return a&&(c=c.remove(new I(e.name,a))),c.insert(e,e.node)}});return new ne(i,this.indexSet_)}removeFromIndexes(e,t){const i=rn(this.indexes_,s=>{if(s===$e)return s;{const r=t.get(e.name);return r?s.remove(new I(e.name,r)):s}});return new ne(i,this.indexSet_)}}let _t;class g{static get EMPTY_NODE(){return _t||(_t=new g(new B(Bi),null,ne.Default))}constructor(e,t,i){this.children_=e,this.priorityNode_=t,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&wo(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||_t}updatePriority(e){return this.children_.isEmpty()?this:new g(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const t=this.children_.get(e);return t===null?_t:t}}getChild(e){const t=y(e);return t===null?this:this.getImmediateChild(t).getChild(S(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,t){if(f(t,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(t);{const i=new I(e,t);let s,r;t.isEmpty()?(s=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(i,this.children_)):(s=this.children_.insert(e,t),r=this.indexMap_.addToIndexes(i,this.children_));const o=s.isEmpty()?_t:this.priorityNode_;return new g(s,o,r)}}updateChild(e,t){const i=y(e);if(i===null)return t;{f(y(e)!==".priority"||we(e)===1,".priority must be the last token in a path");const s=this.getImmediateChild(i).updateChild(S(e),t);return this.updateImmediateChild(i,s)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let i=0,s=0,r=!0;if(this.forEachChild(R,(o,a)=>{t[o]=a.val(e),i++,r&&g.INTEGER_REGEXP_.test(o)?s=Math.max(s,Number(o)):r=!1}),!e&&r&&s<2*i){const o=[];for(const a in t)o[a]=t[a];return o}else return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+Eo(this.getPriority().val())+":"),this.forEachChild(R,(t,i)=>{const s=i.hash();s!==""&&(e+=":"+t+":"+s)}),this.lazyHash_=e===""?"":Qr(e)}return this.lazyHash_}getPredecessorChildName(e,t,i){const s=this.resolveIndex_(i);if(s){const r=s.getPredecessorKey(new I(e,t));return r?r.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const i=t.minKey();return i&&i.name}else return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new I(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const i=t.maxKey();return i&&i.name}else return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new I(t,this.children_.get(t)):null}forEachChild(e,t){const i=this.resolveIndex_(e);return i?i.inorderTraversal(s=>t(s.name,s.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const i=this.resolveIndex_(t);if(i)return i.getIteratorFrom(e,s=>s);{const s=this.children_.getIteratorFrom(e.name,I.Wrap);let r=s.peek();for(;r!=null&&t.compare(r,e)<0;)s.getNext(),r=s.peek();return s}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const i=this.resolveIndex_(t);if(i)return i.getReverseIteratorFrom(e,s=>s);{const s=this.children_.getReverseIteratorFrom(e.name,I.Wrap);let r=s.peek();for(;r!=null&&t.compare(r,e)>0;)s.getNext(),r=s.peek();return s}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Ut?-1:0}withIndex(e){if(e===je||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new g(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===je||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority()))if(this.children_.count()===t.children_.count()){const i=this.getIterator(R),s=t.getIterator(R);let r=i.getNext(),o=s.getNext();for(;r&&o;){if(r.name!==o.name||!r.node.equals(o.node))return!1;r=i.getNext(),o=s.getNext()}return r===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===je?null:this.indexMap_.get(e.toString())}}g.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Rh extends g{constructor(){super(new B(Bi),g.EMPTY_NODE,ne.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return g.EMPTY_NODE}isEmpty(){return!1}}const Ut=new Rh;Object.defineProperties(I,{MIN:{value:new I(Xe,g.EMPTY_NODE)},MAX:{value:new I(Le,Ut)}});Io.__EMPTY_NODE=g.EMPTY_NODE;O.__childrenNodeConstructor=g;Eh(Ut);Ch(Ut);const kh=!0;function k(n,e=null){if(n===null)return g.EMPTY_NODE;if(typeof n=="object"&&".priority"in n&&(e=n[".priority"]),f(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof n=="object"&&".value"in n&&n[".value"]!==null&&(n=n[".value"]),typeof n!="object"||".sv"in n){const t=n;return new O(t,k(e))}if(!(n instanceof Array)&&kh){const t=[];let i=!1;if(x(n,(o,a)=>{if(o.substring(0,1)!=="."){const c=k(a);c.isEmpty()||(i=i||!c.getPriority().isEmpty(),t.push(new I(o,c)))}}),t.length===0)return g.EMPTY_NODE;const r=ln(t,Ih,o=>o.name,Bi);if(i){const o=ln(t,R.getCompare());return new g(r,k(e),new ne({".priority":o},{".priority":R}))}else return new g(r,k(e),ne.Default)}else{let t=g.EMPTY_NODE;return x(n,(i,s)=>{if(X(n,i)&&i.substring(0,1)!=="."){const r=k(s);(r.isLeafNode()||!r.isEmpty())&&(t=t.updateImmediateChild(i,r))}}),t.updatePriority(k(e))}}wh(k);class Nh extends An{constructor(e){super(),this.indexPath_=e,f(!v(e)&&y(e)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const i=this.extractChild(e.node),s=this.extractChild(t.node),r=i.compareTo(s);return r===0?Be(e.name,t.name):r}makePost(e,t){const i=k(e),s=g.EMPTY_NODE.updateChild(this.indexPath_,i);return new I(t,s)}maxPost(){const e=g.EMPTY_NODE.updateChild(this.indexPath_,Ut);return new I(Le,e)}toString(){return Rt(this.indexPath_,0).join("/")}}class Ah extends An{compare(e,t){const i=e.node.compareTo(t.node);return i===0?Be(e.name,t.name):i}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return I.MIN}maxPost(){return I.MAX}makePost(e,t){const i=k(e);return new I(t,i)}toString(){return".value"}}const Ph=new Ah;function So(n){return{type:"value",snapshotNode:n}}function Ze(n,e){return{type:"child_added",snapshotNode:e,childName:n}}function kt(n,e){return{type:"child_removed",snapshotNode:e,childName:n}}function Nt(n,e,t){return{type:"child_changed",snapshotNode:e,childName:n,oldSnap:t}}function Oh(n,e){return{type:"child_moved",snapshotNode:e,childName:n}}class Hi{constructor(e){this.index_=e}updateChild(e,t,i,s,r,o){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(s).equals(i.getChild(s))&&a.isEmpty()===i.isEmpty()||(o!=null&&(i.isEmpty()?e.hasChild(t)?o.trackChildChange(kt(t,a)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Ze(t,i)):o.trackChildChange(Nt(t,i,a))),e.isLeafNode()&&i.isEmpty())?e:e.updateImmediateChild(t,i).withIndex(this.index_)}updateFullNode(e,t,i){return i!=null&&(e.isLeafNode()||e.forEachChild(R,(s,r)=>{t.hasChild(s)||i.trackChildChange(kt(s,r))}),t.isLeafNode()||t.forEachChild(R,(s,r)=>{if(e.hasChild(s)){const o=e.getImmediateChild(s);o.equals(r)||i.trackChildChange(Nt(s,r,o))}else i.trackChildChange(Ze(s,r))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?g.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class At{constructor(e){this.indexedFilter_=new Hi(e.getIndex()),this.index_=e.getIndex(),this.startPost_=At.getStartPost_(e),this.endPost_=At.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,i=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&i}updateChild(e,t,i,s,r,o){return this.matches(new I(t,i))||(i=g.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,i,s,r,o)}updateFullNode(e,t,i){t.isLeafNode()&&(t=g.EMPTY_NODE);let s=t.withIndex(this.index_);s=s.updatePriority(g.EMPTY_NODE);const r=this;return t.forEachChild(R,(o,a)=>{r.matches(new I(o,a))||(s=s.updateImmediateChild(o,g.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,s,i)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}else return e.getIndex().maxPost()}}class Dh{constructor(e){this.withinDirectionalStart=t=>this.reverse_?this.withinEndPost(t):this.withinStartPost(t),this.withinDirectionalEnd=t=>this.reverse_?this.withinStartPost(t):this.withinEndPost(t),this.withinStartPost=t=>{const i=this.index_.compare(this.rangedFilter_.getStartPost(),t);return this.startIsInclusive_?i<=0:i<0},this.withinEndPost=t=>{const i=this.index_.compare(t,this.rangedFilter_.getEndPost());return this.endIsInclusive_?i<=0:i<0},this.rangedFilter_=new At(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,i,s,r,o){return this.rangedFilter_.matches(new I(t,i))||(i=g.EMPTY_NODE),e.getImmediateChild(t).equals(i)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,i,s,r,o):this.fullLimitUpdateChild_(e,t,i,r,o)}updateFullNode(e,t,i){let s;if(t.isLeafNode()||t.isEmpty())s=g.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<t.numChildren()&&t.isIndexed(this.index_)){s=g.EMPTY_NODE.withIndex(this.index_);let r;this.reverse_?r=t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r=t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let o=0;for(;r.hasNext()&&o<this.limit_;){const a=r.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))s=s.updateImmediateChild(a.name,a.node),o++;else break;else continue}}else{s=t.withIndex(this.index_),s=s.updatePriority(g.EMPTY_NODE);let r;this.reverse_?r=s.getReverseIterator(this.index_):r=s.getIterator(this.index_);let o=0;for(;r.hasNext();){const a=r.getNext();o<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?o++:s=s.updateImmediateChild(a.name,g.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,s,i)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,i,s,r){let o;if(this.reverse_){const h=this.index_.getCompare();o=(u,p)=>h(p,u)}else o=this.index_.getCompare();const a=e;f(a.numChildren()===this.limit_,"");const c=new I(t,i),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),d=this.rangedFilter_.matches(c);if(a.hasChild(t)){const h=a.getImmediateChild(t);let u=s.getChildAfterChild(this.index_,l,this.reverse_);for(;u!=null&&(u.name===t||a.hasChild(u.name));)u=s.getChildAfterChild(this.index_,u,this.reverse_);const p=u==null?1:o(u,c);if(d&&!i.isEmpty()&&p>=0)return r?.trackChildChange(Nt(t,i,h)),a.updateImmediateChild(t,i);{r?.trackChildChange(kt(t,h));const E=a.updateImmediateChild(t,g.EMPTY_NODE);return u!=null&&this.rangedFilter_.matches(u)?(r?.trackChildChange(Ze(u.name,u.node)),E.updateImmediateChild(u.name,u.node)):E}}else return i.isEmpty()?e:d&&o(l,c)>=0?(r!=null&&(r.trackChildChange(kt(l.name,l.node)),r.trackChildChange(Ze(t,i))),a.updateImmediateChild(t,i).updateImmediateChild(l.name,g.EMPTY_NODE)):e}}class Vi{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=R}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Xe}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Le}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return f(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===R}copy(){const e=new Vi;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function Mh(n){return n.loadsAllData()?new Hi(n.getIndex()):n.hasLimit()?new Dh(n):new At(n)}function Ys(n){const e={};if(n.isDefault())return e;let t;if(n.index_===R?t="$priority":n.index_===Ph?t="$value":n.index_===je?t="$key":(f(n.index_ instanceof Nh,"Unrecognized index type!"),t=n.index_.toString()),e.orderBy=P(t),n.startSet_){const i=n.startAfterSet_?"startAfter":"startAt";e[i]=P(n.indexStartValue_),n.startNameSet_&&(e[i]+=","+P(n.indexStartName_))}if(n.endSet_){const i=n.endBeforeSet_?"endBefore":"endAt";e[i]=P(n.indexEndValue_),n.endNameSet_&&(e[i]+=","+P(n.indexEndName_))}return n.limitSet_&&(n.isViewFromLeft()?e.limitToFirst=n.limit_:e.limitToLast=n.limit_),e}function Qs(n){const e={};if(n.startSet_&&(e.sp=n.indexStartValue_,n.startNameSet_&&(e.sn=n.indexStartName_),e.sin=!n.startAfterSet_),n.endSet_&&(e.ep=n.indexEndValue_,n.endNameSet_&&(e.en=n.indexEndName_),e.ein=!n.endBeforeSet_),n.limitSet_){e.l=n.limit_;let t=n.viewFrom_;t===""&&(n.isViewFromLeft()?t="l":t="r"),e.vf=t}return n.index_!==R&&(e.i=n.index_.toString()),e}class hn extends go{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return t!==void 0?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,i,s){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=i,this.appCheckTokenProvider_=s,this.log_=Ft("p:rest:"),this.listens_={}}listen(e,t,i,s){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=hn.getListenId_(e,i),a={};this.listens_[o]=a;const c=Ys(e._queryParams);this.restRequest_(r+".json",c,(l,d)=>{let h=d;if(l===404&&(h=null,l=null),l===null&&this.onDataUpdate_(r,h,!1,i),De(this.listens_,o)===a){let u;l?l===401?u="permission_denied":u="rest_error:"+l:u="ok",s(u,null)}})}unlisten(e,t){const i=hn.getListenId_(e,t);delete this.listens_[i]}get(e){const t=Ys(e._queryParams),i=e._path.toString(),s=new j;return this.restRequest_(i+".json",t,(r,o)=>{let a=o;r===404&&(a=null,r=null),r===null?(this.onDataUpdate_(i,a,!1,null),s.resolve(a)):s.reject(new Error(a))}),s.promise}refreshAuthToken(e){}restRequest_(e,t={},i){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([s,r])=>{s&&s.accessToken&&(t.auth=s.accessToken),r&&r.token&&(t.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+ot(t);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(i&&a.readyState===4){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=Tt(a.responseText)}catch{U("Failed to parse JSON response for "+o+": "+a.responseText)}i(null,c)}else a.status!==401&&a.status!==404&&U("Got unsuccessful REST response for "+o+" Status: "+a.status),i(a.status);i=null}},a.open("GET",o,!0),a.send()})}}class xh{constructor(){this.rootNode_=g.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function un(){return{value:null,children:new Map}}function lt(n,e,t){if(v(e))n.value=t,n.children.clear();else if(n.value!==null)n.value=n.value.updateChild(e,t);else{const i=y(e);n.children.has(i)||n.children.set(i,un());const s=n.children.get(i);e=S(e),lt(s,e,t)}}function _i(n,e){if(v(e))return n.value=null,n.children.clear(),!0;if(n.value!==null){if(n.value.isLeafNode())return!1;{const t=n.value;return n.value=null,t.forEachChild(R,(i,s)=>{lt(n,new C(i),s)}),_i(n,e)}}else if(n.children.size>0){const t=y(e);return e=S(e),n.children.has(t)&&_i(n.children.get(t),e)&&n.children.delete(t),n.children.size===0}else return!0}function gi(n,e,t){n.value!==null?t(e,n.value):Lh(n,(i,s)=>{const r=new C(e.toString()+"/"+i);gi(s,r,t)})}function Lh(n,e){n.children.forEach((t,i)=>{e(i,t)})}class Fh{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t={...e};return this.last_&&x(this.last_,(i,s)=>{t[i]=t[i]-s}),this.last_=e,t}}const Js=10*1e3,Uh=30*1e3,Wh=300*1e3;class Bh{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Fh(e);const i=Js+(Uh-Js)*Math.random();vt(this.reportStats_.bind(this),Math.floor(i))}reportStats_(){const e=this.statsListener_.get(),t={};let i=!1;x(e,(s,r)=>{r>0&&X(this.statsToReport_,s)&&(t[s]=r,i=!0)}),i&&this.server_.reportStats(t),vt(this.reportStats_.bind(this),Math.floor(Math.random()*2*Wh))}}var K;(function(n){n[n.OVERWRITE=0]="OVERWRITE",n[n.MERGE=1]="MERGE",n[n.ACK_USER_WRITE=2]="ACK_USER_WRITE",n[n.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(K||(K={}));function $i(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Gi(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function zi(n){return{fromUser:!1,fromServer:!0,queryId:n,tagged:!0}}class dn{constructor(e,t,i){this.path=e,this.affectedTree=t,this.revert=i,this.type=K.ACK_USER_WRITE,this.source=$i()}operationForChild(e){if(v(this.path)){if(this.affectedTree.value!=null)return f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new C(e));return new dn(w(),t,this.revert)}}else return f(y(this.path)===e,"operationForChild called for unrelated child."),new dn(S(this.path),this.affectedTree,this.revert)}}class Pt{constructor(e,t){this.source=e,this.path=t,this.type=K.LISTEN_COMPLETE}operationForChild(e){return v(this.path)?new Pt(this.source,w()):new Pt(this.source,S(this.path))}}class Fe{constructor(e,t,i){this.source=e,this.path=t,this.snap=i,this.type=K.OVERWRITE}operationForChild(e){return v(this.path)?new Fe(this.source,w(),this.snap.getImmediateChild(e)):new Fe(this.source,S(this.path),this.snap)}}class et{constructor(e,t,i){this.source=e,this.path=t,this.children=i,this.type=K.MERGE}operationForChild(e){if(v(this.path)){const t=this.children.subtree(new C(e));return t.isEmpty()?null:t.value?new Fe(this.source,w(),t.value):new et(this.source,w(),t)}else return f(y(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new et(this.source,S(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Ce{constructor(e,t,i){this.node_=e,this.fullyInitialized_=t,this.filtered_=i}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(v(e))return this.isFullyInitialized()&&!this.filtered_;const t=y(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Hh{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Vh(n,e,t,i){const s=[],r=[];return e.forEach(o=>{o.type==="child_changed"&&n.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&r.push(Oh(o.childName,o.snapshotNode))}),gt(n,s,"child_removed",e,i,t),gt(n,s,"child_added",e,i,t),gt(n,s,"child_moved",r,i,t),gt(n,s,"child_changed",e,i,t),gt(n,s,"value",e,i,t),s}function gt(n,e,t,i,s,r){const o=i.filter(a=>a.type===t);o.sort((a,c)=>Gh(n,a,c)),o.forEach(a=>{const c=$h(n,a,r);s.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,n.query_))})})}function $h(n,e,t){return e.type==="value"||e.type==="child_removed"||(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,n.index_)),e}function Gh(n,e,t){if(e.childName==null||t.childName==null)throw st("Should only compare child_ events.");const i=new I(e.childName,e.snapshotNode),s=new I(t.childName,t.snapshotNode);return n.index_.compare(i,s)}function Pn(n,e){return{eventCache:n,serverCache:e}}function It(n,e,t,i){return Pn(new Ce(e,t,i),n.serverCache)}function bo(n,e,t,i){return Pn(n.eventCache,new Ce(e,t,i))}function fn(n){return n.eventCache.isFullyInitialized()?n.eventCache.getNode():null}function Ue(n){return n.serverCache.isFullyInitialized()?n.serverCache.getNode():null}let ni;const zh=()=>(ni||(ni=new B(Nl)),ni);class b{static fromObject(e){let t=new b(null);return x(e,(i,s)=>{t=t.set(new C(i),s)}),t}constructor(e,t=zh()){this.value=e,this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value))return{path:w(),value:this.value};if(v(e))return null;{const i=y(e),s=this.children.get(i);if(s!==null){const r=s.findRootMostMatchingPathAndValue(S(e),t);return r!=null?{path:N(new C(i),r.path),value:r.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(v(e))return this;{const t=y(e),i=this.children.get(t);return i!==null?i.subtree(S(e)):new b(null)}}set(e,t){if(v(e))return new b(t,this.children);{const i=y(e),r=(this.children.get(i)||new b(null)).set(S(e),t),o=this.children.insert(i,r);return new b(this.value,o)}}remove(e){if(v(e))return this.children.isEmpty()?new b(null):new b(null,this.children);{const t=y(e),i=this.children.get(t);if(i){const s=i.remove(S(e));let r;return s.isEmpty()?r=this.children.remove(t):r=this.children.insert(t,s),this.value===null&&r.isEmpty()?new b(null):new b(this.value,r)}else return this}}get(e){if(v(e))return this.value;{const t=y(e),i=this.children.get(t);return i?i.get(S(e)):null}}setTree(e,t){if(v(e))return t;{const i=y(e),r=(this.children.get(i)||new b(null)).setTree(S(e),t);let o;return r.isEmpty()?o=this.children.remove(i):o=this.children.insert(i,r),new b(this.value,o)}}fold(e){return this.fold_(w(),e)}fold_(e,t){const i={};return this.children.inorderTraversal((s,r)=>{i[s]=r.fold_(N(e,s),t)}),t(e,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,w(),t)}findOnPath_(e,t,i){const s=this.value?i(t,this.value):!1;if(s)return s;if(v(e))return null;{const r=y(e),o=this.children.get(r);return o?o.findOnPath_(S(e),N(t,r),i):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,w(),t)}foreachOnPath_(e,t,i){if(v(e))return this;{this.value&&i(t,this.value);const s=y(e),r=this.children.get(s);return r?r.foreachOnPath_(S(e),N(t,s),i):new b(null)}}foreach(e){this.foreach_(w(),e)}foreach_(e,t){this.children.inorderTraversal((i,s)=>{s.foreach_(N(e,i),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,i)=>{i.value&&e(t,i.value)})}}class Q{constructor(e){this.writeTree_=e}static empty(){return new Q(new b(null))}}function Et(n,e,t){if(v(e))return new Q(new b(t));{const i=n.writeTree_.findRootMostValueAndPath(e);if(i!=null){const s=i.path;let r=i.value;const o=F(s,e);return r=r.updateChild(o,t),new Q(n.writeTree_.set(s,r))}else{const s=new b(t),r=n.writeTree_.setTree(e,s);return new Q(r)}}}function mi(n,e,t){let i=n;return x(t,(s,r)=>{i=Et(i,N(e,s),r)}),i}function Xs(n,e){if(v(e))return Q.empty();{const t=n.writeTree_.setTree(e,new b(null));return new Q(t)}}function yi(n,e){return He(n,e)!=null}function He(n,e){const t=n.writeTree_.findRootMostValueAndPath(e);return t!=null?n.writeTree_.get(t.path).getChild(F(t.path,e)):null}function Zs(n){const e=[],t=n.writeTree_.value;return t!=null?t.isLeafNode()||t.forEachChild(R,(i,s)=>{e.push(new I(i,s))}):n.writeTree_.children.inorderTraversal((i,s)=>{s.value!=null&&e.push(new I(i,s.value))}),e}function ve(n,e){if(v(e))return n;{const t=He(n,e);return t!=null?new Q(new b(t)):new Q(n.writeTree_.subtree(e))}}function vi(n){return n.writeTree_.isEmpty()}function tt(n,e){return Ro(w(),n.writeTree_,e)}function Ro(n,e,t){if(e.value!=null)return t.updateChild(n,e.value);{let i=null;return e.children.inorderTraversal((s,r)=>{s===".priority"?(f(r.value!==null,"Priority writes must always be leaf nodes"),i=r.value):t=Ro(N(n,s),r,t)}),!t.getChild(n).isEmpty()&&i!==null&&(t=t.updateChild(N(n,".priority"),i)),t}}function On(n,e){return Po(e,n)}function jh(n,e,t,i,s){f(i>n.lastWriteId,"Stacking an older write on top of newer ones"),s===void 0&&(s=!0),n.allWrites.push({path:e,snap:t,writeId:i,visible:s}),s&&(n.visibleWrites=Et(n.visibleWrites,e,t)),n.lastWriteId=i}function qh(n,e,t,i){f(i>n.lastWriteId,"Stacking an older merge on top of newer ones"),n.allWrites.push({path:e,children:t,writeId:i,visible:!0}),n.visibleWrites=mi(n.visibleWrites,e,t),n.lastWriteId=i}function Kh(n,e){for(let t=0;t<n.allWrites.length;t++){const i=n.allWrites[t];if(i.writeId===e)return i}return null}function Yh(n,e){const t=n.allWrites.findIndex(a=>a.writeId===e);f(t>=0,"removeWrite called with nonexistent writeId.");const i=n.allWrites[t];n.allWrites.splice(t,1);let s=i.visible,r=!1,o=n.allWrites.length-1;for(;s&&o>=0;){const a=n.allWrites[o];a.visible&&(o>=t&&Qh(a,i.path)?s=!1:G(i.path,a.path)&&(r=!0)),o--}if(s){if(r)return Jh(n),!0;if(i.snap)n.visibleWrites=Xs(n.visibleWrites,i.path);else{const a=i.children;x(a,c=>{n.visibleWrites=Xs(n.visibleWrites,N(i.path,c))})}return!0}else return!1}function Qh(n,e){if(n.snap)return G(n.path,e);for(const t in n.children)if(n.children.hasOwnProperty(t)&&G(N(n.path,t),e))return!0;return!1}function Jh(n){n.visibleWrites=ko(n.allWrites,Xh,w()),n.allWrites.length>0?n.lastWriteId=n.allWrites[n.allWrites.length-1].writeId:n.lastWriteId=-1}function Xh(n){return n.visible}function ko(n,e,t){let i=Q.empty();for(let s=0;s<n.length;++s){const r=n[s];if(e(r)){const o=r.path;let a;if(r.snap)G(t,o)?(a=F(t,o),i=Et(i,a,r.snap)):G(o,t)&&(a=F(o,t),i=Et(i,w(),r.snap.getChild(a)));else if(r.children){if(G(t,o))a=F(t,o),i=mi(i,a,r.children);else if(G(o,t))if(a=F(o,t),v(a))i=mi(i,w(),r.children);else{const c=De(r.children,y(a));if(c){const l=c.getChild(S(a));i=Et(i,w(),l)}}}else throw st("WriteRecord should have .snap or .children")}}return i}function No(n,e,t,i,s){if(!i&&!s){const r=He(n.visibleWrites,e);if(r!=null)return r;{const o=ve(n.visibleWrites,e);if(vi(o))return t;if(t==null&&!yi(o,w()))return null;{const a=t||g.EMPTY_NODE;return tt(o,a)}}}else{const r=ve(n.visibleWrites,e);if(!s&&vi(r))return t;if(!s&&t==null&&!yi(r,w()))return null;{const o=function(l){return(l.visible||s)&&(!i||!~i.indexOf(l.writeId))&&(G(l.path,e)||G(e,l.path))},a=ko(n.allWrites,o,e),c=t||g.EMPTY_NODE;return tt(a,c)}}}function Zh(n,e,t){let i=g.EMPTY_NODE;const s=He(n.visibleWrites,e);if(s)return s.isLeafNode()||s.forEachChild(R,(r,o)=>{i=i.updateImmediateChild(r,o)}),i;if(t){const r=ve(n.visibleWrites,e);return t.forEachChild(R,(o,a)=>{const c=tt(ve(r,new C(o)),a);i=i.updateImmediateChild(o,c)}),Zs(r).forEach(o=>{i=i.updateImmediateChild(o.name,o.node)}),i}else{const r=ve(n.visibleWrites,e);return Zs(r).forEach(o=>{i=i.updateImmediateChild(o.name,o.node)}),i}}function eu(n,e,t,i,s){f(i||s,"Either existingEventSnap or existingServerSnap must exist");const r=N(e,t);if(yi(n.visibleWrites,r))return null;{const o=ve(n.visibleWrites,r);return vi(o)?s.getChild(t):tt(o,s.getChild(t))}}function tu(n,e,t,i){const s=N(e,t),r=He(n.visibleWrites,s);if(r!=null)return r;if(i.isCompleteForChild(t)){const o=ve(n.visibleWrites,s);return tt(o,i.getNode().getImmediateChild(t))}else return null}function nu(n,e){return He(n.visibleWrites,e)}function iu(n,e,t,i,s,r,o){let a;const c=ve(n.visibleWrites,e),l=He(c,w());if(l!=null)a=l;else if(t!=null)a=tt(c,t);else return[];if(a=a.withIndex(o),!a.isEmpty()&&!a.isLeafNode()){const d=[],h=o.getCompare(),u=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let p=u.getNext();for(;p&&d.length<s;)h(p,i)!==0&&d.push(p),p=u.getNext();return d}else return[]}function su(){return{visibleWrites:Q.empty(),allWrites:[],lastWriteId:-1}}function pn(n,e,t,i){return No(n.writeTree,n.treePath,e,t,i)}function ji(n,e){return Zh(n.writeTree,n.treePath,e)}function er(n,e,t,i){return eu(n.writeTree,n.treePath,e,t,i)}function _n(n,e){return nu(n.writeTree,N(n.treePath,e))}function ru(n,e,t,i,s,r){return iu(n.writeTree,n.treePath,e,t,i,s,r)}function qi(n,e,t){return tu(n.writeTree,n.treePath,e,t)}function Ao(n,e){return Po(N(n.treePath,e),n.writeTree)}function Po(n,e){return{treePath:n,writeTree:e}}class ou{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,i=e.childName;f(t==="child_added"||t==="child_changed"||t==="child_removed","Only child changes supported for tracking"),f(i!==".priority","Only non-priority child changes can be tracked.");const s=this.changeMap.get(i);if(s){const r=s.type;if(t==="child_added"&&r==="child_removed")this.changeMap.set(i,Nt(i,e.snapshotNode,s.snapshotNode));else if(t==="child_removed"&&r==="child_added")this.changeMap.delete(i);else if(t==="child_removed"&&r==="child_changed")this.changeMap.set(i,kt(i,s.oldSnap));else if(t==="child_changed"&&r==="child_added")this.changeMap.set(i,Ze(i,e.snapshotNode));else if(t==="child_changed"&&r==="child_changed")this.changeMap.set(i,Nt(i,e.snapshotNode,s.oldSnap));else throw st("Illegal combination of changes: "+e+" occurred after "+s)}else this.changeMap.set(i,e)}getChanges(){return Array.from(this.changeMap.values())}}class au{getCompleteChild(e){return null}getChildAfterChild(e,t,i){return null}}const Oo=new au;class Ki{constructor(e,t,i=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=i}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const i=this.optCompleteServerCache_!=null?new Ce(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return qi(this.writes_,e,i)}}getChildAfterChild(e,t,i){const s=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:Ue(this.viewCache_),r=ru(this.writes_,s,t,1,i,e);return r.length===0?null:r[0]}}function cu(n){return{filter:n}}function lu(n,e){f(e.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),f(e.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed")}function hu(n,e,t,i,s){const r=new ou;let o,a;if(t.type===K.OVERWRITE){const l=t;l.source.fromUser?o=Ii(n,e,l.path,l.snap,i,s,r):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!v(l.path),o=gn(n,e,l.path,l.snap,i,s,a,r))}else if(t.type===K.MERGE){const l=t;l.source.fromUser?o=du(n,e,l.path,l.children,i,s,r):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),o=Ei(n,e,l.path,l.children,i,s,a,r))}else if(t.type===K.ACK_USER_WRITE){const l=t;l.revert?o=_u(n,e,l.path,i,s,r):o=fu(n,e,l.path,l.affectedTree,i,s,r)}else if(t.type===K.LISTEN_COMPLETE)o=pu(n,e,t.path,i,r);else throw st("Unknown operation type: "+t.type);const c=r.getChanges();return uu(e,o,c),{viewCache:o,changes:c}}function uu(n,e,t){const i=e.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=fn(n);(t.length>0||!n.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&t.push(So(fn(e)))}}function Do(n,e,t,i,s,r){const o=e.eventCache;if(_n(i,t)!=null)return e;{let a,c;if(v(t))if(f(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const l=Ue(e),d=l instanceof g?l:g.EMPTY_NODE,h=ji(i,d);a=n.filter.updateFullNode(e.eventCache.getNode(),h,r)}else{const l=pn(i,Ue(e));a=n.filter.updateFullNode(e.eventCache.getNode(),l,r)}else{const l=y(t);if(l===".priority"){f(we(t)===1,"Can't have a priority with additional path components");const d=o.getNode();c=e.serverCache.getNode();const h=er(i,t,d,c);h!=null?a=n.filter.updatePriority(d,h):a=o.getNode()}else{const d=S(t);let h;if(o.isCompleteForChild(l)){c=e.serverCache.getNode();const u=er(i,t,o.getNode(),c);u!=null?h=o.getNode().getImmediateChild(l).updateChild(d,u):h=o.getNode().getImmediateChild(l)}else h=qi(i,l,e.serverCache);h!=null?a=n.filter.updateChild(o.getNode(),l,h,d,s,r):a=o.getNode()}}return It(e,a,o.isFullyInitialized()||v(t),n.filter.filtersNodes())}}function gn(n,e,t,i,s,r,o,a){const c=e.serverCache;let l;const d=o?n.filter:n.filter.getIndexedFilter();if(v(t))l=d.updateFullNode(c.getNode(),i,null);else if(d.filtersNodes()&&!c.isFiltered()){const p=c.getNode().updateChild(t,i);l=d.updateFullNode(c.getNode(),p,null)}else{const p=y(t);if(!c.isCompleteForPath(t)&&we(t)>1)return e;const _=S(t),A=c.getNode().getImmediateChild(p).updateChild(_,i);p===".priority"?l=d.updatePriority(c.getNode(),A):l=d.updateChild(c.getNode(),p,A,_,Oo,null)}const h=bo(e,l,c.isFullyInitialized()||v(t),d.filtersNodes()),u=new Ki(s,h,r);return Do(n,h,t,s,u,a)}function Ii(n,e,t,i,s,r,o){const a=e.eventCache;let c,l;const d=new Ki(s,e,r);if(v(t))l=n.filter.updateFullNode(e.eventCache.getNode(),i,o),c=It(e,l,!0,n.filter.filtersNodes());else{const h=y(t);if(h===".priority")l=n.filter.updatePriority(e.eventCache.getNode(),i),c=It(e,l,a.isFullyInitialized(),a.isFiltered());else{const u=S(t),p=a.getNode().getImmediateChild(h);let _;if(v(u))_=i;else{const E=d.getCompleteChild(h);E!=null?Fi(u)===".priority"&&E.getChild(yo(u)).isEmpty()?_=E:_=E.updateChild(u,i):_=g.EMPTY_NODE}if(p.equals(_))c=e;else{const E=n.filter.updateChild(a.getNode(),h,_,u,d,o);c=It(e,E,a.isFullyInitialized(),n.filter.filtersNodes())}}}return c}function tr(n,e){return n.eventCache.isCompleteForChild(e)}function du(n,e,t,i,s,r,o){let a=e;return i.foreach((c,l)=>{const d=N(t,c);tr(e,y(d))&&(a=Ii(n,a,d,l,s,r,o))}),i.foreach((c,l)=>{const d=N(t,c);tr(e,y(d))||(a=Ii(n,a,d,l,s,r,o))}),a}function nr(n,e,t){return t.foreach((i,s)=>{e=e.updateChild(i,s)}),e}function Ei(n,e,t,i,s,r,o,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;v(t)?l=i:l=new b(null).setTree(t,i);const d=e.serverCache.getNode();return l.children.inorderTraversal((h,u)=>{if(d.hasChild(h)){const p=e.serverCache.getNode().getImmediateChild(h),_=nr(n,p,u);c=gn(n,c,new C(h),_,s,r,o,a)}}),l.children.inorderTraversal((h,u)=>{const p=!e.serverCache.isCompleteForChild(h)&&u.value===null;if(!d.hasChild(h)&&!p){const _=e.serverCache.getNode().getImmediateChild(h),E=nr(n,_,u);c=gn(n,c,new C(h),E,s,r,o,a)}}),c}function fu(n,e,t,i,s,r,o){if(_n(s,t)!=null)return e;const a=e.serverCache.isFiltered(),c=e.serverCache;if(i.value!=null){if(v(t)&&c.isFullyInitialized()||c.isCompleteForPath(t))return gn(n,e,t,c.getNode().getChild(t),s,r,a,o);if(v(t)){let l=new b(null);return c.getNode().forEachChild(je,(d,h)=>{l=l.set(new C(d),h)}),Ei(n,e,t,l,s,r,a,o)}else return e}else{let l=new b(null);return i.foreach((d,h)=>{const u=N(t,d);c.isCompleteForPath(u)&&(l=l.set(d,c.getNode().getChild(u)))}),Ei(n,e,t,l,s,r,a,o)}}function pu(n,e,t,i,s){const r=e.serverCache,o=bo(e,r.getNode(),r.isFullyInitialized()||v(t),r.isFiltered());return Do(n,o,t,i,Oo,s)}function _u(n,e,t,i,s,r){let o;if(_n(i,t)!=null)return e;{const a=new Ki(i,e,s),c=e.eventCache.getNode();let l;if(v(t)||y(t)===".priority"){let d;if(e.serverCache.isFullyInitialized())d=pn(i,Ue(e));else{const h=e.serverCache.getNode();f(h instanceof g,"serverChildren would be complete if leaf node"),d=ji(i,h)}d=d,l=n.filter.updateFullNode(c,d,r)}else{const d=y(t);let h=qi(i,d,e.serverCache);h==null&&e.serverCache.isCompleteForChild(d)&&(h=c.getImmediateChild(d)),h!=null?l=n.filter.updateChild(c,d,h,S(t),a,r):e.eventCache.getNode().hasChild(d)?l=n.filter.updateChild(c,d,g.EMPTY_NODE,S(t),a,r):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=pn(i,Ue(e)),o.isLeafNode()&&(l=n.filter.updateFullNode(l,o,r)))}return o=e.serverCache.isFullyInitialized()||_n(i,w())!=null,It(e,l,o,n.filter.filtersNodes())}}class gu{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const i=this.query_._queryParams,s=new Hi(i.getIndex()),r=Mh(i);this.processor_=cu(r);const o=t.serverCache,a=t.eventCache,c=s.updateFullNode(g.EMPTY_NODE,o.getNode(),null),l=r.updateFullNode(g.EMPTY_NODE,a.getNode(),null),d=new Ce(c,o.isFullyInitialized(),s.filtersNodes()),h=new Ce(l,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=Pn(h,d),this.eventGenerator_=new Hh(this.query_)}get query(){return this.query_}}function mu(n){return n.viewCache_.serverCache.getNode()}function yu(n){return fn(n.viewCache_)}function vu(n,e){const t=Ue(n.viewCache_);return t&&(n.query._queryParams.loadsAllData()||!v(e)&&!t.getImmediateChild(y(e)).isEmpty())?t.getChild(e):null}function ir(n){return n.eventRegistrations_.length===0}function Iu(n,e){n.eventRegistrations_.push(e)}function sr(n,e,t){const i=[];if(t){f(e==null,"A cancel should cancel all event registrations.");const s=n.query._path;n.eventRegistrations_.forEach(r=>{const o=r.createCancelEvent(t,s);o&&i.push(o)})}if(e){let s=[];for(let r=0;r<n.eventRegistrations_.length;++r){const o=n.eventRegistrations_[r];if(!o.matches(e))s.push(o);else if(e.hasAnyCallback()){s=s.concat(n.eventRegistrations_.slice(r+1));break}}n.eventRegistrations_=s}else n.eventRegistrations_=[];return i}function rr(n,e,t,i){e.type===K.MERGE&&e.source.queryId!==null&&(f(Ue(n.viewCache_),"We should always have a full cache before handling merges"),f(fn(n.viewCache_),"Missing event cache, even though we have a server cache"));const s=n.viewCache_,r=hu(n.processor_,s,e,t,i);return lu(n.processor_,r.viewCache),f(r.viewCache.serverCache.isFullyInitialized()||!s.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),n.viewCache_=r.viewCache,Mo(n,r.changes,r.viewCache.eventCache.getNode(),null)}function Eu(n,e){const t=n.viewCache_.eventCache,i=[];return t.getNode().isLeafNode()||t.getNode().forEachChild(R,(r,o)=>{i.push(Ze(r,o))}),t.isFullyInitialized()&&i.push(So(t.getNode())),Mo(n,i,t.getNode(),e)}function Mo(n,e,t,i){const s=i?[i]:n.eventRegistrations_;return Vh(n.eventGenerator_,e,t,s)}let mn;class xo{constructor(){this.views=new Map}}function wu(n){f(!mn,"__referenceConstructor has already been defined"),mn=n}function Cu(){return f(mn,"Reference.ts has not been loaded"),mn}function Tu(n){return n.views.size===0}function Yi(n,e,t,i){const s=e.source.queryId;if(s!==null){const r=n.views.get(s);return f(r!=null,"SyncTree gave us an op for an invalid query."),rr(r,e,t,i)}else{let r=[];for(const o of n.views.values())r=r.concat(rr(o,e,t,i));return r}}function Lo(n,e,t,i,s){const r=e._queryIdentifier,o=n.views.get(r);if(!o){let a=pn(t,s?i:null),c=!1;a?c=!0:i instanceof g?(a=ji(t,i),c=!1):(a=g.EMPTY_NODE,c=!1);const l=Pn(new Ce(a,c,!1),new Ce(i,s,!1));return new gu(e,l)}return o}function Su(n,e,t,i,s,r){const o=Lo(n,e,i,s,r);return n.views.has(e._queryIdentifier)||n.views.set(e._queryIdentifier,o),Iu(o,t),Eu(o,t)}function bu(n,e,t,i){const s=e._queryIdentifier,r=[];let o=[];const a=Te(n);if(s==="default")for(const[c,l]of n.views.entries())o=o.concat(sr(l,t,i)),ir(l)&&(n.views.delete(c),l.query._queryParams.loadsAllData()||r.push(l.query));else{const c=n.views.get(s);c&&(o=o.concat(sr(c,t,i)),ir(c)&&(n.views.delete(s),c.query._queryParams.loadsAllData()||r.push(c.query)))}return a&&!Te(n)&&r.push(new(Cu())(e._repo,e._path)),{removed:r,events:o}}function Fo(n){const e=[];for(const t of n.views.values())t.query._queryParams.loadsAllData()||e.push(t);return e}function Ie(n,e){let t=null;for(const i of n.views.values())t=t||vu(i,e);return t}function Uo(n,e){if(e._queryParams.loadsAllData())return Dn(n);{const i=e._queryIdentifier;return n.views.get(i)}}function Wo(n,e){return Uo(n,e)!=null}function Te(n){return Dn(n)!=null}function Dn(n){for(const e of n.views.values())if(e.query._queryParams.loadsAllData())return e;return null}let yn;function Ru(n){f(!yn,"__referenceConstructor has already been defined"),yn=n}function ku(){return f(yn,"Reference.ts has not been loaded"),yn}let Nu=1;class or{constructor(e){this.listenProvider_=e,this.syncPointTree_=new b(null),this.pendingWriteTree_=su(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Qi(n,e,t,i,s){return jh(n.pendingWriteTree_,e,t,i,s),s?ht(n,new Fe($i(),e,t)):[]}function Au(n,e,t,i){qh(n.pendingWriteTree_,e,t,i);const s=b.fromObject(t);return ht(n,new et($i(),e,s))}function pe(n,e,t=!1){const i=Kh(n.pendingWriteTree_,e);if(Yh(n.pendingWriteTree_,e)){let r=new b(null);return i.snap!=null?r=r.set(w(),!0):x(i.children,o=>{r=r.set(new C(o),!0)}),ht(n,new dn(i.path,r,t))}else return[]}function Wt(n,e,t){return ht(n,new Fe(Gi(),e,t))}function Pu(n,e,t){const i=b.fromObject(t);return ht(n,new et(Gi(),e,i))}function Ou(n,e){return ht(n,new Pt(Gi(),e))}function Du(n,e,t){const i=Ji(n,t);if(i){const s=Xi(i),r=s.path,o=s.queryId,a=F(r,e),c=new Pt(zi(o),a);return Zi(n,r,c)}else return[]}function vn(n,e,t,i,s=!1){const r=e._path,o=n.syncPointTree_.get(r);let a=[];if(o&&(e._queryIdentifier==="default"||Wo(o,e))){const c=bu(o,e,t,i);Tu(o)&&(n.syncPointTree_=n.syncPointTree_.remove(r));const l=c.removed;if(a=c.events,!s){const d=l.findIndex(u=>u._queryParams.loadsAllData())!==-1,h=n.syncPointTree_.findOnPath(r,(u,p)=>Te(p));if(d&&!h){const u=n.syncPointTree_.subtree(r);if(!u.isEmpty()){const p=Lu(u);for(let _=0;_<p.length;++_){const E=p[_],A=E.query,H=$o(n,E);n.listenProvider_.startListening(wt(A),Ot(n,A),H.hashFn,H.onComplete)}}}!h&&l.length>0&&!i&&(d?n.listenProvider_.stopListening(wt(e),null):l.forEach(u=>{const p=n.queryToTagMap.get(xn(u));n.listenProvider_.stopListening(wt(u),p)}))}Fu(n,l)}return a}function Bo(n,e,t,i){const s=Ji(n,i);if(s!=null){const r=Xi(s),o=r.path,a=r.queryId,c=F(o,e),l=new Fe(zi(a),c,t);return Zi(n,o,l)}else return[]}function Mu(n,e,t,i){const s=Ji(n,i);if(s){const r=Xi(s),o=r.path,a=r.queryId,c=F(o,e),l=b.fromObject(t),d=new et(zi(a),c,l);return Zi(n,o,d)}else return[]}function wi(n,e,t,i=!1){const s=e._path;let r=null,o=!1;n.syncPointTree_.foreachOnPath(s,(u,p)=>{const _=F(u,s);r=r||Ie(p,_),o=o||Te(p)});let a=n.syncPointTree_.get(s);a?(o=o||Te(a),r=r||Ie(a,w())):(a=new xo,n.syncPointTree_=n.syncPointTree_.set(s,a));let c;r!=null?c=!0:(c=!1,r=g.EMPTY_NODE,n.syncPointTree_.subtree(s).foreachChild((p,_)=>{const E=Ie(_,w());E&&(r=r.updateImmediateChild(p,E))}));const l=Wo(a,e);if(!l&&!e._queryParams.loadsAllData()){const u=xn(e);f(!n.queryToTagMap.has(u),"View does not exist, but we have a tag");const p=Uu();n.queryToTagMap.set(u,p),n.tagToQueryMap.set(p,u)}const d=On(n.pendingWriteTree_,s);let h=Su(a,e,t,d,r,c);if(!l&&!o&&!i){const u=Uo(a,e);h=h.concat(Wu(n,e,u))}return h}function Mn(n,e,t){const s=n.pendingWriteTree_,r=n.syncPointTree_.findOnPath(e,(o,a)=>{const c=F(o,e),l=Ie(a,c);if(l)return l});return No(s,e,r,t,!0)}function xu(n,e){const t=e._path;let i=null;n.syncPointTree_.foreachOnPath(t,(l,d)=>{const h=F(l,t);i=i||Ie(d,h)});let s=n.syncPointTree_.get(t);s?i=i||Ie(s,w()):(s=new xo,n.syncPointTree_=n.syncPointTree_.set(t,s));const r=i!=null,o=r?new Ce(i,!0,!1):null,a=On(n.pendingWriteTree_,e._path),c=Lo(s,e,a,r?o.getNode():g.EMPTY_NODE,r);return yu(c)}function ht(n,e){return Ho(e,n.syncPointTree_,null,On(n.pendingWriteTree_,w()))}function Ho(n,e,t,i){if(v(n.path))return Vo(n,e,t,i);{const s=e.get(w());t==null&&s!=null&&(t=Ie(s,w()));let r=[];const o=y(n.path),a=n.operationForChild(o),c=e.children.get(o);if(c&&a){const l=t?t.getImmediateChild(o):null,d=Ao(i,o);r=r.concat(Ho(a,c,l,d))}return s&&(r=r.concat(Yi(s,n,i,t))),r}}function Vo(n,e,t,i){const s=e.get(w());t==null&&s!=null&&(t=Ie(s,w()));let r=[];return e.children.inorderTraversal((o,a)=>{const c=t?t.getImmediateChild(o):null,l=Ao(i,o),d=n.operationForChild(o);d&&(r=r.concat(Vo(d,a,c,l)))}),s&&(r=r.concat(Yi(s,n,i,t))),r}function $o(n,e){const t=e.query,i=Ot(n,t);return{hashFn:()=>(mu(e)||g.EMPTY_NODE).hash(),onComplete:s=>{if(s==="ok")return i?Du(n,t._path,i):Ou(n,t._path);{const r=Ol(s,t);return vn(n,t,null,r)}}}}function Ot(n,e){const t=xn(e);return n.queryToTagMap.get(t)}function xn(n){return n._path.toString()+"$"+n._queryIdentifier}function Ji(n,e){return n.tagToQueryMap.get(e)}function Xi(n){const e=n.indexOf("$");return f(e!==-1&&e<n.length-1,"Bad queryKey."),{queryId:n.substr(e+1),path:new C(n.substr(0,e))}}function Zi(n,e,t){const i=n.syncPointTree_.get(e);f(i,"Missing sync point for query tag that we're tracking");const s=On(n.pendingWriteTree_,e);return Yi(i,t,s,null)}function Lu(n){return n.fold((e,t,i)=>{if(t&&Te(t))return[Dn(t)];{let s=[];return t&&(s=Fo(t)),x(i,(r,o)=>{s=s.concat(o)}),s}})}function wt(n){return n._queryParams.loadsAllData()&&!n._queryParams.isDefault()?new(ku())(n._repo,n._path):n}function Fu(n,e){for(let t=0;t<e.length;++t){const i=e[t];if(!i._queryParams.loadsAllData()){const s=xn(i),r=n.queryToTagMap.get(s);n.queryToTagMap.delete(s),n.tagToQueryMap.delete(r)}}}function Uu(){return Nu++}function Wu(n,e,t){const i=e._path,s=Ot(n,e),r=$o(n,t),o=n.listenProvider_.startListening(wt(e),s,r.hashFn,r.onComplete),a=n.syncPointTree_.subtree(i);if(s)f(!Te(a.value),"If we're adding a query, it shouldn't be shadowed");else{const c=a.fold((l,d,h)=>{if(!v(l)&&d&&Te(d))return[Dn(d).query];{let u=[];return d&&(u=u.concat(Fo(d).map(p=>p.query))),x(h,(p,_)=>{u=u.concat(_)}),u}});for(let l=0;l<c.length;++l){const d=c[l];n.listenProvider_.stopListening(wt(d),Ot(n,d))}}return o}class es{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new es(t)}node(){return this.node_}}class ts{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=N(this.path_,e);return new ts(this.syncTree_,t)}node(){return Mn(this.syncTree_,this.path_)}}const Bu=function(n){return n=n||{},n.timestamp=n.timestamp||new Date().getTime(),n},ar=function(n,e,t){if(!n||typeof n!="object")return n;if(f(".sv"in n,"Unexpected leaf node or priority contents"),typeof n[".sv"]=="string")return Hu(n[".sv"],e,t);if(typeof n[".sv"]=="object")return Vu(n[".sv"],e);f(!1,"Unexpected server value: "+JSON.stringify(n,null,2))},Hu=function(n,e,t){if(n==="timestamp")return t.timestamp;f(!1,"Unexpected server value: "+n)},Vu=function(n,e,t){n.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(n,null,2));const i=n.increment;typeof i!="number"&&f(!1,"Unexpected increment value: "+i);const s=e.node();if(f(s!==null&&typeof s<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!s.isLeafNode())return i;const o=s.getValue();return typeof o!="number"?i:o+i},Go=function(n,e,t,i){return is(e,new ts(t,n),i)},ns=function(n,e,t){return is(n,new es(e),t)};function is(n,e,t){const i=n.getPriority().val(),s=ar(i,e.getImmediateChild(".priority"),t);let r;if(n.isLeafNode()){const o=n,a=ar(o.getValue(),e,t);return a!==o.getValue()||s!==o.getPriority().val()?new O(a,k(s)):n}else{const o=n;return r=o,s!==o.getPriority().val()&&(r=r.updatePriority(new O(s))),o.forEachChild(R,(a,c)=>{const l=is(c,e.getImmediateChild(a),t);l!==c&&(r=r.updateImmediateChild(a,l))}),r}}class ss{constructor(e="",t=null,i={children:{},childCount:0}){this.name=e,this.parent=t,this.node=i}}function Ln(n,e){let t=e instanceof C?e:new C(e),i=n,s=y(t);for(;s!==null;){const r=De(i.node.children,s)||{children:{},childCount:0};i=new ss(s,i,r),t=S(t),s=y(t)}return i}function Ve(n){return n.node.value}function rs(n,e){n.node.value=e,Ci(n)}function zo(n){return n.node.childCount>0}function $u(n){return Ve(n)===void 0&&!zo(n)}function Fn(n,e){x(n.node.children,(t,i)=>{e(new ss(t,n,i))})}function jo(n,e,t,i){t&&e(n),Fn(n,s=>{jo(s,e,!0)})}function Gu(n,e,t){let i=n.parent;for(;i!==null;){if(e(i))return!0;i=i.parent}return!1}function Bt(n){return new C(n.parent===null?n.name:Bt(n.parent)+"/"+n.name)}function Ci(n){n.parent!==null&&zu(n.parent,n.name,n)}function zu(n,e,t){const i=$u(t),s=X(n.node.children,e);i&&s?(delete n.node.children[e],n.node.childCount--,Ci(n)):!i&&!s&&(n.node.children[e]=t.node,n.node.childCount++,Ci(n))}const ju=/[\[\].#$\/\u0000-\u001F\u007F]/,qu=/[\[\].#$\u0000-\u001F\u007F]/,ii=10*1024*1024,os=function(n){return typeof n=="string"&&n.length!==0&&!ju.test(n)},qo=function(n){return typeof n=="string"&&n.length!==0&&!qu.test(n)},Ku=function(n){return n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),qo(n)},as=function(n){return n===null||typeof n=="string"||typeof n=="number"&&!Nn(n)||n&&typeof n=="object"&&X(n,".sv")},In=function(n,e,t,i){i&&e===void 0||Ht(Qe(n,"value"),e,t)},Ht=function(n,e,t){const i=t instanceof C?new dh(t,n):t;if(e===void 0)throw new Error(n+"contains undefined "+Ae(i));if(typeof e=="function")throw new Error(n+"contains a function "+Ae(i)+" with contents = "+e.toString());if(Nn(e))throw new Error(n+"contains "+e.toString()+" "+Ae(i));if(typeof e=="string"&&e.length>ii/3&&kn(e)>ii)throw new Error(n+"contains a string greater than "+ii+" utf8 bytes "+Ae(i)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let s=!1,r=!1;if(x(e,(o,a)=>{if(o===".value")s=!0;else if(o!==".priority"&&o!==".sv"&&(r=!0,!os(o)))throw new Error(n+" contains an invalid key ("+o+") "+Ae(i)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);fh(i,o),Ht(n,a,i),ph(i)}),s&&r)throw new Error(n+' contains ".value" child '+Ae(i)+" in addition to actual children.")}},Yu=function(n,e){let t,i;for(t=0;t<e.length;t++){i=e[t];const r=Rt(i);for(let o=0;o<r.length;o++)if(!(r[o]===".priority"&&o===r.length-1)){if(!os(r[o]))throw new Error(n+"contains an invalid key ("+r[o]+") in path "+i.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}}e.sort(uh);let s=null;for(t=0;t<e.length;t++){if(i=e[t],s!==null&&G(s,i))throw new Error(n+"contains a path "+s.toString()+" that is ancestor of another path "+i.toString());s=i}},Ko=function(n,e,t,i){const s=Qe(n,"values");if(!(e&&typeof e=="object")||Array.isArray(e))throw new Error(s+" must be an object containing the children to replace.");const r=[];x(e,(o,a)=>{const c=new C(o);if(Ht(s,a,N(t,c)),Fi(c)===".priority"&&!as(a))throw new Error(s+"contains an invalid value for '"+c.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");r.push(c)}),Yu(s,r)},Qu=function(n,e,t){if(Nn(e))throw new Error(Qe(n,"priority")+"is "+e.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!as(e))throw new Error(Qe(n,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")},Yo=function(n,e,t,i){if(!qo(t))throw new Error(Qe(n,e)+'was an invalid path = "'+t+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Ju=function(n,e,t,i){t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),Yo(n,e,t)},_e=function(n,e){if(y(e)===".info")throw new Error(n+" failed = Can't modify data under /.info/")},Xu=function(n,e){const t=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!os(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||t.length!==0&&!Ku(t))throw new Error(Qe(n,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};class Zu{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Un(n,e){let t=null;for(let i=0;i<e.length;i++){const s=e[i],r=s.getPath();t!==null&&!Ui(r,t.path)&&(n.eventLists_.push(t),t=null),t===null&&(t={events:[],path:r}),t.events.push(s)}t&&n.eventLists_.push(t)}function Qo(n,e,t){Un(n,t),Jo(n,i=>Ui(i,e))}function V(n,e,t){Un(n,t),Jo(n,i=>G(i,e)||G(e,i))}function Jo(n,e){n.recursionDepth_++;let t=!0;for(let i=0;i<n.eventLists_.length;i++){const s=n.eventLists_[i];if(s){const r=s.path;e(r)?(ed(n.eventLists_[i]),n.eventLists_[i]=null):t=!1}}t&&(n.eventLists_=[]),n.recursionDepth_--}function ed(n){for(let e=0;e<n.events.length;e++){const t=n.events[e];if(t!==null){n.events[e]=null;const i=t.getEventRunner();yt&&M("event: "+t.toString()),ct(i)}}}const td="repo_interrupt",nd=25;class id{constructor(e,t,i,s){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=i,this.appCheckProvider_=s,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Zu,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=un(),this.transactionQueueTree_=new ss,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function sd(n,e,t){if(n.stats_=xi(n.repoInfo_),n.forceRestClient_||Ll())n.server_=new hn(n.repoInfo_,(i,s,r,o)=>{cr(n,i,s,r,o)},n.authTokenProvider_,n.appCheckProvider_),setTimeout(()=>lr(n,!0),0);else{if(typeof t<"u"&&t!==null){if(typeof t!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{P(t)}catch(i){throw new Error("Invalid authOverride provided: "+i)}}n.persistentConnection_=new re(n.repoInfo_,e,(i,s,r,o)=>{cr(n,i,s,r,o)},i=>{lr(n,i)},i=>{rd(n,i)},n.authTokenProvider_,n.appCheckProvider_,t),n.server_=n.persistentConnection_}n.authTokenProvider_.addTokenChangeListener(i=>{n.server_.refreshAuthToken(i)}),n.appCheckProvider_.addTokenChangeListener(i=>{n.server_.refreshAppCheckToken(i.token)}),n.statsReporter_=Hl(n.repoInfo_,()=>new Bh(n.stats_,n.server_)),n.infoData_=new xh,n.infoSyncTree_=new or({startListening:(i,s,r,o)=>{let a=[];const c=n.infoData_.getNode(i._path);return c.isEmpty()||(a=Wt(n.infoSyncTree_,i._path,c),setTimeout(()=>{o("ok")},0)),a},stopListening:()=>{}}),cs(n,"connected",!1),n.serverSyncTree_=new or({startListening:(i,s,r,o)=>(n.server_.listen(i,r,s,(a,c)=>{const l=o(a,c);V(n.eventQueue_,i._path,l)}),[]),stopListening:(i,s)=>{n.server_.unlisten(i,s)}})}function Xo(n){const t=n.infoData_.getNode(new C(".info/serverTimeOffset")).val()||0;return new Date().getTime()+t}function Vt(n){return Bu({timestamp:Xo(n)})}function cr(n,e,t,i,s){n.dataUpdateCount++;const r=new C(e);t=n.interceptServerDataCallback_?n.interceptServerDataCallback_(e,t):t;let o=[];if(s)if(i){const c=rn(t,l=>k(l));o=Mu(n.serverSyncTree_,r,c,s)}else{const c=k(t);o=Bo(n.serverSyncTree_,r,c,s)}else if(i){const c=rn(t,l=>k(l));o=Pu(n.serverSyncTree_,r,c)}else{const c=k(t);o=Wt(n.serverSyncTree_,r,c)}let a=r;o.length>0&&(a=nt(n,r)),V(n.eventQueue_,a,o)}function lr(n,e){cs(n,"connected",e),e===!1&&ld(n)}function rd(n,e){x(e,(t,i)=>{cs(n,t,i)})}function cs(n,e,t){const i=new C("/.info/"+e),s=k(t);n.infoData_.updateSnapshot(i,s);const r=Wt(n.infoSyncTree_,i,s);V(n.eventQueue_,i,r)}function Wn(n){return n.nextWriteId_++}function od(n,e,t){const i=xu(n.serverSyncTree_,e);return i!=null?Promise.resolve(i):n.server_.get(e).then(s=>{const r=k(s).withIndex(e._queryParams.getIndex());wi(n.serverSyncTree_,e,t,!0);let o;if(e._queryParams.loadsAllData())o=Wt(n.serverSyncTree_,e._path,r);else{const a=Ot(n.serverSyncTree_,e);o=Bo(n.serverSyncTree_,e._path,r,a)}return V(n.eventQueue_,e._path,o),vn(n.serverSyncTree_,e,t,null,!0),r},s=>(ut(n,"get for query "+P(e)+" failed: "+s),Promise.reject(new Error(s))))}function ad(n,e,t,i,s){ut(n,"set",{path:e.toString(),value:t,priority:i});const r=Vt(n),o=k(t,i),a=Mn(n.serverSyncTree_,e),c=ns(o,a,r),l=Wn(n),d=Qi(n.serverSyncTree_,e,c,l,!0);Un(n.eventQueue_,d),n.server_.put(e.toString(),o.val(!0),(u,p)=>{const _=u==="ok";_||U("set at "+e+" failed: "+u);const E=pe(n.serverSyncTree_,l,!_);V(n.eventQueue_,e,E),Se(n,s,u,p)});const h=hs(n,e);nt(n,h),V(n.eventQueue_,h,[])}function cd(n,e,t,i){ut(n,"update",{path:e.toString(),value:t});let s=!0;const r=Vt(n),o={};if(x(t,(a,c)=>{s=!1,o[a]=Go(N(e,a),k(c),n.serverSyncTree_,r)}),s)M("update() called with empty data. Don't do anything."),Se(n,i,"ok",void 0);else{const a=Wn(n),c=Au(n.serverSyncTree_,e,o,a);Un(n.eventQueue_,c),n.server_.merge(e.toString(),t,(l,d)=>{const h=l==="ok";h||U("update at "+e+" failed: "+l);const u=pe(n.serverSyncTree_,a,!h),p=u.length>0?nt(n,e):e;V(n.eventQueue_,p,u),Se(n,i,l,d)}),x(t,l=>{const d=hs(n,N(e,l));nt(n,d)}),V(n.eventQueue_,e,[])}}function ld(n){ut(n,"onDisconnectEvents");const e=Vt(n),t=un();gi(n.onDisconnect_,w(),(s,r)=>{const o=Go(s,r,n.serverSyncTree_,e);lt(t,s,o)});let i=[];gi(t,w(),(s,r)=>{i=i.concat(Wt(n.serverSyncTree_,s,r));const o=hs(n,s);nt(n,o)}),n.onDisconnect_=un(),V(n.eventQueue_,w(),i)}function hd(n,e,t){n.server_.onDisconnectCancel(e.toString(),(i,s)=>{i==="ok"&&_i(n.onDisconnect_,e),Se(n,t,i,s)})}function hr(n,e,t,i){const s=k(t);n.server_.onDisconnectPut(e.toString(),s.val(!0),(r,o)=>{r==="ok"&&lt(n.onDisconnect_,e,s),Se(n,i,r,o)})}function ud(n,e,t,i,s){const r=k(t,i);n.server_.onDisconnectPut(e.toString(),r.val(!0),(o,a)=>{o==="ok"&&lt(n.onDisconnect_,e,r),Se(n,s,o,a)})}function dd(n,e,t,i){if(sn(t)){M("onDisconnect().update() called with empty data. Don't do anything."),Se(n,i,"ok",void 0);return}n.server_.onDisconnectMerge(e.toString(),t,(s,r)=>{s==="ok"&&x(t,(o,a)=>{const c=k(a);lt(n.onDisconnect_,N(e,o),c)}),Se(n,i,s,r)})}function fd(n,e,t){let i;y(e._path)===".info"?i=wi(n.infoSyncTree_,e,t):i=wi(n.serverSyncTree_,e,t),Qo(n.eventQueue_,e._path,i)}function ur(n,e,t){let i;y(e._path)===".info"?i=vn(n.infoSyncTree_,e,t):i=vn(n.serverSyncTree_,e,t),Qo(n.eventQueue_,e._path,i)}function pd(n){n.persistentConnection_&&n.persistentConnection_.interrupt(td)}function ut(n,...e){let t="";n.persistentConnection_&&(t=n.persistentConnection_.id+":"),M(t,...e)}function Se(n,e,t,i){e&&ct(()=>{if(t==="ok")e(null);else{const s=(t||"error").toUpperCase();let r=s;i&&(r+=": "+i);const o=new Error(r);o.code=s,e(o)}})}function _d(n,e,t,i,s,r){ut(n,"transaction on "+e);const o={path:e,update:t,onComplete:i,status:null,order:Yr(),applyLocally:r,retryCount:0,unwatcher:s,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=ls(n,e,void 0);o.currentInputSnapshot=a;const c=o.update(a.val());if(c===void 0)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{Ht("transaction failed: Data returned ",c,o.path),o.status=0;const l=Ln(n.transactionQueueTree_,e),d=Ve(l)||[];d.push(o),rs(l,d);let h;typeof c=="object"&&c!==null&&X(c,".priority")?(h=De(c,".priority"),f(as(h),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):h=(Mn(n.serverSyncTree_,e)||g.EMPTY_NODE).getPriority().val();const u=Vt(n),p=k(c,h),_=ns(p,a,u);o.currentOutputSnapshotRaw=p,o.currentOutputSnapshotResolved=_,o.currentWriteId=Wn(n);const E=Qi(n.serverSyncTree_,e,_,o.currentWriteId,o.applyLocally);V(n.eventQueue_,e,E),Bn(n,n.transactionQueueTree_)}}function ls(n,e,t){return Mn(n.serverSyncTree_,e,t)||g.EMPTY_NODE}function Bn(n,e=n.transactionQueueTree_){if(e||Hn(n,e),Ve(e)){const t=ea(n,e);f(t.length>0,"Sending zero length transaction queue"),t.every(s=>s.status===0)&&gd(n,Bt(e),t)}else zo(e)&&Fn(e,t=>{Bn(n,t)})}function gd(n,e,t){const i=t.map(l=>l.currentWriteId),s=ls(n,e,i);let r=s;const o=s.hash();for(let l=0;l<t.length;l++){const d=t[l];f(d.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),d.status=1,d.retryCount++;const h=F(e,d.path);r=r.updateChild(h,d.currentOutputSnapshotRaw)}const a=r.val(!0),c=e;n.server_.put(c.toString(),a,l=>{ut(n,"transaction put response",{path:c.toString(),status:l});let d=[];if(l==="ok"){const h=[];for(let u=0;u<t.length;u++)t[u].status=2,d=d.concat(pe(n.serverSyncTree_,t[u].currentWriteId)),t[u].onComplete&&h.push(()=>t[u].onComplete(null,!0,t[u].currentOutputSnapshotResolved)),t[u].unwatcher();Hn(n,Ln(n.transactionQueueTree_,e)),Bn(n,n.transactionQueueTree_),V(n.eventQueue_,e,d);for(let u=0;u<h.length;u++)ct(h[u])}else{if(l==="datastale")for(let h=0;h<t.length;h++)t[h].status===3?t[h].status=4:t[h].status=0;else{U("transaction at "+c.toString()+" failed: "+l);for(let h=0;h<t.length;h++)t[h].status=4,t[h].abortReason=l}nt(n,e)}},o)}function nt(n,e){const t=Zo(n,e),i=Bt(t),s=ea(n,t);return md(n,s,i),i}function md(n,e,t){if(e.length===0)return;const i=[];let s=[];const o=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){const c=e[a],l=F(t,c.path);let d=!1,h;if(f(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)d=!0,h=c.abortReason,s=s.concat(pe(n.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=nd)d=!0,h="maxretry",s=s.concat(pe(n.serverSyncTree_,c.currentWriteId,!0));else{const u=ls(n,c.path,o);c.currentInputSnapshot=u;const p=e[a].update(u.val());if(p!==void 0){Ht("transaction failed: Data returned ",p,c.path);let _=k(p);typeof p=="object"&&p!=null&&X(p,".priority")||(_=_.updatePriority(u.getPriority()));const A=c.currentWriteId,H=Vt(n),z=ns(_,u,H);c.currentOutputSnapshotRaw=_,c.currentOutputSnapshotResolved=z,c.currentWriteId=Wn(n),o.splice(o.indexOf(A),1),s=s.concat(Qi(n.serverSyncTree_,c.path,z,c.currentWriteId,c.applyLocally)),s=s.concat(pe(n.serverSyncTree_,A,!0))}else d=!0,h="nodata",s=s.concat(pe(n.serverSyncTree_,c.currentWriteId,!0))}V(n.eventQueue_,t,s),s=[],d&&(e[a].status=2,(function(u){setTimeout(u,Math.floor(0))})(e[a].unwatcher),e[a].onComplete&&(h==="nodata"?i.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):i.push(()=>e[a].onComplete(new Error(h),!1,null))))}Hn(n,n.transactionQueueTree_);for(let a=0;a<i.length;a++)ct(i[a]);Bn(n,n.transactionQueueTree_)}function Zo(n,e){let t,i=n.transactionQueueTree_;for(t=y(e);t!==null&&Ve(i)===void 0;)i=Ln(i,t),e=S(e),t=y(e);return i}function ea(n,e){const t=[];return ta(n,e,t),t.sort((i,s)=>i.order-s.order),t}function ta(n,e,t){const i=Ve(e);if(i)for(let s=0;s<i.length;s++)t.push(i[s]);Fn(e,s=>{ta(n,s,t)})}function Hn(n,e){const t=Ve(e);if(t){let i=0;for(let s=0;s<t.length;s++)t[s].status!==2&&(t[i]=t[s],i++);t.length=i,rs(e,t.length>0?t:void 0)}Fn(e,i=>{Hn(n,i)})}function hs(n,e){const t=Bt(Zo(n,e)),i=Ln(n.transactionQueueTree_,e);return Gu(i,s=>{si(n,s)}),si(n,i),jo(i,s=>{si(n,s)}),t}function si(n,e){const t=Ve(e);if(t){const i=[];let s=[],r=-1;for(let o=0;o<t.length;o++)t[o].status===3||(t[o].status===1?(f(r===o-1,"All SENT items should be at beginning of queue."),r=o,t[o].status=3,t[o].abortReason="set"):(f(t[o].status===0,"Unexpected transaction status in abort"),t[o].unwatcher(),s=s.concat(pe(n.serverSyncTree_,t[o].currentWriteId,!0)),t[o].onComplete&&i.push(t[o].onComplete.bind(null,new Error("set"),!1,null))));r===-1?rs(e,void 0):t.length=r+1,V(n.eventQueue_,Bt(e),s);for(let o=0;o<i.length;o++)ct(i[o])}}function yd(n){let e="";const t=n.split("/");for(let i=0;i<t.length;i++)if(t[i].length>0){let s=t[i];try{s=decodeURIComponent(s.replace(/\+/g," "))}catch{}e+="/"+s}return e}function vd(n){const e={};n.charAt(0)==="?"&&(n=n.substring(1));for(const t of n.split("&")){if(t.length===0)continue;const i=t.split("=");i.length===2?e[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):U(`Invalid query segment '${t}' in query '${n}'`)}return e}const dr=function(n,e){const t=Id(n),i=t.namespace;t.domain==="firebase.com"&&ae(t.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!i||i==="undefined")&&t.domain!=="localhost"&&ae("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),t.secure||Rl();const s=t.scheme==="ws"||t.scheme==="wss";return{repoInfo:new co(t.host,t.secure,i,s,e,"",i!==t.subdomain),path:new C(t.pathString)}},Id=function(n){let e="",t="",i="",s="",r="",o=!0,a="https",c=443;if(typeof n=="string"){let l=n.indexOf("//");l>=0&&(a=n.substring(0,l-1),n=n.substring(l+2));let d=n.indexOf("/");d===-1&&(d=n.length);let h=n.indexOf("?");h===-1&&(h=n.length),e=n.substring(0,Math.min(d,h)),d<h&&(s=yd(n.substring(d,h)));const u=vd(n.substring(Math.min(n.length,h)));l=e.indexOf(":"),l>=0?(o=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;const p=e.slice(0,l);if(p.toLowerCase()==="localhost")t="localhost";else if(p.split(".").length<=2)t=p;else{const _=e.indexOf(".");i=e.substring(0,_).toLowerCase(),t=e.substring(_+1),r=i}"ns"in u&&(r=u.ns)}return{host:e,port:c,domain:t,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}};const fr="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Ed=(function(){let n=0;const e=[];return function(t){const i=t===n;n=t;let s;const r=new Array(8);for(s=7;s>=0;s--)r[s]=fr.charAt(t%64),t=Math.floor(t/64);f(t===0,"Cannot push at time == 0");let o=r.join("");if(i){for(s=11;s>=0&&e[s]===63;s--)e[s]=0;e[s]++}else for(s=0;s<12;s++)e[s]=Math.floor(Math.random()*64);for(s=0;s<12;s++)o+=fr.charAt(e[s]);return f(o.length===20,"nextPushId: Length should be 20."),o}})();class wd{constructor(e,t,i,s){this.eventType=e,this.eventRegistration=t,this.snapshot=i,this.prevName=s}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+P(this.snapshot.exportVal())}}class Cd{constructor(e,t,i){this.eventRegistration=e,this.error=t,this.path=i}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class na{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class Td{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new j;return hd(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){_e("OnDisconnect.remove",this._path);const e=new j;return hr(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){_e("OnDisconnect.set",this._path),In("OnDisconnect.set",e,this._path,!1);const t=new j;return hr(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){_e("OnDisconnect.setWithPriority",this._path),In("OnDisconnect.setWithPriority",e,this._path,!1),Qu("OnDisconnect.setWithPriority",t);const i=new j;return ud(this._repo,this._path,e,t,i.wrapCallback(()=>{})),i.promise}update(e){_e("OnDisconnect.update",this._path),Ko("OnDisconnect.update",e,this._path);const t=new j;return dd(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class us{constructor(e,t,i,s){this._repo=e,this._path=t,this._queryParams=i,this._orderByCalled=s}get key(){return v(this._path)?null:Fi(this._path)}get ref(){return new te(this._repo,this._path)}get _queryIdentifier(){const e=Qs(this._queryParams),t=Di(e);return t==="{}"?"default":t}get _queryObject(){return Qs(this._queryParams)}isEqual(e){if(e=L(e),!(e instanceof us))return!1;const t=this._repo===e._repo,i=Ui(this._path,e._path),s=this._queryIdentifier===e._queryIdentifier;return t&&i&&s}toJSON(){return this.toString()}toString(){return this._repo.toString()+hh(this._path)}}class te extends us{constructor(e,t){super(e,t,new Vi,!1)}get parent(){const e=yo(this._path);return e===null?null:new te(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class it{constructor(e,t,i){this._node=e,this.ref=t,this._index=i}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new C(e),i=Dt(this.ref,e);return new it(this._node.getChild(t),i,R)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(i,s)=>e(new it(s,Dt(this.ref,i),R)))}hasChild(e){const t=new C(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Fp(n,e){return n=L(n),n._checkNotDeleted("ref"),e!==void 0?Dt(n._root,e):n._root}function Dt(n,e){return n=L(n),y(n._path)===null?Ju("child","path",e):Yo("child","path",e),new te(n._repo,N(n._path,e))}function Up(n){return n=L(n),new Td(n._repo,n._path)}function Wp(n,e){n=L(n),_e("push",n._path),In("push",e,n._path,!0);const t=Xo(n._repo),i=Ed(t),s=Dt(n,i),r=Dt(n,i);let o;return e!=null?o=ia(r,e).then(()=>r):o=Promise.resolve(r),s.then=o.then.bind(o),s.catch=o.then.bind(o,void 0),s}function Bp(n){return _e("remove",n._path),ia(n,null)}function ia(n,e){n=L(n),_e("set",n._path),In("set",e,n._path,!1);const t=new j;return ad(n._repo,n._path,e,null,t.wrapCallback(()=>{})),t.promise}function Hp(n,e){Ko("update",e,n._path);const t=new j;return cd(n._repo,n._path,e,t.wrapCallback(()=>{})),t.promise}function Vp(n){n=L(n);const e=new na(()=>{}),t=new Vn(e);return od(n._repo,n,t).then(i=>new it(i,new te(n._repo,n._path),n._queryParams.getIndex()))}class Vn{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,t){const i=t._queryParams.getIndex();return new wd("value",this,new it(e.snapshotNode,new te(t._repo,t._path),i))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new Cd(this,e,t):null}matches(e){return e instanceof Vn?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}function Sd(n,e,t,i,s){let r;if(typeof i=="object"&&(r=void 0,s=i),typeof i=="function"&&(r=i),s&&s.onlyOnce){const c=t,l=(d,h)=>{ur(n._repo,n,a),c(d,h)};l.userCallback=t.userCallback,l.context=t.context,t=l}const o=new na(t,r||void 0),a=new Vn(o);return fd(n._repo,n,a),()=>ur(n._repo,n,a)}function bd(n,e,t,i){return Sd(n,"value",e,t,i)}wu(te);Ru(te);const Rd="FIREBASE_DATABASE_EMULATOR_HOST",Ti={};let kd=!1;function Nd(n,e,t,i){const s=e.lastIndexOf(":"),r=e.substring(0,s),o=rt(r);n.repoInfo_=new co(e,o,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),i&&(n.authTokenProvider_=i)}function Ad(n,e,t,i,s){let r=i||n.options.databaseURL;r===void 0&&(n.options.projectId||ae("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),M("Using default host for project ",n.options.projectId),r=`${n.options.projectId}-default-rtdb.firebaseio.com`);let o=dr(r,s),a=o.repoInfo,c;typeof process<"u"&&Os&&(c=Os[Rd]),c?(r=`http://${c}?ns=${a.namespace}`,o=dr(r,s),a=o.repoInfo):o.repoInfo.secure;const l=new Ul(n.name,n.options,e);Xu("Invalid Firebase Database URL",o),v(o.path)||ae("Database URL must point to the root of a Firebase Database (not including a child path).");const d=Od(a,n,l,new Fl(n,t));return new Dd(d,n)}function Pd(n,e){const t=Ti[e];(!t||t[n.key]!==n)&&ae(`Database ${e}(${n.repoInfo_}) has already been deleted.`),pd(n),delete t[n.key]}function Od(n,e,t,i){let s=Ti[e.name];s||(s={},Ti[e.name]=s);let r=s[n.toURLString()];return r&&ae("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new id(n,kd,t,i),s[n.toURLString()]=r,r}class Dd{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(sd(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new te(this._repo,w())),this._rootInternal}_delete(){return this._rootInternal!==null&&(Pd(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&ae("Cannot call "+e+" on a deleted database.")}}function $p(n=Gr(),e){const t=Oi(n,"database").getImmediate({identifier:e});if(!t._instanceStarted){const i=Ga("database");i&&Md(t,...i)}return t}function Md(n,e,t,i={}){n=L(n),n._checkNotDeleted("useEmulator");const s=`${e}:${t}`,r=n._repoInternal;if(n._instanceStarted){if(s===n._repoInternal.repoInfo_.host&&Me(i,r.repoInfo_.emulatorOptions))return;ae("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o;if(r.repoInfo_.nodeAdmin)i.mockUserToken&&ae('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Qt(Qt.OWNER);else if(i.mockUserToken){const a=typeof i.mockUserToken=="string"?i.mockUserToken:za(i.mockUserToken,n.app.options.projectId);o=new Qt(a)}rt(e)&&(Ur(e),Wr("Database",!0)),Nd(r,s,i,o)}function xd(n){wl(at),Je(new xe("database",(e,{instanceIdentifier:t})=>{const i=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return Ad(i,s,r,t)},"PUBLIC").setMultipleInstances(!0)),ye(Ds,Ms,n),ye(Ds,Ms,"esm2020")}const Ld={".sv":"timestamp"};function Gp(){return Ld}class Fd{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function zp(n,e,t){if(n=L(n),_e("Reference.transaction",n._path),n.key===".length"||n.key===".keys")throw"Reference.transaction failed: "+n.key+" is a read-only object.";const i=!0,s=new j,r=(a,c,l)=>{let d=null;a?s.reject(a):(d=new it(l,new te(n._repo,n._path),R),s.resolve(new Fd(c,d)))},o=bd(n,()=>{});return _d(n._repo,n._path,e,r,o,i),s.promise}re.prototype.simpleListen=function(n,e){this.sendRequest("q",{p:n},e)};re.prototype.echo=function(n,e){this.sendRequest("echo",{d:n},e)};xd();function sa(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const Ud=sa,ra=new xt("auth","Firebase",sa());const En=new Ai("@firebase/auth");function Wd(n,...e){En.logLevel<=T.WARN&&En.warn(`Auth (${at}): ${n}`,...e)}function Jt(n,...e){En.logLevel<=T.ERROR&&En.error(`Auth (${at}): ${n}`,...e)}function ee(n,...e){throw fs(n,...e)}function J(n,...e){return fs(n,...e)}function ds(n,e,t){const i={...Ud(),[e]:t};return new xt("auth","Firebase",i).create(e,{appName:n.name})}function Ee(n){return ds(n,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Bd(n,e,t){const i=t;if(!(e instanceof i))throw i.name!==e.constructor.name&&ee(n,"argument-error"),ds(n,"argument-error",`Type of ${e.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function fs(n,...e){if(typeof n!="string"){const t=e[0],i=[...e.slice(1)];return i[0]&&(i[0].appName=n.name),n._errorFactory.create(t,...i)}return ra.create(n,...e)}function m(n,e,...t){if(!n)throw fs(e,...t)}function ie(n){const e="INTERNAL ASSERTION FAILED: "+n;throw Jt(e),new Error(e)}function ce(n,e){n||ie(e)}function Si(){return typeof self<"u"&&self.location?.href||""}function Hd(){return pr()==="http:"||pr()==="https:"}function pr(){return typeof self<"u"&&self.location?.protocol||null}function Vd(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(Hd()||Qa()||"connection"in navigator)?navigator.onLine:!0}function $d(){if(typeof navigator>"u")return null;const n=navigator;return n.languages&&n.languages[0]||n.language||null}class $t{constructor(e,t){this.shortDelay=e,this.longDelay=t,ce(t>e,"Short delay should be less than long delay!"),this.isMobile=Ni()||Br()}get(){return Vd()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function ps(n,e){ce(n.emulator,"Emulator should always be set here");const{url:t}=n.emulator;return e?`${t}${e.startsWith("/")?e.slice(1):e}`:t}class oa{static initialize(e,t,i){this.fetchImpl=e,t&&(this.headersImpl=t),i&&(this.responseImpl=i)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;ie("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;ie("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;ie("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const Gd={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};const zd=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],jd=new $t(3e4,6e4);function $n(n,e){return n.tenantId&&!e.tenantId?{...e,tenantId:n.tenantId}:e}async function dt(n,e,t,i,s={}){return aa(n,s,async()=>{let r={},o={};i&&(e==="GET"?o=i:r={body:JSON.stringify(i)});const a=ot({key:n.config.apiKey,...o}).slice(1),c=await n._getAdditionalHeaders();c["Content-Type"]="application/json",n.languageCode&&(c["X-Firebase-Locale"]=n.languageCode);const l={method:e,headers:c,...r};return Ya()||(l.referrerPolicy="no-referrer"),n.emulatorConfig&&rt(n.emulatorConfig.host)&&(l.credentials="include"),oa.fetch()(await la(n,n.config.apiHost,t,a),l)})}async function aa(n,e,t){n._canInitEmulator=!1;const i={...Gd,...e};try{const s=new qd(n),r=await Promise.race([t(),s.promise]);s.clearNetworkTimeout();const o=await r.json();if("needConfirmation"in o)throw Yt(n,"account-exists-with-different-credential",o);if(r.ok&&!("errorMessage"in o))return o;{const a=r.ok?o.errorMessage:o.error.message,[c,l]=a.split(" : ");if(c==="FEDERATED_USER_ID_ALREADY_LINKED")throw Yt(n,"credential-already-in-use",o);if(c==="EMAIL_EXISTS")throw Yt(n,"email-already-in-use",o);if(c==="USER_DISABLED")throw Yt(n,"user-disabled",o);const d=i[c]||c.toLowerCase().replace(/[_\s]+/g,"-");if(l)throw ds(n,d,l);ee(n,d)}}catch(s){if(s instanceof Re)throw s;ee(n,"network-request-failed",{message:String(s)})}}async function ca(n,e,t,i,s={}){const r=await dt(n,e,t,i,s);return"mfaPendingCredential"in r&&ee(n,"multi-factor-auth-required",{_serverResponse:r}),r}async function la(n,e,t,i){const s=`${e}${t}?${i}`,r=n,o=r.config.emulator?ps(n.config,s):`${n.config.apiScheme}://${s}`;return zd.includes(t)&&(await r._persistenceManagerAvailable,r._getPersistenceType()==="COOKIE")?r._getPersistence()._getFinalTarget(o).toString():o}class qd{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((t,i)=>{this.timer=setTimeout(()=>i(J(this.auth,"network-request-failed")),jd.get())})}}function Yt(n,e,t){const i={appName:n.name};t.email&&(i.email=t.email),t.phoneNumber&&(i.phoneNumber=t.phoneNumber);const s=J(n,e,i);return s.customData._tokenResponse=t,s}async function Kd(n,e){return dt(n,"POST","/v1/accounts:delete",e)}async function wn(n,e){return dt(n,"POST","/v1/accounts:lookup",e)}function Ct(n){if(n)try{const e=new Date(Number(n));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function Yd(n,e=!1){const t=L(n),i=await t.getIdToken(e),s=_s(i);m(s&&s.exp&&s.auth_time&&s.iat,t.auth,"internal-error");const r=typeof s.firebase=="object"?s.firebase:void 0,o=r?.sign_in_provider;return{claims:s,token:i,authTime:Ct(ri(s.auth_time)),issuedAtTime:Ct(ri(s.iat)),expirationTime:Ct(ri(s.exp)),signInProvider:o||null,signInSecondFactor:r?.sign_in_second_factor||null}}function ri(n){return Number(n)*1e3}function _s(n){const[e,t,i]=n.split(".");if(e===void 0||t===void 0||i===void 0)return Jt("JWT malformed, contained fewer than 3 sections"),null;try{const s=nn(t);return s?JSON.parse(s):(Jt("Failed to decode base64 JWT payload"),null)}catch(s){return Jt("Caught error parsing JWT payload as JSON",s?.toString()),null}}function _r(n){const e=_s(n);return m(e,"internal-error"),m(typeof e.exp<"u","internal-error"),m(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Mt(n,e,t=!1){if(t)return e;try{return await e}catch(i){throw i instanceof Re&&Qd(i)&&n.auth.currentUser===n&&await n.auth.signOut(),i}}function Qd({code:n}){return n==="auth/user-disabled"||n==="auth/user-token-expired"}class Jd{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){const t=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),t}else{this.errorBackoff=3e4;const i=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,i)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class bi{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ct(this.lastLoginAt),this.creationTime=Ct(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Cn(n){const e=n.auth,t=await n.getIdToken(),i=await Mt(n,wn(e,{idToken:t}));m(i?.users.length,e,"internal-error");const s=i.users[0];n._notifyReloadListener(s);const r=s.providerUserInfo?.length?ha(s.providerUserInfo):[],o=Zd(n.providerData,r),a=n.isAnonymous,c=!(n.email&&s.passwordHash)&&!o?.length,l=a?c:!1,d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:o,metadata:new bi(s.createdAt,s.lastLoginAt),isAnonymous:l};Object.assign(n,d)}async function Xd(n){const e=L(n);await Cn(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function Zd(n,e){return[...n.filter(i=>!e.some(s=>s.providerId===i.providerId)),...e]}function ha(n){return n.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function ef(n,e){const t=await aa(n,{},async()=>{const i=ot({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:r}=n.config,o=await la(n,s,"/v1/token",`key=${r}`),a=await n._getAdditionalHeaders();a["Content-Type"]="application/x-www-form-urlencoded";const c={method:"POST",headers:a,body:i};return n.emulatorConfig&&rt(n.emulatorConfig.host)&&(c.credentials="include"),oa.fetch()(o,c)});return{accessToken:t.access_token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}async function tf(n,e){return dt(n,"POST","/v2/accounts:revokeToken",$n(n,e))}class qe{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){m(e.idToken,"internal-error"),m(typeof e.idToken<"u","internal-error"),m(typeof e.refreshToken<"u","internal-error");const t="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):_r(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){m(e.length!==0,"internal-error");const t=_r(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(m(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:i,refreshToken:s,expiresIn:r}=await ef(e,t);this.updateTokensAndExpiration(i,s,Number(r))}updateTokensAndExpiration(e,t,i){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+i*1e3}static fromJSON(e,t){const{refreshToken:i,accessToken:s,expirationTime:r}=t,o=new qe;return i&&(m(typeof i=="string","internal-error",{appName:e}),o.refreshToken=i),s&&(m(typeof s=="string","internal-error",{appName:e}),o.accessToken=s),r&&(m(typeof r=="number","internal-error",{appName:e}),o.expirationTime=r),o}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new qe,this.toJSON())}_performRefresh(){return ie("not implemented")}}function le(n,e){m(typeof n=="string"||typeof n>"u","internal-error",{appName:e})}class Y{constructor({uid:e,auth:t,stsTokenManager:i,...s}){this.providerId="firebase",this.proactiveRefresh=new Jd(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new bi(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Mt(this,this.stsTokenManager.getToken(this.auth,e));return m(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return Yd(this,e)}reload(){return Xd(this)}_assign(e){this!==e&&(m(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(t=>({...t})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Y({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){m(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let i=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),i=!0),t&&await Cn(this),await this.auth._persistUserIfCurrent(this),i&&this.auth._notifyListenersIfCurrent(this)}async delete(){if($(this.auth.app))return Promise.reject(Ee(this.auth));const e=await this.getIdToken();return await Mt(this,Kd(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const i=t.displayName??void 0,s=t.email??void 0,r=t.phoneNumber??void 0,o=t.photoURL??void 0,a=t.tenantId??void 0,c=t._redirectEventId??void 0,l=t.createdAt??void 0,d=t.lastLoginAt??void 0,{uid:h,emailVerified:u,isAnonymous:p,providerData:_,stsTokenManager:E}=t;m(h&&E,e,"internal-error");const A=qe.fromJSON(this.name,E);m(typeof h=="string",e,"internal-error"),le(i,e.name),le(s,e.name),m(typeof u=="boolean",e,"internal-error"),m(typeof p=="boolean",e,"internal-error"),le(r,e.name),le(o,e.name),le(a,e.name),le(c,e.name),le(l,e.name),le(d,e.name);const H=new Y({uid:h,auth:e,email:s,emailVerified:u,displayName:i,isAnonymous:p,photoURL:o,phoneNumber:r,tenantId:a,stsTokenManager:A,createdAt:l,lastLoginAt:d});return _&&Array.isArray(_)&&(H.providerData=_.map(z=>({...z}))),c&&(H._redirectEventId=c),H}static async _fromIdTokenResponse(e,t,i=!1){const s=new qe;s.updateFromServerResponse(t);const r=new Y({uid:t.localId,auth:e,stsTokenManager:s,isAnonymous:i});return await Cn(r),r}static async _fromGetAccountInfoResponse(e,t,i){const s=t.users[0];m(s.localId!==void 0,"internal-error");const r=s.providerUserInfo!==void 0?ha(s.providerUserInfo):[],o=!(s.email&&s.passwordHash)&&!r?.length,a=new qe;a.updateFromIdToken(i);const c=new Y({uid:s.localId,auth:e,stsTokenManager:a,isAnonymous:o}),l={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:r,metadata:new bi(s.createdAt,s.lastLoginAt),isAnonymous:!(s.email&&s.passwordHash)&&!r?.length};return Object.assign(c,l),c}}const gr=new Map;function se(n){ce(n instanceof Function,"Expected a class definition");let e=gr.get(n);return e?(ce(e instanceof n,"Instance stored in cache mismatched with class"),e):(e=new n,gr.set(n,e),e)}class ua{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}ua.type="NONE";const mr=ua;function Xt(n,e,t){return`firebase:${n}:${e}:${t}`}class Ke{constructor(e,t,i){this.persistence=e,this.auth=t,this.userKey=i;const{config:s,name:r}=this.auth;this.fullUserKey=Xt(this.userKey,s.apiKey,r),this.fullPersistenceKey=Xt("persistence",s.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){const t=await wn(this.auth,{idToken:e}).catch(()=>{});return t?Y._fromGetAccountInfoResponse(this.auth,t,e):null}return Y._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,i="authUser"){if(!t.length)return new Ke(se(mr),e,i);const s=(await Promise.all(t.map(async l=>{if(await l._isAvailable())return l}))).filter(l=>l);let r=s[0]||se(mr);const o=Xt(i,e.config.apiKey,e.name);let a=null;for(const l of t)try{const d=await l._get(o);if(d){let h;if(typeof d=="string"){const u=await wn(e,{idToken:d}).catch(()=>{});if(!u)break;h=await Y._fromGetAccountInfoResponse(e,u,d)}else h=Y._fromJSON(e,d);l!==r&&(a=h),r=l;break}}catch{}const c=s.filter(l=>l._shouldAllowMigration);return!r._shouldAllowMigration||!c.length?new Ke(r,e,i):(r=c[0],a&&await r._set(o,a.toJSON()),await Promise.all(t.map(async l=>{if(l!==r)try{await l._remove(o)}catch{}})),new Ke(r,e,i))}}function yr(n){const e=n.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(_a(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(da(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(ma(e))return"Blackberry";if(ya(e))return"Webos";if(fa(e))return"Safari";if((e.includes("chrome/")||pa(e))&&!e.includes("edge/"))return"Chrome";if(ga(e))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,i=n.match(t);if(i?.length===2)return i[1]}return"Other"}function da(n=W()){return/firefox\//i.test(n)}function fa(n=W()){const e=n.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function pa(n=W()){return/crios\//i.test(n)}function _a(n=W()){return/iemobile/i.test(n)}function ga(n=W()){return/android/i.test(n)}function ma(n=W()){return/blackberry/i.test(n)}function ya(n=W()){return/webos/i.test(n)}function gs(n=W()){return/iphone|ipad|ipod/i.test(n)||/macintosh/i.test(n)&&/mobile/i.test(n)}function nf(n=W()){return gs(n)&&!!window.navigator?.standalone}function sf(){return Ja()&&document.documentMode===10}function va(n=W()){return gs(n)||ga(n)||ya(n)||ma(n)||/windows phone/i.test(n)||_a(n)}function Ia(n,e=[]){let t;switch(n){case"Browser":t=yr(W());break;case"Worker":t=`${yr(W())}-${n}`;break;default:t=n}const i=e.length?e.join(","):"FirebaseCore-web";return`${t}/JsCore/${at}/${i}`}class rf{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const i=r=>new Promise((o,a)=>{try{const c=e(r);o(c)}catch(c){a(c)}});i.onAbort=t,this.queue.push(i);const s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const i of this.queue)await i(e),i.onAbort&&t.push(i.onAbort)}catch(i){t.reverse();for(const s of t)try{s()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:i?.message})}}}async function of(n,e={}){return dt(n,"GET","/v2/passwordPolicy",$n(n,e))}const af=6;class cf{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??af,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),t.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),t.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),t.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),t.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const i=this.customStrengthOptions.minPasswordLength,s=this.customStrengthOptions.maxPasswordLength;i&&(t.meetsMinPasswordLength=e.length>=i),s&&(t.meetsMaxPasswordLength=e.length<=s)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let i;for(let s=0;s<e.length;s++)i=e.charAt(s),this.updatePasswordCharacterOptionsStatuses(t,i>="a"&&i<="z",i>="A"&&i<="Z",i>="0"&&i<="9",this.allowedNonAlphanumericCharacters.includes(i))}updatePasswordCharacterOptionsStatuses(e,t,i,s,r){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=i)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=s)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=r))}}class lf{constructor(e,t,i,s){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=i,this.config=s,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new vr(this),this.idTokenSubscription=new vr(this),this.beforeStateQueue=new rf(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=ra,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=s.sdkClientVersion,this._persistenceManagerAvailable=new Promise(r=>this._resolvePersistenceManagerAvailable=r)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=se(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Ke.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const t=await wn(this,{idToken:e}),i=await Y._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(i)}catch(t){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",t),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if($(this.app)){const r=this.app.settings.authIdToken;return r?new Promise(o=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(r).then(o,o))}):this.directlySetCurrentUser(null)}const t=await this.assertedPersistence.getCurrentUser();let i=t,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const r=this.redirectUser?._redirectEventId,o=i?._redirectEventId,a=await this.tryRedirectSignIn(e);(!r||r===o)&&a?.user&&(i=a.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(r){i=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(r))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return m(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Cn(e)}catch(t){if(t?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=$d()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if($(this.app))return Promise.reject(Ee(this));const t=e?L(e):null;return t&&m(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&m(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return $(this.app)?Promise.reject(Ee(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return $(this.app)?Promise.reject(Ee(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(se(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await of(this),t=new cf(e);this.tenantId===null?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new xt("auth","Firebase",e())}onAuthStateChanged(e,t,i){return this.registerStateListener(this.authStateSubscription,e,t,i)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,i){return this.registerStateListener(this.idTokenSubscription,e,t,i)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const i=this.onAuthStateChanged(()=>{i(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken(),i={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};this.tenantId!=null&&(i.tenantId=this.tenantId),await tf(this,i)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const i=await this.getOrInitRedirectPersistenceManager(t);return e===null?i.removeCurrentUser():i.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&se(e)||this._popupRedirectResolver;m(t,this,"argument-error"),this.redirectPersistenceManager=await Ke.create(this,[se(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,i,s){if(this._deleted)return()=>{};const r=typeof t=="function"?t:t.next.bind(t);let o=!1;const a=this._isInitialized?Promise.resolve():this._initializationPromise;if(m(a,this,"internal-error"),a.then(()=>{o||r(this.currentUser)}),typeof t=="function"){const c=e.addObserver(t,i,s);return()=>{o=!0,c()}}else{const c=e.addObserver(t);return()=>{o=!0,c()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return m(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Ia(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);const i=await this._getAppCheckToken();return i&&(e["X-Firebase-AppCheck"]=i),e}async _getAppCheckToken(){if($(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Wd(`Error while retrieving App Check token: ${e.error}`),e?.token}}function Gt(n){return L(n)}class vr{constructor(e){this.auth=e,this.observer=null,this.addObserver=ac(t=>this.observer=t)}get next(){return m(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let ms={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function hf(n){ms=n}function uf(n){return ms.loadJS(n)}function df(){return ms.gapiScript}function ff(n){return`__${n}${Math.floor(Math.random()*1e6)}`}function pf(n,e){const t=Oi(n,"auth");if(t.isInitialized()){const s=t.getImmediate(),r=t.getOptions();if(Me(r,e??{}))return s;ee(s,"already-initialized")}return t.initialize({options:e})}function _f(n,e){const t=e?.persistence||[],i=(Array.isArray(t)?t:[t]).map(se);e?.errorMap&&n._updateErrorMap(e.errorMap),n._initializeWithPersistence(i,e?.popupRedirectResolver)}function gf(n,e,t){const i=Gt(n);m(/^https?:\/\//.test(e),i,"invalid-emulator-scheme");const s=!1,r=Ea(e),{host:o,port:a}=mf(e),c=a===null?"":`:${a}`,l={url:`${r}//${o}${c}/`},d=Object.freeze({host:o,port:a,protocol:r.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!i._canInitEmulator){m(i.config.emulator&&i.emulatorConfig,i,"emulator-config-failed"),m(Me(l,i.config.emulator)&&Me(d,i.emulatorConfig),i,"emulator-config-failed");return}i.config.emulator=l,i.emulatorConfig=d,i.settings.appVerificationDisabledForTesting=!0,rt(o)?(Ur(`${r}//${o}${c}`),Wr("Auth",!0)):yf()}function Ea(n){const e=n.indexOf(":");return e<0?"":n.substr(0,e+1)}function mf(n){const e=Ea(n),t=/(\/\/)?([^?#/]+)/.exec(n.substr(e.length));if(!t)return{host:"",port:null};const i=t[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(i);if(s){const r=s[1];return{host:r,port:Ir(i.substr(r.length+1))}}else{const[r,o]=i.split(":");return{host:r,port:Ir(o)}}}function Ir(n){if(!n)return null;const e=Number(n);return isNaN(e)?null:e}function yf(){function n(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",n):n())}class wa{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return ie("not implemented")}_getIdTokenResponse(e){return ie("not implemented")}_linkToIdToken(e,t){return ie("not implemented")}_getReauthenticationResolver(e){return ie("not implemented")}}async function Ye(n,e){return ca(n,"POST","/v1/accounts:signInWithIdp",$n(n,e))}const vf="http://localhost";class We extends wa{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new We(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):ee("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e,{providerId:i,signInMethod:s,...r}=t;if(!i||!s)return null;const o=new We(i,s);return o.idToken=r.idToken||void 0,o.accessToken=r.accessToken||void 0,o.secret=r.secret,o.nonce=r.nonce,o.pendingToken=r.pendingToken||null,o}_getIdTokenResponse(e){const t=this.buildRequest();return Ye(e,t)}_linkToIdToken(e,t){const i=this.buildRequest();return i.idToken=t,Ye(e,i)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Ye(e,t)}buildRequest(){const e={requestUri:vf,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=ot(t)}return e}}class ys{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class zt extends ys{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class he extends zt{constructor(){super("facebook.com")}static credential(e){return We._fromParams({providerId:he.PROVIDER_ID,signInMethod:he.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return he.credentialFromTaggedObject(e)}static credentialFromError(e){return he.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return he.credential(e.oauthAccessToken)}catch{return null}}}he.FACEBOOK_SIGN_IN_METHOD="facebook.com";he.PROVIDER_ID="facebook.com";class ue extends zt{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return We._fromParams({providerId:ue.PROVIDER_ID,signInMethod:ue.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return ue.credentialFromTaggedObject(e)}static credentialFromError(e){return ue.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:i}=e;if(!t&&!i)return null;try{return ue.credential(t,i)}catch{return null}}}ue.GOOGLE_SIGN_IN_METHOD="google.com";ue.PROVIDER_ID="google.com";class de extends zt{constructor(){super("github.com")}static credential(e){return We._fromParams({providerId:de.PROVIDER_ID,signInMethod:de.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return de.credentialFromTaggedObject(e)}static credentialFromError(e){return de.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return de.credential(e.oauthAccessToken)}catch{return null}}}de.GITHUB_SIGN_IN_METHOD="github.com";de.PROVIDER_ID="github.com";class fe extends zt{constructor(){super("twitter.com")}static credential(e,t){return We._fromParams({providerId:fe.PROVIDER_ID,signInMethod:fe.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return fe.credentialFromTaggedObject(e)}static credentialFromError(e){return fe.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:i}=e;if(!t||!i)return null;try{return fe.credential(t,i)}catch{return null}}}fe.TWITTER_SIGN_IN_METHOD="twitter.com";fe.PROVIDER_ID="twitter.com";async function If(n,e){return ca(n,"POST","/v1/accounts:signUp",$n(n,e))}class be{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,i,s=!1){const r=await Y._fromIdTokenResponse(e,i,s),o=Er(i);return new be({user:r,providerId:o,_tokenResponse:i,operationType:t})}static async _forOperation(e,t,i){await e._updateTokensIfNecessary(i,!0);const s=Er(i);return new be({user:e,providerId:s,_tokenResponse:i,operationType:t})}}function Er(n){return n.providerId?n.providerId:"phoneNumber"in n?"phone":null}async function jp(n){if($(n.app))return Promise.reject(Ee(n));const e=Gt(n);if(await e._initializationPromise,e.currentUser?.isAnonymous)return new be({user:e.currentUser,providerId:null,operationType:"signIn"});const t=await If(e,{returnSecureToken:!0}),i=await be._fromIdTokenResponse(e,"signIn",t,!0);return await e._updateCurrentUser(i.user),i}class Tn extends Re{constructor(e,t,i,s){super(t.code,t.message),this.operationType=i,this.user=s,Object.setPrototypeOf(this,Tn.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:i}}static _fromErrorAndOperation(e,t,i,s){return new Tn(e,t,i,s)}}function Ca(n,e,t,i){return(e==="reauthenticate"?t._getReauthenticationResolver(n):t._getIdTokenResponse(n)).catch(r=>{throw r.code==="auth/multi-factor-auth-required"?Tn._fromErrorAndOperation(n,r,e,i):r})}async function Ef(n,e,t=!1){const i=await Mt(n,e._linkToIdToken(n.auth,await n.getIdToken()),t);return be._forOperation(n,"link",i)}async function wf(n,e,t=!1){const{auth:i}=n;if($(i.app))return Promise.reject(Ee(i));const s="reauthenticate";try{const r=await Mt(n,Ca(i,s,e,n),t);m(r.idToken,i,"internal-error");const o=_s(r.idToken);m(o,i,"internal-error");const{sub:a}=o;return m(n.uid===a,i,"user-mismatch"),be._forOperation(n,s,r)}catch(r){throw r?.code==="auth/user-not-found"&&ee(i,"user-mismatch"),r}}async function Cf(n,e,t=!1){if($(n.app))return Promise.reject(Ee(n));const i="signIn",s=await Ca(n,i,e),r=await be._fromIdTokenResponse(n,i,s);return t||await n._updateCurrentUser(r.user),r}function Tf(n,e,t,i){return L(n).onIdTokenChanged(e,t,i)}function Sf(n,e,t){return L(n).beforeAuthStateChanged(e,t)}function qp(n,e,t,i){return L(n).onAuthStateChanged(e,t,i)}function Kp(n){return L(n).signOut()}const Sn="__sak";class Ta{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Sn,"1"),this.storage.removeItem(Sn),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}const bf=1e3,Rf=10;class Sa extends Ta{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=va(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const i=this.storage.getItem(t),s=this.localCache[t];i!==s&&e(t,s,i)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((o,a,c)=>{this.notifyListeners(o,c)});return}const i=e.key;t?this.detachListener():this.stopPolling();const s=()=>{const o=this.storage.getItem(i);!t&&this.localCache[i]===o||this.notifyListeners(i,o)},r=this.storage.getItem(i);sf()&&r!==e.newValue&&e.newValue!==e.oldValue?setTimeout(s,Rf):s()}notifyListeners(e,t){this.localCache[e]=t;const i=this.listeners[e];if(i)for(const s of Array.from(i))s(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,i)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:i}),!0)})},bf)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){Object.keys(this.listeners).length===0&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Sa.type="LOCAL";const kf=Sa;class ba extends Ta{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}ba.type="SESSION";const Ra=ba;function Nf(n){return Promise.all(n.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}class Gn{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find(s=>s.isListeningto(e));if(t)return t;const i=new Gn(e);return this.receivers.push(i),i}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:i,eventType:s,data:r}=t.data,o=this.handlersMap[s];if(!o?.size)return;t.ports[0].postMessage({status:"ack",eventId:i,eventType:s});const a=Array.from(o).map(async l=>l(t.origin,r)),c=await Nf(a);t.ports[0].postMessage({status:"done",eventId:i,eventType:s,response:c})}_subscribe(e,t){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),(!t||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}Gn.receivers=[];function vs(n="",e=10){let t="";for(let i=0;i<e;i++)t+=Math.floor(Math.random()*10);return n+t}class Af{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,i=50){const s=typeof MessageChannel<"u"?new MessageChannel:null;if(!s)throw new Error("connection_unavailable");let r,o;return new Promise((a,c)=>{const l=vs("",20);s.port1.start();const d=setTimeout(()=>{c(new Error("unsupported_event"))},i);o={messageChannel:s,onMessage(h){const u=h;if(u.data.eventId===l)switch(u.data.status){case"ack":clearTimeout(d),r=setTimeout(()=>{c(new Error("timeout"))},3e3);break;case"done":clearTimeout(r),a(u.data.response);break;default:clearTimeout(d),clearTimeout(r),c(new Error("invalid_response"));break}}},this.handlers.add(o),s.port1.addEventListener("message",o.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[s.port2])}).finally(()=>{o&&this.removeMessageHandler(o)})}}function Z(){return window}function Pf(n){Z().location.href=n}function ka(){return typeof Z().WorkerGlobalScope<"u"&&typeof Z().importScripts=="function"}async function Of(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function Df(){return navigator?.serviceWorker?.controller||null}function Mf(){return ka()?self:null}const Na="firebaseLocalStorageDb",xf=1,bn="firebaseLocalStorage",Aa="fbase_key";class jt{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function zn(n,e){return n.transaction([bn],e?"readwrite":"readonly").objectStore(bn)}function Lf(){const n=indexedDB.deleteDatabase(Na);return new jt(n).toPromise()}function Ri(){const n=indexedDB.open(Na,xf);return new Promise((e,t)=>{n.addEventListener("error",()=>{t(n.error)}),n.addEventListener("upgradeneeded",()=>{const i=n.result;try{i.createObjectStore(bn,{keyPath:Aa})}catch(s){t(s)}}),n.addEventListener("success",async()=>{const i=n.result;i.objectStoreNames.contains(bn)?e(i):(i.close(),await Lf(),e(await Ri()))})})}async function wr(n,e,t){const i=zn(n,!0).put({[Aa]:e,value:t});return new jt(i).toPromise()}async function Ff(n,e){const t=zn(n,!1).get(e),i=await new jt(t).toPromise();return i===void 0?null:i.value}function Cr(n,e){const t=zn(n,!0).delete(e);return new jt(t).toPromise()}const Uf=800,Wf=3;class Pa{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db?this.db:(this.db=await Ri(),this.db)}async _withRetries(e){let t=0;for(;;)try{const i=await this._openDb();return await e(i)}catch(i){if(t++>Wf)throw i;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return ka()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Gn._getInstance(Mf()),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await Of(),!this.activeServiceWorker)return;this.sender=new Af(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||Df()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Ri();return await wr(e,Sn,"1"),await Cr(e,Sn),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(i=>wr(i,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(i=>Ff(i,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>Cr(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(s=>{const r=zn(s,!1).getAll();return new jt(r).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const t=[],i=new Set;if(e.length!==0)for(const{fbase_key:s,value:r}of e)i.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(r)&&(this.notifyListeners(s,r),t.push(s));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}notifyListeners(e,t){this.localCache[e]=t;const i=this.listeners[e];if(i)for(const s of Array.from(i))s(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),Uf)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){Object.keys(this.listeners).length===0&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}Pa.type="LOCAL";const Bf=Pa;new $t(3e4,6e4);function Oa(n,e){return e?se(e):(m(n._popupRedirectResolver,n,"argument-error"),n._popupRedirectResolver)}class Is extends wa{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Ye(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Ye(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Ye(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function Hf(n){return Cf(n.auth,new Is(n),n.bypassAuthState)}function Vf(n){const{auth:e,user:t}=n;return m(t,e,"internal-error"),wf(t,new Is(n),n.bypassAuthState)}async function $f(n){const{auth:e,user:t}=n;return m(t,e,"internal-error"),Ef(t,new Is(n),n.bypassAuthState)}class Da{constructor(e,t,i,s,r=!1){this.auth=e,this.resolver=i,this.user=s,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(i){this.reject(i)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:i,postBody:s,tenantId:r,error:o,type:a}=e;if(o){this.reject(o);return}const c={auth:this.auth,requestUri:t,sessionId:i,tenantId:r||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(c))}catch(l){this.reject(l)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Hf;case"linkViaPopup":case"linkViaRedirect":return $f;case"reauthViaPopup":case"reauthViaRedirect":return Vf;default:ee(this.auth,"internal-error")}}resolve(e){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const Gf=new $t(2e3,1e4);async function Yp(n,e,t){if($(n.app))return Promise.reject(J(n,"operation-not-supported-in-this-environment"));const i=Gt(n);Bd(n,e,ys);const s=Oa(i,t);return new Oe(i,"signInViaPopup",e,s).executeNotNull()}class Oe extends Da{constructor(e,t,i,s,r){super(e,t,s,r),this.provider=i,this.authWindow=null,this.pollId=null,Oe.currentPopupAction&&Oe.currentPopupAction.cancel(),Oe.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return m(e,this.auth,"internal-error"),e}async onExecution(){ce(this.filter.length===1,"Popup operations only handle one event");const e=vs();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(t=>{this.reject(t)}),this.resolver._isIframeWebStorageSupported(this.auth,t=>{t||this.reject(J(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(J(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Oe.currentPopupAction=null}pollUserCancellation(){const e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(J(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,Gf.get())};e()}}Oe.currentPopupAction=null;const zf="pendingRedirect",Zt=new Map;class jf extends Da{constructor(e,t,i=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,i),this.eventId=null}async execute(){let e=Zt.get(this.auth._key());if(!e){try{const i=await qf(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(i)}catch(t){e=()=>Promise.reject(t)}Zt.set(this.auth._key(),e)}return this.bypassAuthState||Zt.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function qf(n,e){const t=Qf(e),i=Yf(n);if(!await i._isAvailable())return!1;const s=await i._get(t)==="true";return await i._remove(t),s}function Kf(n,e){Zt.set(n._key(),e)}function Yf(n){return se(n._redirectPersistence)}function Qf(n){return Xt(zf,n.config.apiKey,n.name)}async function Jf(n,e,t=!1){if($(n.app))return Promise.reject(Ee(n));const i=Gt(n),s=Oa(i,e),o=await new jf(i,s,t).execute();return o&&!t&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,e)),o}const Xf=600*1e3;class Zf{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(i=>{this.isEventForConsumer(e,i)&&(t=!0,this.sendToConsumer(e,i),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!ep(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!Ma(e)){const i=e.error.code?.split("auth/")[1]||"internal-error";t.onError(J(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const i=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&i}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=Xf&&this.cachedEventUids.clear(),this.cachedEventUids.has(Tr(e))}saveEventToCache(e){this.cachedEventUids.add(Tr(e)),this.lastProcessedEventTime=Date.now()}}function Tr(n){return[n.type,n.eventId,n.sessionId,n.tenantId].filter(e=>e).join("-")}function Ma({type:n,error:e}){return n==="unknown"&&e?.code==="auth/no-auth-event"}function ep(n){switch(n.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Ma(n);default:return!1}}async function tp(n,e={}){return dt(n,"GET","/v1/projects",e)}const np=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,ip=/^https?/;async function sp(n){if(n.config.emulator)return;const{authorizedDomains:e}=await tp(n);for(const t of e)try{if(rp(t))return}catch{}ee(n,"unauthorized-domain")}function rp(n){const e=Si(),{protocol:t,hostname:i}=new URL(e);if(n.startsWith("chrome-extension://")){const o=new URL(n);return o.hostname===""&&i===""?t==="chrome-extension:"&&n.replace("chrome-extension://","")===e.replace("chrome-extension://",""):t==="chrome-extension:"&&o.hostname===i}if(!ip.test(t))return!1;if(np.test(n))return i===n;const s=n.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(i)}const op=new $t(3e4,6e4);function Sr(){const n=Z().___jsl;if(n?.H){for(const e of Object.keys(n.H))if(n.H[e].r=n.H[e].r||[],n.H[e].L=n.H[e].L||[],n.H[e].r=[...n.H[e].L],n.CP)for(let t=0;t<n.CP.length;t++)n.CP[t]=null}}function ap(n){return new Promise((e,t)=>{function i(){Sr(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Sr(),t(J(n,"network-request-failed"))},timeout:op.get()})}if(Z().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else if(Z().gapi?.load)i();else{const s=ff("iframefcb");return Z()[s]=()=>{gapi.load?i():t(J(n,"network-request-failed"))},uf(`${df()}?onload=${s}`).catch(r=>t(r))}}).catch(e=>{throw en=null,e})}let en=null;function cp(n){return en=en||ap(n),en}const lp=new $t(5e3,15e3),hp="__/auth/iframe",up="emulator/auth/iframe",dp={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},fp=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function pp(n){const e=n.config;m(e.authDomain,n,"auth-domain-config-required");const t=e.emulator?ps(e,up):`https://${n.config.authDomain}/${hp}`,i={apiKey:e.apiKey,appName:n.name,v:at},s=fp.get(n.config.apiHost);s&&(i.eid=s);const r=n._getFrameworks();return r.length&&(i.fw=r.join(",")),`${t}?${ot(i).slice(1)}`}async function _p(n){const e=await cp(n),t=Z().gapi;return m(t,n,"internal-error"),e.open({where:document.body,url:pp(n),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:dp,dontclear:!0},i=>new Promise(async(s,r)=>{await i.restyle({setHideOnLeave:!1});const o=J(n,"network-request-failed"),a=Z().setTimeout(()=>{r(o)},lp.get());function c(){Z().clearTimeout(a),s(i)}i.ping(c).then(c,()=>{r(o)})}))}const gp={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},mp=500,yp=600,vp="_blank",Ip="http://localhost";class br{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function Ep(n,e,t,i=mp,s=yp){const r=Math.max((window.screen.availHeight-s)/2,0).toString(),o=Math.max((window.screen.availWidth-i)/2,0).toString();let a="";const c={...gp,width:i.toString(),height:s.toString(),top:r,left:o},l=W().toLowerCase();t&&(a=pa(l)?vp:t),da(l)&&(e=e||Ip,c.scrollbars="yes");const d=Object.entries(c).reduce((u,[p,_])=>`${u}${p}=${_},`,"");if(nf(l)&&a!=="_self")return wp(e||"",a),new br(null);const h=window.open(e||"",a,d);m(h,n,"popup-blocked");try{h.focus()}catch{}return new br(h)}function wp(n,e){const t=document.createElement("a");t.href=n,t.target=e;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),t.dispatchEvent(i)}const Cp="__/auth/handler",Tp="emulator/auth/handler",Sp=encodeURIComponent("fac");async function Rr(n,e,t,i,s,r){m(n.config.authDomain,n,"auth-domain-config-required"),m(n.config.apiKey,n,"invalid-api-key");const o={apiKey:n.config.apiKey,appName:n.name,authType:t,redirectUrl:i,v:at,eventId:s};if(e instanceof ys){e.setDefaultLanguage(n.languageCode),o.providerId=e.providerId||"",sn(e.getCustomParameters())||(o.customParameters=JSON.stringify(e.getCustomParameters()));for(const[d,h]of Object.entries({}))o[d]=h}if(e instanceof zt){const d=e.getScopes().filter(h=>h!=="");d.length>0&&(o.scopes=d.join(","))}n.tenantId&&(o.tid=n.tenantId);const a=o;for(const d of Object.keys(a))a[d]===void 0&&delete a[d];const c=await n._getAppCheckToken(),l=c?`#${Sp}=${encodeURIComponent(c)}`:"";return`${bp(n)}?${ot(a).slice(1)}${l}`}function bp({config:n}){return n.emulator?ps(n,Tp):`https://${n.authDomain}/${Cp}`}const oi="webStorageSupport";class Rp{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ra,this._completeRedirectFn=Jf,this._overrideRedirectResult=Kf}async _openPopup(e,t,i,s){ce(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const r=await Rr(e,t,i,Si(),s);return Ep(e,r,vs())}async _openRedirect(e,t,i,s){await this._originValidation(e);const r=await Rr(e,t,i,Si(),s);return Pf(r),new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:s,promise:r}=this.eventManagers[t];return s?Promise.resolve(s):(ce(r,"If manager is not set, promise should be"),r)}const i=this.initAndGetManager(e);return this.eventManagers[t]={promise:i},i.catch(()=>{delete this.eventManagers[t]}),i}async initAndGetManager(e){const t=await _p(e),i=new Zf(e);return t.register("authEvent",s=>(m(s?.authEvent,e,"invalid-auth-event"),{status:i.onEvent(s.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:i},this.iframes[e._key()]=t,i}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(oi,{type:oi},s=>{const r=s?.[0]?.[oi];r!==void 0&&t(!!r),ee(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=sp(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return va()||fa()||gs()}}const kp=Rp;var kr="@firebase/auth",Nr="1.12.0";class Np{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(i=>{e(i?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){m(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Ap(n){switch(n){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function Pp(n){Je(new xe("auth",(e,{options:t})=>{const i=e.getProvider("app").getImmediate(),s=e.getProvider("heartbeat"),r=e.getProvider("app-check-internal"),{apiKey:o,authDomain:a}=i.options;m(o&&!o.includes(":"),"invalid-api-key",{appName:i.name});const c={apiKey:o,authDomain:a,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Ia(n)},l=new lf(i,s,r,c);return _f(l,t),l},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,i)=>{e.getProvider("auth-internal").initialize()})),Je(new xe("auth-internal",e=>{const t=Gt(e.getProvider("auth").getImmediate());return(i=>new Np(i))(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),ye(kr,Nr,Ap(n)),ye(kr,Nr,"esm2020")}const Op=300,Dp=Fr("authIdTokenMaxAge")||Op;let Ar=null;const Mp=n=>async e=>{const t=e&&await e.getIdTokenResult(),i=t&&(new Date().getTime()-Date.parse(t.issuedAtTime))/1e3;if(i&&i>Dp)return;const s=t?.token;Ar!==s&&(Ar=s,await fetch(n,{method:s?"POST":"DELETE",headers:s?{Authorization:`Bearer ${s}`}:{}}))};function Qp(n=Gr()){const e=Oi(n,"auth");if(e.isInitialized())return e.getImmediate();const t=pf(n,{popupRedirectResolver:kp,persistence:[Bf,kf,Ra]}),i=Fr("authTokenSyncURL");if(i&&typeof isSecureContext=="boolean"&&isSecureContext){const r=new URL(i,location.origin);if(location.origin===r.origin){const o=Mp(r.toString());Sf(t,o,()=>o(t.currentUser)),Tf(t,a=>o(a))}}const s=xr("auth");return s&&gf(t,`http://${s}`),t}function xp(){return document.getElementsByTagName("head")?.[0]??document}hf({loadJS(n){return new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",n),i.onload=e,i.onerror=s=>{const r=J("internal-error");r.customData=s,t(r)},i.type="text/javascript",i.charset="UTF-8",xp().appendChild(i)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="});Pp("Browser");export{Bp as A,jp as B,xe as C,qp as D,Kp as E,Re as F,ue as G,Yp as H,Ai as L,at as S,Je as _,Qp as a,zp as b,Vp as c,ye as d,$ as e,T as f,$p as g,Gr as h,ll as i,Oi as j,Ga as k,rt as l,Me as m,za as n,bd as o,Ur as p,L as q,Fp as r,ia as s,Lp as t,Wr as u,W as v,Wp as w,Hp as x,Gp as y,Up as z};