@veltdev/sdk-staging 6.0.37 → 6.0.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunk-2BTM4CFE.js +1 -0
- package/{chunk-ZJ4HIVB2.js → chunk-2QEJSDDK.js} +1 -1
- package/{chunk-R23OJH7V.js → chunk-3C3NVOFE.js} +1 -1
- package/{chunk-UURPJNXC.js → chunk-3INUN5X4.js} +1 -1
- package/chunk-3WXPNBX5.js +6 -0
- package/{chunk-DBBDJNHD.js → chunk-5VC7CCBD.js} +1 -1
- package/{chunk-CIPYIXSV.js → chunk-5VEPPJ7L.js} +1 -1
- package/{chunk-J7V2TOP4.js → chunk-5YQBTUDX.js} +1 -1
- package/{chunk-KX4P36RQ.js → chunk-6GGZZ4AU.js} +1 -1
- package/{chunk-I26YJORG.js → chunk-7GOPVFGG.js} +1 -1
- package/{chunk-XNUQWGIJ.js → chunk-A67RL2PN.js} +1 -1
- package/{chunk-YUS5IIVT.js → chunk-BGHA3HPN.js} +1 -1
- package/{chunk-PK6OYS7I.js → chunk-CGUTLGPR.js} +1 -1
- package/{chunk-22NJIPA6.js → chunk-CRZUWE4H.js} +1 -1
- package/{chunk-2US3JDFZ.js → chunk-EUGFBHET.js} +1 -1
- package/{chunk-MYKADDFQ.js → chunk-FABIYF77.js} +1 -1
- package/{chunk-LFLXYS4L.js → chunk-FQKWEEFD.js} +1 -1
- package/{chunk-JROC6NID.js → chunk-J63WRUBY.js} +1 -1
- package/{chunk-H7Q22XHP.js → chunk-KDR7F33G.js} +1 -1
- package/{chunk-GPP5W5BF.js → chunk-KSHKS6KZ.js} +1 -1
- package/{chunk-KNUY7U6A.js → chunk-KXR5HWPR.js} +1 -1
- package/{chunk-CYLFZYDC.js → chunk-LURMWRN2.js} +1 -1
- package/{chunk-3VD2M25A.js → chunk-LYWPFYXA.js} +1 -1
- package/{chunk-JPMXBN2F.js → chunk-MU4JCWH6.js} +1 -1
- package/{chunk-S5EASEE5.js → chunk-MYDCS2BE.js} +1 -1
- package/{chunk-Z5AFOX5P.js → chunk-OPZBNZVO.js} +1 -1
- package/{chunk-K64SVWEW.js → chunk-PHUEJCYV.js} +1 -1
- package/{chunk-NXOAKSI4.js → chunk-QTMY2244.js} +1 -1
- package/{chunk-PNQG5PL6.js → chunk-RNFB3ETM.js} +1 -1
- package/{chunk-SV4RWX2E.js → chunk-UM4DCTY2.js} +1 -1
- package/{chunk-WMCSEYPH.js → chunk-UW6RLILR.js} +1 -1
- package/{chunk-2O5WHWYH.js → chunk-VHPIMIJS.js} +1 -1
- package/{chunk-W3U57RSU.js → chunk-WHDXUE5R.js} +1 -1
- package/{chunk-HTYG2BOR.js → chunk-X7MTAUNM.js} +1 -1
- package/{chunk-DRZ2C3XD.js → chunk-XCL6Y7ID.js} +1 -1
- package/{chunk-E7O3QXJL.js → chunk-XUBWZTRK.js} +4 -4
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +1 -1
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-portable.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +2 -2
- package/chunk-CWOZPXKE.js +0 -6
- package/chunk-PR53PKH3.js +0 -1
|
@@ -145,12 +145,12 @@ ${n.map((r,i)=>`${i+1}) ${r.toString()}`).join(`
|
|
|
145
145
|
`:"")+s+` Recent session events (most recent last, times relative to now):
|
|
146
146
|
`+(o.length?o.join(`
|
|
147
147
|
`):" (no events recorded)")+`
|
|
148
|
-
This block prints once per distinct problem. If a realtime feature looks stuck, copy it into the issue \u2014 it contains no credentials.`)}catch{}}var Rne={fetch:(t,e)=>fetch(t,e)},Nne=5e3;function wne(t){return`${t.replace(/\/+$/,"")}/operations/getProjectConfig`}function bne(t,e){return y(this,null,function*(){let n=typeof AbortController<"u"?new AbortController:null,r,i=new Promise(o=>{r=setTimeout(()=>{try{n?.abort()}catch{}o(null)},Nne)});try{return yield Promise.race([Rne.fetch(t,n?me(B({},e),{signal:n.signal}):e),i])}finally{r!==void 0&&clearTimeout(r)}})}function HN(t){return y(this,null,function*(){let{apiEndpoint:e,token:n}=t;if(!e||!n)return null;if(!nl(e))return console.error(`Velt [portable backend]: refusing to send the session token to an insecure apiEndpoint (${e}). Project config was not read; https is required (http is allowed on loopback only).`),null;try{let r=yield bne(wne(e),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({})});if(!r)return null;let i=yield r.json();return!i||i.ok!==!0||!i.data?null:{isPrivateCommentsEnabled:i.data.isPrivateCommentsEnabled===!0,activityConfig:i.data.activityConfig??null}}catch{return null}})}function $N(t,e,n){return t.userSnippylyId!==e?.userSnippylyId||e?.groupId!==t.groupId||e?.organizationId!==t.organizationId||!!n?.forceReset}function WN(t,e){let{provided:n,resolved:r}=e;return t.name=r?r?.name:n?.name||t.name,t.clientUserName=r?r?.clientUserName:n?.clientUserName||t.clientUserName,t.photoUrl=r?r?.photoUrl:n?.photoUrl||t.photoUrl,t?.photoUrl===void 0&&(t.photoUrl=null),t.email=r?r?.email:n?.email||t.email,t.color=r?.color||n?.color||e.avatarColor(t.userId),t.textColor=r?.textColor||n?.textColor||e.textColor(t.userId),t.initial=r?.initial||n?.initial||t.initial||t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase(),t.contacts=n?.contacts||t.contacts,t.plan=n?.plan||t.plan,t.groupId=n?.groupId||t.groupId,t.clientGroupId=n?.clientGroupId||t.clientGroupId,t.clientOrganizationId=n?.clientOrganizationId||t.clientOrganizationId,t.organizationId=n?.organizationId||t.organizationId,t.isAdmin=n?.isAdmin,t.isReadOnly=n?.isReadOnly,t.isAnonymous=n?.isAnonymous,t.isGuest=n?.isGuest,t}var One=["unauthenticated","permission-denied","not-found","invalid-argument","failed-precondition","resource-exhausted"],f2=[...One,"unimplemented"];function p2(t){return!!t&&t.backend==="portable"&&typeof t.wsEndpoint=="string"&&typeof t.apiEndpoint=="string"}var t1e="getaccess-any-user",n1e="ordered-deltas",r1e="doc-notification-views",i1e="fetch-folders-include-children",o1e="notification-timestamp-by-document",s1e="per-editor-crdt-fold",a1e="attachments",c1e="comment-views-updated-at",l1e="organization-user-config",u1e="organization-directory",d1e="customer-metadata",h1e="multi-thread";var yy={import:()=>import("./velt-portable.js")},Sr=null,kp=!1;function g2(t){if(Sr)Sr=Sr.then(()=>yy.import().then(e=>{kp=!0,e.default(t)})).catch(e=>{b.catch("Error re-establishing portable session after re-identify: ",e)});else{let e=yy.import().then(n=>{kp=!0,n.default(t)}).catch(n=>{Sr===e&&(Sr=null),kp=!1,console.warn("Velt [portable backend]: failed to load the portable transport chunk (velt-portable.js). Portable features are disabled for this page load.",n)});Sr=e}return Sr}function m2(){Sr&&(Sr=Sr.then(()=>kp?yy.import().then(t=>{t.teardownPortableBackend()}):void 0).catch(t=>{b.catch("Error tearing down portable backend session: ",t)}))}function E2(){Sr&&(Sr=Sr.then(()=>kp?yy.import().then(t=>{t.checkPortableBackendLiveness?.()}):void 0).catch(t=>{b.catch("Error checking portable backend liveness: ",t)}))}var _2=(()=>{let e=class e{constructor(r){this.loggingService=r,this.initLocalStorageData()}initLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: initLocalStorageData","color: green;"),this.getLocalStorageData(),this.getSessionStorageData()}getLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStorageData","color: green;");try{let r=localStorage?.getItem(k.LOCALSTORAGE_DATA_ID);if(r)return JSON.parse(r);{let i=new Bc;return this.setLocalStorageData(i),i}}catch(r){return this.loggingService.catch("Error in getLocalStorageData:",r),new Bc}}setLocalStorageData(r){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(r){let i=JSON.stringify(r);localStorage?.setItem(k.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setLocalStorageData:",i)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(k.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let r=sessionStorage?.getItem(k.LOCALSTORAGE_DATA_ID);if(r)return JSON.parse(r);{let i=new Bc;return this.setSessionStorageData(i),i}}catch(r){return this.loggingService.catch("Error in getSessionStorageData:",r),new Bc}}setSessionStorageData(r){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(r){let i=JSON.stringify(r);sessionStorage?.setItem(k.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setSessionStorageData:",i)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(k.LOCALSTORAGE_DATA_ID)}catch(r){this.loggingService.catch("Error in deleteSessionStorageData:",r)}}};e.\u0275fac=function(i){return new(i||e)(z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var T2=(()=>{let e=class e{constructor(r,i){this.localStorageService=r,this.loggingService=i,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let r=new so,i=this.localStorageService.getSessionStorageData();if(i.snippylyAvatar)r=i.snippylyAvatar;else{let o=this.generateUserAvatar();i.snippylyAvatar=o,this.localStorageService.setSessionStorageData(i)}return r}catch(r){return this.loggingService.catch("Error in getSessionAvatar:",r),new so}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let r=Math.floor(Math.random()*this.avatarList.length),i=this.avatarList[r];return i.color=this.generateUserColor(),i}catch(r){return this.loggingService.catch("Error in generateUserAvatar:",r),this.avatarList[0]}}generateUserColor(r){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(r)return k.AVATAR_COLOR_LIST[r%k.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*k.AVATAR_COLOR_LIST.length);return k.AVATAR_COLOR_LIST[i]}catch(i){return this.loggingService.catch("Error in generateUserColor:",i),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(r){return this.loggingService.catch("Error in generateUserImage:",r),""}}};e.\u0275fac=function(i){return new(i||e)(z(_2),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var y2=(()=>{let e=class e{constructor(r){this.loggingService=r,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(r,i){try{this.actionSubjects.has(r)||this.actionSubjects.set(r,new Be),this.actionSubjects.get(r)?.next(i)}catch(o){this.loggingService.catch("Error in CoreActionsService triggerAction: ",o)}}onAction(r){try{this.actionSubjects.has(r)||this.actionSubjects.set(r,new Be);let i=this.actionSubjects.get(r);return i?i.asObservable():ot(null)}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),ot(null)}}};e.\u0275fac=function(i){return new(i||e)(z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function xne(t,e){this.v=t,this.k=e}function I2(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function kne(t){if(Array.isArray(t))return t}function Fne(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,o,s,a=[],c=!0,l=!1;try{if(o=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);c=!0);}catch(d){l=!0,i=d}finally{try{if(!c&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}function Une(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
148
|
+
This block prints once per distinct problem. If a realtime feature looks stuck, copy it into the issue \u2014 it contains no credentials.`)}catch{}}var Rne={fetch:(t,e)=>fetch(t,e)},Nne=5e3;function wne(t){return`${t.replace(/\/+$/,"")}/operations/getProjectConfig`}function bne(t,e){return y(this,null,function*(){let n=typeof AbortController<"u"?new AbortController:null,r,i=new Promise(o=>{r=setTimeout(()=>{try{n?.abort()}catch{}o(null)},Nne)});try{return yield Promise.race([Rne.fetch(t,n?me(B({},e),{signal:n.signal}):e),i])}finally{r!==void 0&&clearTimeout(r)}})}function HN(t){return y(this,null,function*(){let{apiEndpoint:e,token:n}=t;if(!e||!n)return null;if(!nl(e))return console.error(`Velt [portable backend]: refusing to send the session token to an insecure apiEndpoint (${e}). Project config was not read; https is required (http is allowed on loopback only).`),null;try{let r=yield bne(wne(e),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({})});if(!r)return null;let i=yield r.json();return!i||i.ok!==!0||!i.data?null:{isPrivateCommentsEnabled:i.data.isPrivateCommentsEnabled===!0,activityConfig:i.data.activityConfig??null}}catch{return null}})}function $N(t,e,n){return t.userSnippylyId!==e?.userSnippylyId||e?.groupId!==t.groupId||e?.organizationId!==t.organizationId||!!n?.forceReset}function WN(t,e){let{provided:n,resolved:r}=e;return t.name=r?r?.name:n?.name||t.name,t.clientUserName=r?r?.clientUserName:n?.clientUserName||t.clientUserName,t.photoUrl=r?r?.photoUrl:n?.photoUrl||t.photoUrl,t?.photoUrl===void 0&&(t.photoUrl=null),t.email=r?r?.email:n?.email||t.email,t.color=r?.color||n?.color||e.avatarColor(t.userId),t.textColor=r?.textColor||n?.textColor||e.textColor(t.userId),t.initial=r?.initial||n?.initial||t.initial||t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase(),t.contacts=n?.contacts||t.contacts,t.plan=n?.plan||t.plan,t.groupId=n?.groupId||t.groupId,t.clientGroupId=n?.clientGroupId||t.clientGroupId,t.clientOrganizationId=n?.clientOrganizationId||t.clientOrganizationId,t.organizationId=n?.organizationId||t.organizationId,t.isAdmin=n?.isAdmin,t.isReadOnly=n?.isReadOnly,t.isAnonymous=n?.isAnonymous,t.isGuest=n?.isGuest,t}var One=["unauthenticated","permission-denied","not-found","invalid-argument","failed-precondition","resource-exhausted"],f2=[...One,"unimplemented"];function p2(t){return!!t&&t.backend==="portable"&&typeof t.wsEndpoint=="string"&&typeof t.apiEndpoint=="string"}var t1e="getaccess-any-user",n1e="ordered-deltas",r1e="doc-notification-views",i1e="fetch-folders-include-children",o1e="notification-timestamp-by-document",s1e="per-editor-crdt-fold",a1e="attachments",c1e="comment-views-updated-at",l1e="organization-user-config",u1e="organization-directory",d1e="customer-metadata",h1e="multi-thread",f1e="organization-user-search";var yy={import:()=>import("./velt-portable.js")},Sr=null,kp=!1;function g2(t){if(Sr)Sr=Sr.then(()=>yy.import().then(e=>{kp=!0,e.default(t)})).catch(e=>{b.catch("Error re-establishing portable session after re-identify: ",e)});else{let e=yy.import().then(n=>{kp=!0,n.default(t)}).catch(n=>{Sr===e&&(Sr=null),kp=!1,console.warn("Velt [portable backend]: failed to load the portable transport chunk (velt-portable.js). Portable features are disabled for this page load.",n)});Sr=e}return Sr}function m2(){Sr&&(Sr=Sr.then(()=>kp?yy.import().then(t=>{t.teardownPortableBackend()}):void 0).catch(t=>{b.catch("Error tearing down portable backend session: ",t)}))}function E2(){Sr&&(Sr=Sr.then(()=>kp?yy.import().then(t=>{t.checkPortableBackendLiveness?.()}):void 0).catch(t=>{b.catch("Error checking portable backend liveness: ",t)}))}var _2=(()=>{let e=class e{constructor(r){this.loggingService=r,this.initLocalStorageData()}initLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: initLocalStorageData","color: green;"),this.getLocalStorageData(),this.getSessionStorageData()}getLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStorageData","color: green;");try{let r=localStorage?.getItem(k.LOCALSTORAGE_DATA_ID);if(r)return JSON.parse(r);{let i=new Bc;return this.setLocalStorageData(i),i}}catch(r){return this.loggingService.catch("Error in getLocalStorageData:",r),new Bc}}setLocalStorageData(r){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(r){let i=JSON.stringify(r);localStorage?.setItem(k.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setLocalStorageData:",i)}}deleteLocalStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteLocalStorageData","color: green;"),localStorage?.removeItem(k.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let r=sessionStorage?.getItem(k.LOCALSTORAGE_DATA_ID);if(r)return JSON.parse(r);{let i=new Bc;return this.setSessionStorageData(i),i}}catch(r){return this.loggingService.catch("Error in getSessionStorageData:",r),new Bc}}setSessionStorageData(r){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(r){let i=JSON.stringify(r);sessionStorage?.setItem(k.LOCALSTORAGE_DATA_ID,i)}}catch(i){this.loggingService.catch("Error in setSessionStorageData:",i)}}deleteSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: deleteSessionStorageData","color: green;");try{sessionStorage?.removeItem(k.LOCALSTORAGE_DATA_ID)}catch(r){this.loggingService.catch("Error in deleteSessionStorageData:",r)}}};e.\u0275fac=function(i){return new(i||e)(z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var T2=(()=>{let e=class e{constructor(r,i){this.localStorageService=r,this.loggingService=i,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let r=new so,i=this.localStorageService.getSessionStorageData();if(i.snippylyAvatar)r=i.snippylyAvatar;else{let o=this.generateUserAvatar();i.snippylyAvatar=o,this.localStorageService.setSessionStorageData(i)}return r}catch(r){return this.loggingService.catch("Error in getSessionAvatar:",r),new so}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let r=Math.floor(Math.random()*this.avatarList.length),i=this.avatarList[r];return i.color=this.generateUserColor(),i}catch(r){return this.loggingService.catch("Error in generateUserAvatar:",r),this.avatarList[0]}}generateUserColor(r){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(r)return k.AVATAR_COLOR_LIST[r%k.AVATAR_COLOR_LIST.length];let i=Math.floor(Math.random()*k.AVATAR_COLOR_LIST.length);return k.AVATAR_COLOR_LIST[i]}catch(i){return this.loggingService.catch("Error in generateUserColor:",i),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(r){return this.loggingService.catch("Error in generateUserImage:",r),""}}};e.\u0275fac=function(i){return new(i||e)(z(_2),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var y2=(()=>{let e=class e{constructor(r){this.loggingService=r,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(r,i){try{this.actionSubjects.has(r)||this.actionSubjects.set(r,new Be),this.actionSubjects.get(r)?.next(i)}catch(o){this.loggingService.catch("Error in CoreActionsService triggerAction: ",o)}}onAction(r){try{this.actionSubjects.has(r)||this.actionSubjects.set(r,new Be);let i=this.actionSubjects.get(r);return i?i.asObservable():ot(null)}catch(i){return this.loggingService.catch("Error in CoreActionsService onAction: ",i),ot(null)}}};e.\u0275fac=function(i){return new(i||e)(z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function xne(t,e){this.v=t,this.k=e}function I2(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function kne(t){if(Array.isArray(t))return t}function Fne(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,o,s,a=[],c=!0,l=!1;try{if(o=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);c=!0);}catch(d){l=!0,i=d}finally{try{if(!c&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}function Une(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
149
149
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vne(t,e){return kne(t)||Fne(t,e)||Bne(t,e)||Une()}function Bne(t,e){if(t){if(typeof t=="string")return I2(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?I2(t,e):void 0}}function Iy(t){var e,n;function r(o,s){try{var a=t[o](s),c=a.value,l=c instanceof xne;Promise.resolve(l?c.v:c).then(function(d){if(l){var h=o==="return"&&c.k?o:"next";if(!c.k||d.done)return r(h,d);d=t[h](d).value}i(!!a.done,d)},function(d){r("throw",d)})}catch(d){i(2,d)}}function i(o,s){o===2?e.reject(s):e.resolve({value:s,done:o}),(e=e.next)?r(e.key,e.arg):n=null}this._invoke=function(o,s){return new Promise(function(a,c){var l={key:o,arg:s,resolve:a,reject:c,next:null};n?n=n.next=l:(e=n=l,r(o,s))})},typeof t.return!="function"&&(this.return=void 0)}Iy.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Iy.prototype.next=function(t){return this._invoke("next",t)},Iy.prototype.throw=function(t){return this._invoke("throw",t)},Iy.prototype.return=function(t){return this._invoke("return",t)};var k2=Object.entries,v2=Object.setPrototypeOf,Gne=Object.isFrozen,F2=Object.getPrototypeOf,U2=Object.getOwnPropertyDescriptor,cn=Object.freeze,vn=Object.seal,yd=Object.create,V2=typeof Reflect<"u"&&Reflect,tw=V2.apply,nw=V2.construct;cn||(cn=function(e){return e});vn||(vn=function(e){return e});tw||(tw=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return e.apply(n,i)});nw||(nw=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});var ts=_t(Array.prototype.forEach);Array.prototype.indexOf;var jne=_t(Array.prototype.lastIndexOf),S2=_t(Array.prototype.pop),Fp=_t(Array.prototype.push),Hne=_t(Array.prototype.slice),$ne=_t(Array.prototype.splice),Id=Array.isArray,zN=B2(Set),qN=_t(Set.prototype.add),Up=_t(Set.prototype.has),il=_t(String.prototype.toLowerCase),KN=_t(String.prototype.toString),A2=_t(String.prototype.match),Vp=_t(String.prototype.replace),C2=_t(String.prototype.indexOf),Wne=_t(String.prototype.trim),zne=_t(Number.prototype.toString),qne=_t(Boolean.prototype.toString),D2=typeof BigInt>"u"?null:_t(BigInt.prototype.toString),R2=typeof Symbol>"u"?null:_t(Symbol.prototype.toString),sr=_t(Object.prototype.hasOwnProperty),Bp=_t(Object.prototype.toString),In=_t(RegExp.prototype.test),ns=B2(TypeError);function _t(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return tw(t,e,r)}}function B2(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return nw(t,n)}}function Fe(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:il;if(v2&&v2(t,null),!Id(e))return t;let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){let o=n(i);o!==i&&(Gne(e)||(e[r]=o),i=o)}t[i]=!0}return t}function Kne(t){for(let e=0;e<t.length;e++)sr(t,e)||(t[e]=null);return t}function Ar(t){let e=yd(null);for(let r of k2(t)){var n=Vne(r,2);let i=n[0],o=n[1];sr(t,i)&&(Id(o)?e[i]=Kne(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=Ar(o):e[i]=o)}return e}function Yne(t){switch(typeof t){case"string":return t;case"number":return zne(t);case"boolean":return qne(t);case"bigint":return D2?D2(t):"0";case"symbol":return R2?R2(t):"Symbol()";case"undefined":return Bp(t);case"function":case"object":{if(t===null)return Bp(t);let e=t,n=Kr(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Bp(r)}return Bp(t)}default:return Bp(t)}}function Kr(t,e){for(;t!==null;){let r=U2(t,e);if(r){if(r.get)return _t(r.get);if(typeof r.value=="function")return _t(r.value)}t=F2(t)}function n(){return null}return n}function Xne(t,e){for(;t!==null;){let n=U2(t,e);if(n)return n.get?_t(n.get):null;t=F2(t)}return null}function Qne(t){try{return In(t,""),!0}catch{return!1}}var N2=cn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),YN=cn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),XN=cn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Jne=cn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),QN=cn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Zne=cn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),w2=cn(["#text"]),b2=cn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),JN=cn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),O2=cn(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),vy=cn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ere=vn(/{{[\w\W]*|^[\w\W]*}}/g),tre=vn(/<%[\w\W]*|^[\w\W]*%>/g),nre=vn(/\${[\w\W]*/g),rre=vn(/^data-[\-\w.\u00B7-\uFFFF]+$/),ire=vn(/^aria-[\-\w]+$/),M2=vn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ore=vn(/^(?:\w+script|data):/i),sre=vn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),are=vn(/^html$/i),cre=vn(/^[a-z][.\w]*(-[.\w]+)+$/i),ZN=vn(/<[/\w!]/g),L2=vn(/<[/\w]/g),lre=vn(/<\/no(script|embed|frames)/i),P2=vn(/\/>/i),xt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},ure=cn(Fe({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),dre=function(){return typeof window>"u"?null:window},hre=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));let o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},x2=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},ta=function(e,n,r,i){return sr(e,n)&&Id(e[n])?Fe(i.base?Ar(i.base):{},e[n],i.transform):r},ew=function(e,n,r){let i=sr(e,n)?e[n]:void 0;return i&&typeof i=="object"?Ar(i):r()};function G2(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dre(),e=H=>G2(H);if(e.version="3.4.17",e.removed=[],!t||!t.document||t.document.nodeType!==xt.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,i=r.currentScript;t.DocumentFragment;let o=t.HTMLTemplateElement,s=t.Node,a=t.Element,c=t.NodeFilter;t.NamedNodeMap===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let l=t.DOMParser,d=t.trustedTypes,h=a.prototype,f=Kr(h,"cloneNode"),g=Kr(h,"remove"),E=Kr(h,"removeAttributeNode"),I=Kr(h,"nextSibling"),S=Kr(h,"childNodes"),L=Kr(h,"parentNode"),j=Kr(h,"shadowRoot"),K=Kr(h,"attributes"),te=s&&s.prototype?Kr(s.prototype,"nodeType"):null,pe=s&&s.prototype?Kr(s.prototype,"nodeName"):null,ie=s&&s.prototype?Kr(s.prototype,"ownerDocument"):null,A=function(T){return te?te(T):T.nodeType},v=function(T){return pe?pe(T):T.nodeName},C=Xne(h,"namespaceURI"),w=function(T){return C?C(T):T.namespaceURI};if(typeof o=="function"){let H=n.createElement("template");H.content&&H.content.ownerDocument&&(n=H.content.ownerDocument)}let R,O="",D,Mr=!1,Jr=0,_m=function(){if(Jr>0)throw ns('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},Lr=function(T){_m(),Jr++;try{return R.createHTML(T)}finally{Jr--}},Pa=function(T){_m(),Jr++;try{return R.createScriptURL(T)}finally{Jr--}},Lh=function(){return Mr||(D=hre(d,i),Mr=!0),D},xa=n,Ph=xa.implementation,Zr=xa.createNodeIterator,tn=xa.createDocumentFragment,Kv=xa.getElementsByTagName,ka=r.importNode,nt=x2();e.isSupported=typeof k2=="function"&&typeof L=="function"&&Ph&&Ph.createHTMLDocument!==void 0;let Fa=ere,Yv=tre,Xv=nre,zl=rre,ql=ire,xh=ore,Kl=sre,kh=cre,Yl=M2,rt=null,Xl=Fe({},[...N2,...YN,...XN,...QN,...w2]),lt=null,Ql=Fe({},[...b2,...JN,...O2,...vy]),ur=Object.seal(yd(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),So=null,Fh=null,wi=Object.seal(yd(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Jl=!0,Ua=!0,Zl=!1,bt=!0,dt=!1,Pr=!0,bi=!1,eu=!1,tu=null,Oi=null,nu=!1,Ao=!1,hs=!1,ru=!1,Tm=!0,iu=!1,Uh="user-content-",ou=!0,Co=!1,ei=null,Mi={},Gn=null,Vh=Fe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),Va=null,Bh=Fe({},["audio","video","img","source","image","track"]),fs=null,Gh=Fe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ot="http://www.w3.org/1998/Math/MathML",Ba="http://www.w3.org/2000/svg",An="http://www.w3.org/1999/xhtml",xr=An,jh=!1,Hh=null,ps=Fe({},[Ot,Ba,An],KN),ym=cn(["mi","mo","mn","ms","mtext"]),$h=Fe({},ym),Ga=cn(["annotation-xml"]),su=Fe({},Ga),Wh=Fe({},["title","style","font","a","script"]),Li=null,Pi=["application/xhtml+xml","text/html"],Im="text/html",pt=null,xi=null,zh=n.createElement("form"),qh=function(T){return T instanceof RegExp||T instanceof Function},au=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(xi&&xi===T)return;(!T||typeof T!="object")&&(T={}),T=Ar(T),Li=Pi.indexOf(T.PARSER_MEDIA_TYPE)===-1?Im:T.PARSER_MEDIA_TYPE,pt=Li==="application/xhtml+xml"?KN:il,rt=ta(T,"ALLOWED_TAGS",Xl,{transform:pt}),lt=ta(T,"ALLOWED_ATTR",Ql,{transform:pt}),Hh=ta(T,"ALLOWED_NAMESPACES",ps,{transform:KN}),fs=ta(T,"ADD_URI_SAFE_ATTR",Gh,{transform:pt,base:Gh}),Va=ta(T,"ADD_DATA_URI_TAGS",Bh,{transform:pt,base:Bh}),Gn=ta(T,"FORBID_CONTENTS",Vh,{transform:pt}),So=ta(T,"FORBID_TAGS",Ar({}),{transform:pt}),Fh=ta(T,"FORBID_ATTR",Ar({}),{transform:pt}),Mi=sr(T,"USE_PROFILES")?T.USE_PROFILES&&typeof T.USE_PROFILES=="object"?Ar(T.USE_PROFILES):T.USE_PROFILES:!1,Jl=T.ALLOW_ARIA_ATTR!==!1,Ua=T.ALLOW_DATA_ATTR!==!1,Zl=T.ALLOW_UNKNOWN_PROTOCOLS||!1,bt=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,dt=T.SAFE_FOR_TEMPLATES||!1,Pr=T.SAFE_FOR_XML!==!1,bi=T.WHOLE_DOCUMENT||!1,Ao=T.RETURN_DOM||!1,hs=T.RETURN_DOM_FRAGMENT||!1,ru=T.RETURN_TRUSTED_TYPE||!1,nu=T.FORCE_BODY||!1,Tm=T.SANITIZE_DOM!==!1,iu=T.SANITIZE_NAMED_PROPS||!1,ou=T.KEEP_CONTENT!==!1,Co=T.IN_PLACE||!1,Yl=Qne(T.ALLOWED_URI_REGEXP)?T.ALLOWED_URI_REGEXP:M2,xr=typeof T.NAMESPACE=="string"?T.NAMESPACE:An,$h=ew(T,"MATHML_TEXT_INTEGRATION_POINTS",()=>Fe({},ym)),su=ew(T,"HTML_INTEGRATION_POINTS",()=>Fe({},Ga));let N=ew(T,"CUSTOM_ELEMENT_HANDLING",()=>yd(null));if(ur=yd(null),sr(N,"tagNameCheck")&&qh(N.tagNameCheck)&&(ur.tagNameCheck=N.tagNameCheck),sr(N,"attributeNameCheck")&&qh(N.attributeNameCheck)&&(ur.attributeNameCheck=N.attributeNameCheck),sr(N,"allowCustomizedBuiltInElements")&&typeof N.allowCustomizedBuiltInElements=="boolean"&&(ur.allowCustomizedBuiltInElements=N.allowCustomizedBuiltInElements),vn(ur),dt&&(Ua=!1),hs&&(Ao=!0),Mi&&(rt=Fe({},w2),lt=yd(null),Mi.html===!0&&(Fe(rt,N2),Fe(lt,b2)),Mi.svg===!0&&(Fe(rt,YN),Fe(lt,JN),Fe(lt,vy)),Mi.svgFilters===!0&&(Fe(rt,XN),Fe(lt,JN),Fe(lt,vy)),Mi.mathMl===!0&&(Fe(rt,QN),Fe(lt,O2),Fe(lt,vy))),wi.tagCheck=null,wi.attributeCheck=null,sr(T,"ADD_TAGS")&&(typeof T.ADD_TAGS=="function"?wi.tagCheck=T.ADD_TAGS:Id(T.ADD_TAGS)&&(rt===Xl&&(rt=Ar(rt)),Fe(rt,T.ADD_TAGS,pt))),sr(T,"ADD_ATTR")&&(typeof T.ADD_ATTR=="function"?wi.attributeCheck=T.ADD_ATTR:Id(T.ADD_ATTR)&&(lt===Ql&&(lt=Ar(lt)),Fe(lt,T.ADD_ATTR,pt))),sr(T,"ADD_FORBID_CONTENTS")&&Id(T.ADD_FORBID_CONTENTS)&&(Gn===Vh&&(Gn=Ar(Gn)),Fe(Gn,T.ADD_FORBID_CONTENTS,pt)),ou&&(rt["#text"]=!0),bi&&Fe(rt,["html","head","body"]),rt.table&&(Fe(rt,["tbody"]),delete So.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw ns('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ns('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let G=R;R=T.TRUSTED_TYPES_POLICY;try{O=Lr("")}catch(V){throw R=G,V}}else T.TRUSTED_TYPES_POLICY===null?(R=void 0,O=""):(R===void 0&&(R=Lh()),R&&typeof O=="string"&&(O=Lr("")));cn&&cn(T),xi=T},vm=Fe({},[...YN,...XN,...Jne]),ja=Fe({},[...QN,...Zne]),Sm=function(T,N,G){return N.namespaceURI===An?T==="svg":N.namespaceURI===Ot?T==="svg"&&(G==="annotation-xml"||$h[G]):!!vm[T]},Kh=function(T,N,G){return N.namespaceURI===An?T==="math":N.namespaceURI===Ba?T==="math"&&su[G]:!!ja[T]},Ha=function(T,N,G){return N.namespaceURI===Ba&&!su[G]||N.namespaceURI===Ot&&!$h[G]?!1:!ja[T]&&(Wh[T]||!vm[T])},Do=function(T){let N=w(T),G=il(v(T)),V=L(T),ae,ge;return V&&A(V)===xt.element?(ae={namespaceURI:w(V)},ge=il(v(V))):(ae={namespaceURI:xr},ge="template"),Hh[N]?N===Ba?Sm(G,ae,ge):N===Ot?Kh(G,ae,ge):N===An?Ha(G,ae,ge):!!(Li==="application/xhtml+xml"&&Hh[N]):!1},kr=function(T){Fp(e.removed,{element:T});try{L(T).removeChild(T)}catch{if(g(T),!L(T))throw ns("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Am=function(T,N,G){try{E(T,N)}catch{try{T.removeAttribute(G)}catch{}}},cu=function(T){Wa(T);let N=S(T);N&&ts(Hne(N),V=>{try{g(V)}catch{}});let G=A(T)===xt.element?K(T):null;if(G)for(let V=G.length-1;V>=0;--V){let ae=G[V],ge=ae&&ae.name;typeof ge=="string"&&Am(T,ae,ge)}},Ro=function(T,N,G){if(!G)try{G=N.getAttributeNode(T)}catch{G=null}Fp(e.removed,{attribute:G||null,from:N});try{G?E(N,G):N.removeAttribute(T)}catch{try{N.removeAttribute(T)}catch{}}if(T==="is")if(Ao||hs)try{kr(N)}catch{}else try{N.setAttribute(T,"")}catch{}},Yh=function(T){let N=K(T);if(N)for(let G=N.length-1;G>=0;--G){let V=N[G],ae=V&&V.name;typeof ae!="string"||lt[pt(ae)]||Am(T,V,ae)}},$a=function(T,N){let G=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,V=[T];for(;V.length>0;){let ae=V.pop();if(N(ae)===!1)continue;if(G&&A(ae)===xt.element){let Se=j(ae);Xn(Se)&&V.push(Se)}let ge=S(ae);if(ge)for(let Se=ge.length-1;Se>=0;--Se)V.push(ge[Se])}},Wa=function(T){$a(T,N=>{A(N)===xt.element&&Yh(N)})},lu=function(T){let N=[];return $a(T,G=>{N.push(G)},!0),N},Cm=function(T,N){let G=zN();ts(lu(T),V=>{A(V)===xt.element&&qN(G,V)}),ts(N,V=>{A(V)===xt.element&&!Up(G,V)&&Yh(V)})},Dm=function(T,N){let G=!1;return ts(e.removed,V=>{V.element&&(G=G||V.element===T,Wa(V.element))}),Cm(T,N),G},Qv=8,Rm=function(T,N){let G=ei,V=null,ae=()=>(V||(V=zN(),ts(N,ge=>{qN(V,ge)})),V);for(let ge=0;;ge++){let Se=lu(T),Ae=[T],Vr=!1;if(ts(Se,fn=>{A(fn)===xt.documentFragment?Fp(Ae,fn):!Vr&&!Up(G,fn)&&(Vr=Up(ae(),fn))}),!Vr)return;if(ge>=Qv)throw ns("the tree kept changing during in-place sanitization; refusing to return it");ts(Ae,(fn,pn)=>{Nm(fn,pn>0,T,ae())})}},Nm=function(T,N,G,V){let ae=gs(T),ge;for(;ge=ae.nextNode();)!Up(V,ge)||Up(ei,ge)||(N&&Qn(nt.uponSanitizeShadowNode,ge,null),Ur(ge,G),Jh(ge,G),Xn(ge.content)&&Jn(ge.content))},Jv=function(T){ei&&qN(ei,T)},ki=function(T,N){return Pr?T==="patchsrc"?!0:T==="for"&&N!=="label"&&N!=="output":!1},ti=function(T){Pr&&$a(T,N=>{let G=A(N);if(G===xt.processingInstruction||G===xt.comment&&In(L2,N.data)){try{g(N)}catch{}return!1}if(G===xt.element){let V=N,ae=pt(v(N));try{V.hasAttribute&&V.hasAttribute("patchsrc")&&V.removeAttribute("patchsrc"),V.hasAttribute&&V.hasAttribute("for")&&ki("for",ae)&&V.removeAttribute("for")}catch{}}return!0})},za=function(T){let N=null,G=null;if(nu)T="<remove></remove>"+T;else{let ge=A2(T,/^[\r\n\t ]+/);G=ge&&ge[0]}Li==="application/xhtml+xml"&&xr===An&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");let V=R?Lr(T):T;if(xr===An)try{N=new l().parseFromString(V,Li)}catch{}if(!N||!N.documentElement){N=Ph.createDocument(xr,"template",null);try{N.documentElement.innerHTML=jh?O:V}catch{}}let ae=N.body||N.documentElement;return T&&G&&ae.insertBefore(n.createTextNode(G),ae.childNodes[0]||null),xr===An?Kv.call(N,bi?"html":"body")[0]:bi?N.documentElement:ae},gs=function(T){let N=ie?ie(T):T.ownerDocument;return Zr.call(N||T,T,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},qa=function(T){return T=Vp(T,Fa," "),T=Vp(T,Yv," "),T=Vp(T,Xv," "),T},qe=function(T){var N;Ka(T);let G=(N=T.querySelectorAll)===null||N===void 0?void 0:N.call(T,"template");G&&ts(G,V=>{Xn(V.content)&&qe(V.content)})},Ka=function(T){T.normalize();let N=ie?ie(T):T.ownerDocument,G=Zr.call(N||T,T,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),V=G.nextNode();for(;V;)V.data=qa(V.data),V=G.nextNode()},Fi=function(T){let N=pe?pe(T):null;return typeof N!="string"||pt(N)!=="form"?!1:typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||T.attributes!==K(T)||typeof T.removeAttribute!="function"||typeof T.removeAttributeNode!="function"||typeof T.getAttributeNode!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function"||T.nodeType!==te(T)||T.childNodes!==S(T)},Xn=function(T){if(!te||typeof T!="object"||T===null)return!1;try{return te(T)===xt.documentFragment}catch{return!1}},Ya=function(T){if(!te||typeof T!="object"||T===null)return!1;try{return typeof te(T)=="number"}catch{return!1}};function Qn(H,T,N){H.length!==0&&ts(H,G=>{G.call(e,T,N,xi)})}let Zv=function(T,N){return!!(Pr&&T.hasChildNodes()&&!Ya(T.firstElementChild)&&In(ZN,T.textContent)&&In(ZN,T.innerHTML)||Pr&&ure[N]&&A(T)===xt.element&&w(T)===An&&(Ya(T.firstElementChild)||typeof T.textContent=="string"&&In(ZN,T.textContent))||T.nodeType===xt.processingInstruction||Pr&&T.nodeType===xt.comment&&In(L2,T.data))},uu=function(T,N){if(T instanceof RegExp)return In(T,N);if(T instanceof Function){for(var G=arguments.length,V=new Array(G>2?G-2:0),ae=2;ae<G;ae++)V[ae-2]=arguments[ae];return!!T(N,...V)}return!1},eS=function(T,N,G){if(!So[N]&&Qh(N)&&uu(ur.tagNameCheck,N))return!1;if(ou&&!Gn[N]&&!Gn[il(N)]){let V=L(T),ae=S(T);if(ae&&V){let ge=ae.length;for(let Se=ge-1;Se>=0;--Se){let Ae=T===G?f(ae[Se],!0):ae[Se];V.insertBefore(Ae,I(T))}}}return kr(T),!0},wm=function(T,N,G,V){return T.length===0?N:N===G||N===V?Ar(N):N},Fr=function(T,N){return T===N||L(T)!==null?!1:(Co&&Wa(T),!0)},Ur=function(T,N){if(Jv(T),Qn(nt.beforeSanitizeElements,T,null),Fr(T,N))return!0;if(Fi(T))return kr(T),!0;let G=pt(v(T));if(rt=wm(nt.uponSanitizeElement,rt,Xl,tu),Qn(nt.uponSanitizeElement,T,{tagName:G,allowedTags:rt}),Fr(T,N))return!0;if(Zv(T,G))return kr(T),!0;if(So[G]||!(wi.tagCheck instanceof Function&&wi.tagCheck(G))&&!rt[G]){let V=eS(T,G,N);return V===!1&&(Qn(nt.afterSanitizeElements,T,null),Fr(T,N))?!0:V}if(A(T)===xt.element&&!Do(T)||(G==="noscript"||G==="noembed"||G==="noframes")&&In(lre,T.innerHTML))return kr(T),!0;if(dt&&T.nodeType===xt.text){let V=qa(T.textContent);T.textContent!==V&&(Fp(e.removed,{element:T.cloneNode()}),T.textContent=V)}return Qn(nt.afterSanitizeElements,T,null),Fr(T,N)},Xh=function(T,N,G){if(Fh[N]||ki(N,T)||Tm&&(N==="id"||N==="name")&&(G in n||G in zh))return!1;let V=lt[N]||wi.attributeCheck instanceof Function&&wi.attributeCheck(N,T);return Ua&&In(zl,N)||Jl&&In(ql,N)?!0:V?fs[N]||In(Yl,Vp(G,Kl,""))||(N==="src"||N==="xlink:href"||N==="href")&&T!=="script"&&C2(G,"data:")===0&&Va[T]||Zl&&!In(xh,Vp(G,Kl,""))?!0:!G:Qh(T)&&uu(ur.tagNameCheck,T)&&uu(ur.attributeNameCheck,N,T)||N==="is"&&ur.allowCustomizedBuiltInElements&&uu(ur.tagNameCheck,G)},bm=Fe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Qh=function(T){return!bm[il(T)]&&In(kh,T)},ms=function(T,N,G,V){if(R&&typeof d=="object"&&typeof d.getAttributeType=="function"&&!G)switch(d.getAttributeType(T,N)){case"TrustedHTML":return Lr(V);case"TrustedScriptURL":return Pa(V)}return V},tS=function(T,N,G,V){try{return G?T.setAttributeNS(G,N,V):T.setAttribute(N,V),Fi(T)?(kr(T),!1):!0}catch{return Ro(N,T),!1}},Om=function(T,N){return Pr&&In(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,N)?!0:il(T)==="attributename"&&A2(N,"href")!==null},Jh=function(T,N){if(Qn(nt.beforeSanitizeAttributes,T,null),Fr(T,N))return;let G=T.attributes;if(!G||Fi(T))return;lt=wm(nt.uponSanitizeAttribute,lt,Ql,Oi);let V={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:lt,forceKeepAttr:void 0},ae=G.length,ge=pt(T.nodeName);for(;ae--;){let Se=G[ae],Ae=Se.name,Vr=Se.namespaceURI,fn=Se.value,pn=pt(Ae),No=fn,gn=Ae==="value"?No:Wne(No),Xa=!1;if(V.attrName=pn,V.attrValue=gn,V.keepAttr=!0,V.forceKeepAttr=void 0,Qn(nt.uponSanitizeAttribute,T,V),gn=V.attrValue,iu&&(pn==="id"||pn==="name")&&C2(gn,Uh)!==0&&(Ro(Ae,T,Se),gn=Uh+gn,Xa=!0),Om(Ae,gn)){Ro(Ae,T,Se);continue}if(!V.forceKeepAttr){if(!V.keepAttr){Ro(Ae,T,Se);continue}if(!bt&&In(P2,gn)){Ro(Ae,T,Se);continue}if(dt&&(gn=qa(gn)),!Xh(ge,pn,gn)){Ro(Ae,T,Se);continue}gn=ms(ge,pn,Vr,gn),gn!==No&&tS(T,Ae,Vr,gn)&&Xa&&S2(e.removed)}}Qn(nt.afterSanitizeAttributes,T,null),Fr(T,N)},Jn=function(T){let N=null,G=gs(T);for(Qn(nt.beforeSanitizeShadowDOM,T,null);N=G.nextNode();)if(Qn(nt.uponSanitizeShadowNode,N,null),Ur(N,T),Jh(N,T),Xn(N.content)&&Jn(N.content),A(N)===xt.element){let V=j(N);Xn(V)&&(Zh(V),Jn(V))}dt&&Ka(T),Qn(nt.afterSanitizeShadowDOM,T,null)},Zh=function(T){let N=[{node:T,shadow:null}];for(;N.length>0;){let G=N.pop();if(G.shadow){Jn(G.shadow);continue}let V=G.node,ae=A(V)===xt.element,ge=S(V);if(ge)for(let Se=ge.length-1;Se>=0;--Se)N.push({node:ge[Se],shadow:null});if(ae){let Se=pe?pe(V):null;if(typeof Se=="string"&&pt(Se)==="template"){let Ae=V.content;Xn(Ae)&&N.push({node:Ae,shadow:null})}}if(ae){let Se=j(V);Xn(Se)&&N.push({node:null,shadow:Se},{node:Se,shadow:null})}}};return e.sanitize=function(H){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},N=null,G=null,V=null,ae=null;if(jh=!H,jh&&(H="<!-->"),typeof H!="string"&&!Ya(H)&&(H=Yne(H),typeof H!="string"))throw ns("dirty is not a string, aborting");if(!e.isSupported)return H;eu?(rt=tu,lt=Oi):au(T),(nt.uponSanitizeElement.length>0||nt.uponSanitizeAttribute.length>0)&&(rt=Ar(rt)),nt.uponSanitizeAttribute.length>0&&(lt=Ar(lt)),e.removed=[];let ge=Co&&typeof H!="string"&&Ya(H),Se=[],Ae=ei;if(ge){ti(H);let pn=v(H);if(typeof pn=="string"){let No=pt(pn);if(!rt[No]||So[No])throw cu(H),ns("root node is forbidden and cannot be sanitized in-place")}if(Fi(H))throw cu(H),ns("root node is clobbered and cannot be sanitized in-place");Se=lu(H),ei=zN()}else if(Ya(H))N=za("<!---->"),G=N.ownerDocument.importNode(H,!0),G.nodeType===xt.element&&G.nodeName==="BODY"||G.nodeName==="HTML"?N=G:N.appendChild(G),Zh(N);else{if(!Ao&&!dt&&!bi&&H.indexOf("<")===-1)return R&&ru?Lr(H):H;if(N=za(H),!N)return Ao?null:ru?O:""}N&&nu&&kr(N.firstChild);let Vr=ge?H:N;try{ge&&Zh(H);let pn=gs(Vr);for(;V=pn.nextNode();)Ur(V,Vr),Jh(V,Vr),Xn(V.content)&&Jn(V.content);ge&&Rm(H,Se)}catch(pn){throw ge&&(cu(H),Dm(H,Se)),pn}finally{ei=Ae}if(ge){if(Dm(H,Se))throw ns("a node selected for removal could not be safely returned; refusing to sanitize in place");return dt&&qe(H),H}if(Ao){if(dt&&qe(N),hs)for(ae=tn.call(N.ownerDocument);N.firstChild;)ae.appendChild(N.firstChild);else ae=N;return(lt.shadowroot||lt.shadowrootmode)&&(ae=ka.call(r,ae,!0)),ae}let fn=bi?N.outerHTML:N.innerHTML;return bi&&rt["!doctype"]&&N.ownerDocument&&N.ownerDocument.doctype&&N.ownerDocument.doctype.name&&In(are,N.ownerDocument.doctype.name)&&(fn="<!DOCTYPE "+N.ownerDocument.doctype.name+`>
|
|
150
|
-
`+fn),dt&&(fn=qa(fn)),R&&ru?Lr(fn):fn},e.setConfig=function(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};au(H),eu=!0,tu=rt,Oi=lt},e.clearConfig=function(){xi=null,eu=!1,tu=null,Oi=null,R=D,O=""},e.isValidAttribute=function(H,T,N){xi||au({});let G=pt(H),V=pt(T);return typeof N=="string"&&(Om(T,N)||!bt&&In(P2,N))?!1:Xh(G,V,N)},e.addHook=function(H,T){typeof T=="function"&&sr(nt,H)&&Fp(nt[H],T)},e.removeHook=function(H,T){if(sr(nt,H)){if(T!==void 0){let N=jne(nt[H],T);return N===-1?void 0:$ne(nt[H],N,1)[0]}return S2(nt[H])}},e.removeHooks=function(H){sr(nt,H)&&(nt[H]=[])},e.removeAllHooks=function(){nt=x2()},e}var Sy=G2();var fre=/^\/\/\*\[@id='([^']+)'\]/;function rw(t){try{if(typeof t!="string")return null;let e=fre.exec(t);if(!e)return null;let n=e[1],r=t.slice(e[0].length);if(!r)return{rootId:n,segments:[]};if(!r.startsWith("/"))return null;let i=[],o="",s=0,a=null;for(let c=1;c<r.length;c++){let l=r[c];if(a){l===a&&(a=null),o+=l;continue}if(l==="'"||l==='"')a=l;else if(l==="[")s++;else if(l==="]")s--;else if(l==="/"&&s===0){if(!o)return null;i.push(o),o="";continue}o+=l}return!o||a||s!==0?null:(i.push(o),{rootId:n,segments:i})}catch{return null}}var pre=[/:r[0-9a-z]+:/i,/_r_[0-9a-z]+_/i,/«r[0-9a-z]+»/i,/^radix-/i];function H2(t){try{return t?pre.some(e=>e.test(t)):!1}catch{return!1}}function v1e(t){if(Array.isArray(t))return j2(t);if(!t||typeof t!="object"||!("documentIds"in t))return{documentIds:null};let e=t.documentIds;return Array.isArray(e)?j2(e):{documentIds:[],problem:"not-an-array"}}function j2(t){let e=t.filter(n=>typeof n=="string"||typeof n=="number"&&Number.isFinite(n)).map(n=>String(n)).filter(n=>n.length>0);return B({documentIds:Array.from(new Set(e)).sort()},e.length<t.length?{problem:"dropped-entries"}:{})}function S1e(t,e){return t===null||e===null?t===e:t.length===e.length&&t.every((n,r)=>n===e[r])}var $2={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},W2=(()=>{let e=class e{constructor(r,i,o,s){this.analyticsService=r,this.rendererFactory2=i,this.loggingService=o,this.sanitizer=s,this.smoothScrollShieldHandler=null,this.smoothScrollShieldLoadListener=null,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new le(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new le([]),this.mousedown=!1,this.windowMouseDown$=new Be,this.windowPointerMove$=new le(null),this.windowPointerUp$=new Be,this.documentSelectionChange$=new Be,this.windowClick$=new Be,this.windowScroll$=new le(null),this.windowResize$=new le(null),this.windowKeyupBackspace$=new Be,this.windowKeyupDelete$=new Be,this.windowKeyupEsc$=new Be,this.windowPopState$=new le(null),this.documentClick$=new Be,this.lastDocumentClickTarget=null,this.documentClickSubject$=new Be,this.documentFocus$=new Be,this.isShiftKeyPressed=!1,this.mutation$=new Be,this.childListMutation$=new Be,this.networkStatus$=new le(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new le({}),this.selectedAnnotationsLocationMap$=new le({}),this.selectedAnnotationsContextIdMap$=new le({}),this.recordingInProgress$=new le({}),this.deleteAnnotations$=new le([]),this.pinHighlighterClass$=new le(null),this.dialogOpenedInSidebar$=new le(!1),this.textHighlighterClass$=new le(null),this.commentPinHighlighter$=new le(!1),this.deviceInfo$=new le(new Wr),this.customCss$=new le(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=a=>{try{let c=[];return a.forEach(l=>{if(!ao(l))if(l instanceof HTMLElement){if(l.className.includes("cdk-overlay-container")||l.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(l.className.includes("cdk-overlay")){let d=!1;l.childNodes.forEach(h=>{ao(h)&&(d=!0)}),d||c.push(l)}else c.push(l)}else c.push(l)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new le(a),this.currentMousePosition$=new le(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(sc(),lE(([c,l])=>{try{let d=l.filter(f=>!c.includes(f)),h=c.filter(f=>!l.includes(f));h.length&&h.map(g=>document.getElementById(g)).filter(g=>g).forEach(g=>{this.unlistenElementScroll&&this.unlistenElementScroll[g.id]&&this.unlistenElementScroll[g.id]()}),d.length&&d.map(g=>document.getElementById(g)).filter(g=>g).forEach(g=>{this.unlistenElementScroll[g.id]=this.renderer.listen(g,"scroll",E=>{let I=this.calculateScreenSize();this.currentScreenSize$.next(I)})})}catch(d){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",d)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?iB("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):oB("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(r){try{this.docService=r,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}setDynamicIdPatterns(r){try{let i=r.map(o=>typeof o=="string"?new RegExp(o):o).filter(Boolean);i.length&&(this.dynamicIdPatterns=i)}catch(i){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",i)}}isLikelyDynamicId(r){try{return r?this.dynamicIdPatterns.some(i=>i.test(r)):!1}catch{return!1}}isGeneratedId(r){return this.isLikelyDynamicId(r)||H2(r)}getStableAttributes(r){try{let i={};if(!r.getAttributeNames)return i;let o=new Set(["id","class","style"]);return r.getAttributeNames().forEach(a=>{if(o.has(a)||a.includes("snippyly")||a.includes("velt"))return;let c=r.getAttribute(a);c&&c.length<=256&&(i[a]=c)}),i}catch{return{}}}buildStableElementSelector(r,i){try{if(Object.keys(i).length===0)return;let s=[r.tagName?.toLowerCase()],a=["data-","aria-","role","name","title","type"];return Object.keys(i).sort((l,d)=>{let h=a.findIndex(g=>l.startsWith(g)),f=a.findIndex(g=>d.startsWith(g));return(h===-1?99:h)-(f===-1?99:f)}).slice(0,4).forEach(l=>{let d=CSS.escape(i[l]);s.push(`[${l}="${d}"]`)}),s.join("")}catch{return}}getVisibleText(r,i=400){try{let o=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),s="",a,c=0;for(;(a=o.nextNode())&&s.length<i;){let l=(a.textContent||"").replace(/\s+/g," ").trim();if(l&&(s+=(s?" ":"")+l),c++,c>100)break}return s.slice(0,i)}catch{return""}}hashText(r){try{return GV(r)}catch{return}}generateRobustXPath(r,i){try{let o=i?.maxDepth||10,s=i?.useAbsolutePath||!1,a=[],c=r,l=0;for(;c&&c!==document.documentElement&&l<o;){let g=this.buildRobustXPathSegment(c);if(g&&(a.unshift(g),this.isStrongAnchorSegment(g)))break;c=c.parentElement,l++}if(a.length===0)return;let h=(s?"/":"//")+a.join("/");return a.some(g=>g.includes("[@")||g.includes("[contains(@class"))?h:void 0}catch{return}}buildRobustXPathSegment(r){try{let i=r.tagName.toLowerCase(),o=r.id;if(o&&!this.isLikelyDynamicId(o)&&document.querySelectorAll(`[id="${CSS.escape(o)}"]`).length===1)return`*[@id=${this.escapeXPathValue(o)}]`;let s=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let g of s){let E=r.getAttribute(g);if(E)return`${i}[@${g}=${this.escapeXPathValue(E)}]`}let a=Array.from(r.attributes).filter(g=>g.name.startsWith("data-")&&!g.name.includes("snippyly")&&!g.name.includes("velt")&&g.value.length<100).sort((g,E)=>g.value.length-E.value.length);if(a.length>0){let g=a[0];return`${i}[@${g.name}=${this.escapeXPathValue(g.value)}]`}let c=r.getAttribute("role");if(c)return`${i}[@role=${this.escapeXPathValue(c)}]`;let l=r.getAttribute("aria-label");if(l&&l.length<50)return`${i}[@aria-label=${this.escapeXPathValue(l)}]`;let d=r.getAttribute("name");if(d)return`${i}[@name=${this.escapeXPathValue(d)}]`;let h=r.getAttribute("type");if(h)return`${i}[@type=${this.escapeXPathValue(h)}]`;let f=Array.from(r.classList||[]).filter(g=>g.length>0&&g.length<40&&!g.includes("yui")&&!g.includes("velt")&&!g.includes("snippyly")&&!this.excludeClassList.includes(g)).slice(0,2);if(f.length>0){let g=f.map(E=>`contains(@class, ${this.escapeXPathValue(E)})`).join(" and ");return`${i}[${g}]`}if(r.parentElement){let g=Array.from(r.parentElement.children).filter(E=>E.tagName===r.tagName);if(g.length>1){let E=g.indexOf(r)+1;return`${i}[${E}]`}}return i}catch{return}}isStrongAnchorSegment(r){try{return!!(r.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(s=>r.includes(`[@role='${s}']`))||["data-region","data-instanceid","data-activityid"].some(s=>r.includes(`[@${s}=`)))}catch{return!1}}escapeXPathValue(r,i=!0){try{return r.includes("'")?r.includes('"')?`concat(${r.split("'").map(a=>`'${a}'`).join(`,"'",`)})`:i?`"${r}"`:r:i?`'${r}'`:r}catch{try{return`concat(${r.split("'").map(c=>`'${c}'`).join(`,"'",`)})`}catch{return i?`'${r}'`:r}}}getElementFromRobustXPath(r){try{return document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(r){try{let i=document.evaluate(r,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),o=[];for(let s=0;s<i.snapshotLength;s++){let a=i.snapshotItem(s);a instanceof Element&&o.push(a)}return o}catch{return[]}}generateAnchorRecord(r,i){try{let o=this.generateAnchorRecordForElement(r,i),s=null;if(r.parentElement&&r.parentElement instanceof HTMLElement&&cd(r.parentElement)&&r.parentElement!==document.body&&(s=r.parentElement),o&&s){let a=this.generateAnchorRecordForElement(s,i);a&&(o.parent=a)}return o}catch(o){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",o),null}}generateAnchorRecordForElement(r,i){try{if(!r)return null;let o=r,s=o.tagName?.toUpperCase();if(!s)return null;let a=o.id&&!this.isLikelyDynamicId(o.id)?o.id:void 0,c=this.getStableAttributes(o),l=this.buildStableElementSelector(o,c),d=this.getVisibleText(o),h=this.hashText(d||""),f=this.generateRobustXPath(o),g=this.getXPath(o,!1,!1,void 0,{ignoreGeneratedIds:i?.ignoreGeneratedIds}),E=this.getXPath(o,!0),I=this.getXPath(o,!0,!0);return{version:"1.0",id:a,tagName:s,elementSelector:l,robustXPath:f||void 0,xPath:g||void 0,fXPath:E||void 0,cfXPath:I||void 0,contentHash:h?{value:h,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(o){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",o),null}}resolveAnchorRecord(r){try{let i=[],o=null,s=(h,f,g=0)=>{let E=[],I=g;if(E.push({method:f,score:g}),r.tagName&&h.tagName?.toUpperCase()===r.tagName&&(I+=10,E.push({method:"tagName-match",score:10})),r.contentHash?.value){let S=this.getVisibleText(h);this.hashText(S)===r.contentHash.value&&(I+=30,E.push({method:"contentHash-match",score:30}))}i.push({el:h,score:I,by:f,scoreBreakdown:E})};if(r.id){let h=document.querySelectorAll(`#${CSS.escape(r.id)}`);if(h.length===1)return{element:h[0],matchedBy:"id",score:90};h.length>1&&h.forEach(f=>s(f,"id-duplicate",70))}if(r.elementSelector){let h=document.querySelectorAll(r.elementSelector);if(h.length===1)return{element:h[0],matchedBy:"element-selector",score:80};h.forEach(f=>s(f,"element-selector-duplicate",60))}r.robustXPath&&this.getAllElementsFromRobustXPath(r.robustXPath).slice(0,20).forEach(E=>s(E,"robustXPath",50)),r?.parent&&(o=this.resolveAnchorRecord(r.parent),o.element&&o.element.querySelectorAll(r.tagName?.toLowerCase()||"*").forEach(f=>s(f,"parent+tag",40)));let a=(h,f,g)=>{if(!h)return;let E=this.getElementFromXPath(h);E&&s(E,f||"xpath",g||30)};if(a(r.xPath,"xPath",30),a(r.cfXPath,"cfXPath",30),a(r.fXPath,"fXPath",30),r.contentHash?.value&&i.length===0){let f=g=>{let E=0;for(let I=0;I<g.length&&E<400;I++){let S=g[I];if(E++,!this.isElementVisible(S))continue;let L=this.getVisibleText(S),j=this.hashText(L);j&&j===r.contentHash?.value&&s(S,"contentHash",15)}};if(o?.element&&o?.element instanceof Element){let g=o?.element?.querySelectorAll("*");f(g)}}if(!i.length)return{element:null};i.sort((h,f)=>f.score-h.score);let c=i[0].score,l=i.filter(h=>h.score===c);if(l.length>1){let h=[{path:r.xPath,label:"xPath"},{path:r.cfXPath,label:"cfXPath"},{path:r.fXPath,label:"fXPath"}];for(let f of h)if(f.path){let g=this.getElementFromXPath(f.path);if(g){let E=l.find(I=>I.el===g);if(E)return{element:E.el,matchedBy:`${E.by}+position`,score:E.score,scoreBreakdown:E.scoreBreakdown}}}}let d=i[0];return{element:d.el,matchedBy:d.by,score:d.score,scoreBreakdown:d.scoreBreakdown}}catch(i){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",i),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(De(r=>{r?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentFocus(),this.setupSmoothScrollShield()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver(),this.teardownSmoothScrollShield())})).subscribe(),this.onDocumentClick()}catch(r){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",r)}}setScrollableElementsIds(r){try{r&&r.length&&this.scrollableElementsIds$.next(Array.from(new Set(r)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(r){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+r,"color: green;"),this.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(s=>s?.attributeName===k.VELT_IGNORE_CHANGE_DETECTION))return;let o=i.filter(s=>s.type==="childList").filter(s=>{let a=s.target;return s.removedNodes.forEach(c=>{let l=c;if(typeof l.getAttribute=="function"){let d=l.getAttribute(k.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(d!==null&&d!==""){let h=this.xpathCacheId.get(d);h!==void 0&&(this.xpathCacheId.delete(d),this.xpathCache.delete(h))}}}),ao(a)?!1:!!(this.filterSnippylyNodes(s.addedNodes).length||this.filterSnippylyNodes(s.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(o.filter(s=>!this.isAnimatingElement(s.target))):this.childListMutation$.next(o),o.push(...i.filter(s=>s.type==="attributes").filter(s=>!ao(s.target)).filter(s=>this.filterSnippylyNodes([s.target]).length).filter(s=>{if(s){let a=s.target;return a?.classList?.contains("snippyly-sidebar-panel")?!1:a?!a.getAttribute(k.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),o=o.filter(s=>{let a=!0;return Object.keys(k.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{s.target?.closest(c)&&(a=!1)}),a}),o=o.filter(s=>s.target&&cd(s.target)),this.animationFilterEnabled&&(o=o.filter(s=>!this.isAnimatingElement(s.target))),o.length&&this.mutation$.next(o)}catch(o){this.loggingService.catch("Error in DomService change detection: ",o)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let r=window;return r.gsap||r.TweenMax||r.TweenLite||r.TimelineMax||r.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):r.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):r.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):r.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):r.lottie||r.Lottie||r.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(r){try{if(!r||typeof r.closest!="function")return!1;let i=window;if(i.gsap&&typeof i.gsap.isTweening=="function"){if(i.gsap.isTweening(r))return!0;if(typeof i.gsap.getTweensOf=="function")try{if(i.gsap.getTweensOf(r).length>0)return!0}catch{}}else if(i.TweenMax&&typeof i.TweenMax.isTweening=="function"){if(i.TweenMax.isTweening(r))return!0;if(typeof i.TweenMax.getTweensOf=="function")try{if(i.TweenMax.getTweensOf(r).length>0)return!0}catch{}}let o=r.style?.cssText||"";if(o){let l=o.includes("transform")||o.includes("translate3d")||o.includes("translate(")||o.includes("scale3d")||o.includes("rotate"),d=o.includes("will-change")&&o.includes("transform"),h=o.includes("transform-style")&&o.includes("preserve-3d");if(l&&(d||h))return!0}if(r.style&&(r.style.animation!==""&&r.style.animation!=="none"||r.style.transition!==""&&r.style.transition!=="none")||r.classList?.contains("animate")||r.classList?.contains("animating")||r.classList?.contains("animated")||r.classList?.contains("animation"))return!0;let s=this.staticAnimationCache.get(r);if(s!==void 0)return s;let a=!1,c=r.className||"";return typeof c=="string"&&(c.includes("slider")&&(c.includes("bullet")||c.includes("pagination"))&&(a=!0),c.includes("swiper-pagination")&&(a=!0)),!a&&(r.hasAttribute("data-aos")||r.hasAttribute("data-motion"))&&(a=!0),!a&&r.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(a=!0),this.staticAnimationCache.set(r,a),a}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(r){this.loggingService.catch("Error in DomService unsetMutationObserver: ",r)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{vs(Hi(window,"offline").pipe(De(()=>!1)),Hi(window,"online").pipe(De(()=>!0)),new ue(r=>{r.next(navigator.onLine),r.complete()})).subscribe(r=>{this.networkStatus$.next(r)})}catch(r){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",r)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",r=>{this.windowResize$.next(r);let i=this.calculateScreenSize();this.deviceInfo$.next(new Wr),this.currentScreenSize$.next(i)})}catch(r){this.loggingService.catch("Error in DomService onWindowResize: ",r)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",r)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",r=>{this.windowScroll$.next(r);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(r){this.loggingService.catch("Error in DomService onWindowScroll: ",r)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",r)}}setupSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: setupSmoothScrollShield","color: green;");try{if(typeof window>"u"||typeof document>"u"||this.smoothScrollShieldHandler)return;if(this.isSmoothScrollLibPresent()){this.attachSmoothScrollShield();return}if(document.readyState!=="complete"&&!this.smoothScrollShieldLoadListener){let r=()=>{this.smoothScrollShieldLoadListener=null;try{if(this.smoothScrollShieldHandler)return;this.isSmoothScrollLibPresent()&&this.attachSmoothScrollShield()}catch(i){this.loggingService.catch("Error in DomService smooth-scroll shield load re-check: ",i)}};window.addEventListener("load",r,{once:!0}),this.smoothScrollShieldLoadListener=()=>window.removeEventListener("load",r)}}catch(r){this.loggingService.catch("Error in DomService setupSmoothScrollShield: ",r)}}isSmoothScrollLibPresent(){try{if(typeof window>"u"||typeof document>"u")return!1;if(window.ET_SmoothScroll)return!0;let i=document.body;return!!(i&&i.classList&&i.classList.contains("et_smooth_scroll"))}catch(r){return this.loggingService.catch("Error in DomService isSmoothScrollLibPresent: ",r),!1}}attachSmoothScrollShield(){if(this.smoothScrollShieldHandler)return;let r=/^(VELT-|SUPERFLOW-|SNIPPYLY-)/,i=s=>{try{let a=typeof s.composedPath=="function"?s.composedPath():[];for(let c=0;c<a.length;c++){let l=a[c];if(!(!l||l.nodeType!==1)&&l.tagName&&r.test(l.tagName)){s.stopImmediatePropagation();return}}}catch(a){this.loggingService.catch("Error in DomService smoothScrollShield handler: ",a)}};this.smoothScrollShieldHandler=i;let o={capture:!0,passive:!0};window.addEventListener("wheel",i,o),window.addEventListener("mousewheel",i,o),window.addEventListener("touchmove",i,o),this.unlistenWindowWheelShield=()=>window.removeEventListener("wheel",i,o),this.unlistenWindowMouseWheelShield=()=>window.removeEventListener("mousewheel",i,o),this.unlistenWindowTouchMoveShield=()=>window.removeEventListener("touchmove",i,o)}teardownSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: teardownSmoothScrollShield","color: green;");try{try{this.smoothScrollShieldLoadListener&&typeof this.smoothScrollShieldLoadListener=="function"&&(this.smoothScrollShieldLoadListener(),this.smoothScrollShieldLoadListener=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (load): ",r)}try{this.unlistenWindowWheelShield&&typeof this.unlistenWindowWheelShield=="function"&&(this.unlistenWindowWheelShield(),this.unlistenWindowWheelShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (wheel): ",r)}try{this.unlistenWindowMouseWheelShield&&typeof this.unlistenWindowMouseWheelShield=="function"&&(this.unlistenWindowMouseWheelShield(),this.unlistenWindowMouseWheelShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (mousewheel): ",r)}try{this.unlistenWindowTouchMoveShield&&typeof this.unlistenWindowTouchMoveShield=="function"&&(this.unlistenWindowTouchMoveShield(),this.unlistenWindowTouchMoveShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (touchmove): ",r)}this.smoothScrollShieldHandler=null}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield: ",r)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",r=>{this.mousedown=!0,this.windowMouseDown$.next(r),this.setPointerPosition(r)})}catch(r){this.loggingService.catch("Error in DomService onPointerDown: ",r)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",r)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",r=>{this.windowClick$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowClick: ",r)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",r)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",r=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",r)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",r)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",r=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",r)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",r)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",r=>{this.windowKeyupEsc$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",r)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",r)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",r=>{this.windowPopState$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowPopState: ",r)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",r)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=r=>{r?.target?.tagName?.toLowerCase()!==k.TAGS.SUPERFLOW_TOOLBAR&&(this.lastDocumentClickTarget=r?.target?new WeakRef(r.target):null,this.documentClick$.next(r),this.documentClickSubject$.next(r))},document.addEventListener("click",this.documentClickListener,!0)}catch(r){this.loggingService.catch("Error in DomService onDocumentClick: ",r)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",r)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=r=>{this.documentFocus$.next(r)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(r){this.loggingService.catch("Error in DomService onDocumentFocus: ",r)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",r)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",()=>{this.isShiftKeyPressed=!0})}catch(r){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",r)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",r)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",()=>{this.isShiftKeyPressed=!1})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",r)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",r)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return Hi(window,"keydown")}catch(r){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",r),nc}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",r=>{this.windowPointerMove$.next(r),this.mouseMoveEvent=r})}catch(r){this.loggingService.catch("Error in DomService addPointerMoveListener: ",r)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",r)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",r=>{this.windowPointerUp$.next(r)})}catch(r){this.loggingService.catch("Error in DomService addPointerUpListener: ",r)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",r)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",r=>{this.documentSelectionChange$.next(r)})}catch(r){this.loggingService.catch("Error in DomService addPointerUpListener: ",r)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",r)}}updateCurrentMousePosition(r){try{if(this.currentMousePosition.pageX=r.pageX,this.currentMousePosition.pageY=r.pageY,this.currentMousePosition.clientX=r.clientX,this.currentMousePosition.clientY=r.clientY,r.target){let i=this.getXPath(r.target),o=r.target;if(i?.includes("name()='svg'")){let h=this.getXPath(i);h&&(o=h.iterateNext()||r.target)}let s=o.getBoundingClientRect(),a=r.clientX-s.x,c=r.clientY-s.y,l=a*100/(s.width||1),d=c*100/(s.height||1);this.currentMousePosition.element={xpath:i,topPercentage:d,leftPercentage:l}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(r,i=!0,o=!1,s=!0,a,c=!0,l,d){try{let h=r,f=h?.touches?.length?h.touches[0]?.clientX:h?.clientX,g=h?.touches?.length?h.touches[0]?.clientY:h?.clientY;l&&(f=l.clientX,g=l.clientY);let E=this.getBackgroundElement(f,g,i,o);if(E&&a&&typeof a=="function"&&(E=a(E)),E){let I=this.getXPath(E,!1,!1,void 0,d),S=this.getXPath(E,!0),L=E.getBoundingClientRect(),j=f-L.x,K=g-L.y,te=j*100/(L.width||1),pe=K*100/(L.height||1),ie={xpath:I,fXpath:S,leftPercentage:te,topPercentage:pe};if(s){let A=this.getXPath(E,!0,!0);ie.cfXpath=A}if(c){let A=this.generateAnchorRecord(E,d);A&&(ie.anchor=A)}return ie}else return null}catch(h){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",h),null}}getBackgroundElement(r,i,o=!0,s=!1){try{let a=document.elementsFromPoint(r,i),c=[];a.forEach(d=>{ao(d)?c=[]:cd(d)&&c.push(d)}),s&&(c=c.filter(d=>this.isElementVisibleOnScreen(d)));let l=0;return o||c?.forEach((d,h)=>{d.tagName.toLowerCase()==="svg"&&(l=h)}),c[l]}catch(a){return this.loggingService.catch("Error in DomService getBackgroundElement: ",a),null}}getBackgroundVeltElement(r,i){try{let o=document.elementsFromPoint(r,i),s=[];return o.forEach(a=>{ao(a)&&cd(a)&&s.push(a)}),s[0]}catch(o){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",o),null}}setPointerPosition(r){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=r.pageX,this.previousMousePosition.pageY=r.pageY,this.currentMousePosition.pageX=r.pageX,this.currentMousePosition.pageY=r.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(r){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let r=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||r.x+200,o=Math.min(i,r.width/2),s=Math.abs(r.y),a=r.y-20;return s>50&&(a=Math.abs(r.y)+180),this.loggingService.log(r),this.loggingService.log(o),this.loggingService.log(a),{topPositionX:o,topPositionY:a}}catch(r){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",r),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(r){this.pinHighlighterClass$.next(r)}setTextHighlighterClass(r){this.textHighlighterClass$.next(r)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(r,i,o){if(r&&!Gc(r)){if(!o&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(r,this.pinHighlighterClass$.value):this.addClassToElement(r,k.SNIPPYLY_HIGHLIGHT)),i&&!r.hasAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)){let s=r.style.getPropertyValue("cursor"),a=r.style.getPropertyPriority("cursor"),c=s?{defaultCursorValue:s,defaultCursorPriority:a}:"";r.setAttribute(k.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),r.style.setProperty("cursor",i,"important")}r.setAttribute(k.SNIPPYLY_HIGHLIGHT,"true"),r.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(r){if(r&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(r,this.pinHighlighterClass$.value),this.removeClassFromElement(r,k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.VELT_IGNORE_CHANGE_DETECTION),r.hasAttribute(k.ATTRIBUTES.DEFAULT_CURSOR))){try{if(r.style.removeProperty("cursor"),r.getAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(r.getAttribute(k.ATTRIBUTES.DEFAULT_CURSOR));r.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}r.removeAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(r,i,o,s=!1){try{r&&(this.addClassToElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT),s&&this.addClassToElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),r.setAttribute(k.SNIPPYLY_HIGHLIGHT,"true"),r.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!r.style.getPropertyValue(k.VELT_SELECTION_COLOR)&&r.style.setProperty(k.VELT_SELECTION_COLOR,i),o&&r.setAttribute(k.SNIPPYLY_HIGHLIGHT_USER_NAME,o))}catch(a){this.loggingService.catch("Error in DomService highlightUserElement: ",a)}}removeHighlightUserFromElement(r){try{r&&(this.removeClassFromElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.VELT_IGNORE_CHANGE_DETECTION),r.removeAttribute(k.VELT_SELECTION_COLOR),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT_USER_NAME),r.style.removeProperty(k.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(r){r&&r.setAttribute(k.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(r){r&&r.removeAttribute(k.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(r,i=!1,o=!1,s,a){try{let c=this.calculateXPath(r,i,o,s,a);if(c&&typeof c=="string"&&c.includes("/svg")){let l=c.split("/"),d=!1;l.forEach((h,f)=>{h.includes("svg")&&(d=!0),d&&(l[f]="svg:"+h)}),c=l.join("/")}return c}catch(c){this.loggingService.catch("Error in DomService getXPath:",c)}}namespaceResolver(r){return r==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(r,i,o,s,a){try{if(r){if(typeof r=="string")return document.evaluate(r,s||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!r||r.nodeType!=1)return"";if(r.id&&document.querySelectorAll(`[id='${r.id}']`)?.length===1&&!i&&!(a?.ignoreGeneratedIds&&this.isGeneratedId(r.id)))return"//*[@id='"+r.id+"']";if(o&&r.className&&r.className.split){let l=r.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(l){let d=this.calculateXPath(r.parentNode,i,o,s,a)+"/"+r.tagName.toLowerCase(),h=Array.from(r.parentNode?.children||[]).filter(f=>f.nodeType===1&&f.tagName===r.tagName?f.className?.split(" ")?.filter(E=>E?.includes("snippyly")||E?.includes("velt")||["show-pin-cursor"].includes(E))[0]===l:!1);if(h.length>1){let f=h.indexOf(r)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${l} ')][${f}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${l} ')]`;return d}}let c=[].filter.call(r.parentNode?.children?r.parentNode?.children:[],function(l){return l.tagName==r.tagName});return this.calculateXPath(r.parentNode,i,o,void 0,a)+"/"+r.tagName.toLowerCase()+(c.length>1?"["+([].indexOf.call(c,r)+1)+"]":"")}}catch(c){this.loggingService.catch("Error in DomService calculateXPath:",c)}}getElementFromXPath(r,i=document){try{if(this.xpathCache.has(r)){let s=this.xpathCache.get(r);if(s!==void 0&&document.contains(s))return s;this.xpathCache.delete(r)}let o=this.getXPath(r,!1,!1,i);if(o){let s=o?.iterateNext();if(s!==null&&typeof s.setAttribute=="function"&&!Gc(s)){let a=ad();s.setAttribute(k.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,a),this.xpathCacheId.set(a,r)}return this.xpathCache.set(r,s),s}return null}catch(o){return this.loggingService.catch("Error in DomService getElementFromXPath:",o),null}}getElementFromTargetElement(r){try{let i=null;if(r?.anchor){let o=this.resolveAnchorRecord(r.anchor);o?.element&&(i=o.element)}else r?.xpath?i=this.getElementFromXPath(r.xpath):r?.cfXpath?i=this.getElementFromXPath(r.cfXpath):r?.fXpath&&(i=this.getElementFromXPath(r.fXpath));return i}catch(i){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",i),null}}resolveIdScopedTarget(r){try{let i=r?.anchor?.xPath||r?.xpath,o=rw(i);if(!i||!o||this.isGeneratedId(o.rootId))return{applicable:!1,element:null};let s=this.getUniqueElementById(o.rootId);if(!s||!this.isElementVisible(s)||!cd(s))return{applicable:!0,element:null};let a=d=>!!d&&s.contains(d)&&this.isElementVisible(d),c=this.getElementFromXPath(i);if(a(c))return{applicable:!0,element:c,matchedBy:"exact"};let l=r?.anchor?.robustXPath;if(l&&rw(l)?.rootId===o.rootId){let d=this.getElementFromRobustXPath(l);if(a(d))return{applicable:!0,element:d,matchedBy:"robust"}}return{applicable:!0,element:s,matchedBy:"root"}}catch(i){return this.loggingService.catch("Error in DomService resolveIdScopedTarget: ",i),{applicable:!1,element:null}}}getUniqueElementById(r){try{let i=document.querySelectorAll(`[id="${CSS.escape(r)}"]`);return i.length===1?i[0]:null}catch{return null}}getElementFromTargetTextRange(r){try{let i=null;if(r?.commonAncestorContainerAnchor){let o=this.resolveAnchorRecord(r.commonAncestorContainerAnchor);o?.element&&(i=o.element)}else r?.commonAncestorContainer&&(i=this.getElementFromXPath(r.commonAncestorContainer));return i}catch(i){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",i),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let r=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight);let o=new lp;return o.screenWidth=Math.max(...i),o.screenHeight=Math.max(...r),o.screenScrollHeight=this.pageScrollHeight,o}catch(r){return this.loggingService.catch("Error in DomService calculateScreenSize:",r),new lp}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.highestNode=void 0;let r=this.findLongestNode(document?.documentElement?.childNodes);this.highestNode=r?new WeakRef(r):void 0}catch(r){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",r)}}removeSnippylyContent(r){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let o=new DOMParser().parseFromString(r,"text/html");o.querySelectorAll("[data-snippyly-cache-id]").forEach(f=>{f.removeAttribute("data-snippyly-cache-id")}),o.querySelectorAll("[data-velt-cache-id]").forEach(f=>{f.removeAttribute("data-velt-cache-id")}),o.querySelectorAll(".comment-text-highlight").forEach(f=>{f?.parentNode?.insertBefore(document.createTextNode(f?.textContent),f),f.remove()});let l=document.createNodeIterator(o,NodeFilter.SHOW_COMMENT),d;for(;d=l.nextNode();)d?.remove();return this.mergeAdjacentTextNodes(o.body),this.sanitizeHtml(o.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),r}}mergeAdjacentTextNodes(r){try{let i=r.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let o=i.nextSibling;for(;o&&o.nodeType===Node.TEXT_NODE;)i.textContent+=o.textContent,o.remove(),o=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(r){let i;try{for(let o=r.length-1;o>=0;o--){if(r[o]?.scrollHeight&&r[o]?.clientHeight){let s=Math.max(r[o]?.scrollHeight,r[o]?.clientHeight);s>=this.pageScrollHeight&&(this.pageScrollHeight=s,i=r[o])}r[o]?.childNodes?.length&&(i=this.findLongestNode(r[o]?.childNodes)??i)}}catch(o){this.loggingService.catch("Error in DomService findLongestNode: ",o)}return i}resetSelectedAnnotationsMap(r=!0,i){try{let s=this.getDraftAnnotationRefs().map(d=>d.classList.contains("velt-annotation-draft-checked")?(d.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(d,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(d,"velt-comment-dialog-shake"),d.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||d.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(d,"velt-annotation-draft-checked")},100),d.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(d=>d),a=Object.keys(this.getRecordingInProgress()||{});s=[...s,...a];let c=this.selectedAnnotationsMap$.value;if(r&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let d=[];Object.keys(c).forEach(h=>{if(c[h]?.type==="tag"){let f=c[h];f?.to?.length||s.includes(h)||d.push(f)}else c[h]?.comments?.length||s.includes(h)||d.push(c[h])}),this.deleteAnnotations$.next(d),this.deleteAnnotations$.next([])}let l={};Object.keys(c).forEach(d=>{s.includes(d)&&(l[d]=c[d]),i&&(i==="comment"?["comment","videoPin"].includes(c[d]?.type)||(l[d]=c[d]):c[d]?.type!==i&&(l[d]=c[d]))}),Object.keys(l).forEach(d=>{let h=l[d]?.multiThreadAnnotationId;h&&!l[h]&&(l[h]={annotationId:h,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(l)&&this.selectedAnnotationsMap$.next(l),this.setDialogOpenedInSidebar(!1)}catch(o){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",o)}}getDraftAnnotationRefs(){let r=Array.from(document.querySelectorAll(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`));return r.push(...this.getDraftCommentAnnotationDialogs()||[]),Array.from(new Set(r))}isEmptyDraftAnnotation(r){try{let i=this.selectedAnnotationsMap$.value?.[r];return!i||i.type==="tag"||i.type==="multiThread"||i.comments?.length||Object.prototype.hasOwnProperty.call(this.getRecordingInProgress()||{},r)?!1:!this.getDraftAnnotationRefs().some(o=>o.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_DRAFT)===r)}catch(i){return this.loggingService.catch("Error in DomService isEmptyDraftAnnotation: ",i),!1}}discardEmptyDraftAnnotation(r){try{let i=this.selectedAnnotationsMap$.value||{};if(!r||!this.isEmptyDraftAnnotation(r))return!1;this.deleteAnnotations$.next([i[r]]),this.deleteAnnotations$.next([]);let o=B({},i);return delete o[r],this.selectedAnnotationsMap$.next(o),!0}catch(i){return this.loggingService.catch("Error in DomService discardEmptyDraftAnnotation: ",i),!1}}setRecordingInProgress(r,i){try{if(i)this.recordingInProgress$.next(me(B({},this.recordingInProgress$.value),{[r]:i}));else{let o=this.recordingInProgress$.value;delete o[r],this.recordingInProgress$.next(o)}}catch(o){this.loggingService.catch("Error in DomService setRecordingInProgress: ",o)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(r){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",r)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(r){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",r),{}}}getDraftCommentAnnotationDialogs(){try{let r=[],i=Array.from(document.querySelectorAll(`${k.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),o=Array.from(document.querySelectorAll(`${k.TAGS.VELT_COMMENT_DIALOG}`));return[...i,...o].forEach(a=>{if(a?.shadowRoot){let c=a.shadowRoot.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);c&&r.push(c)}else{let c=a.querySelector(`${k.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(c?.shadowRoot){let l=c.shadowRoot?.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);l&&r.push(l)}else{let l=a.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);l&&r.push(l)}}}),r}catch(r){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",r),[]}}getSelectedAnnotationsMap(r){try{let i=this.selectedAnnotationsMap$.value;if(r){let o={};return Object.keys(i).forEach(s=>{r==="comment"?["comment","videoPin"].includes(i[s].type)&&(o[s]=i[s]):i[s].type===r&&(o[s]=i[s])}),o}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(r){return this.selectedAnnotationsMap$.asObservable().pipe(De(i=>{if(r){let o={};return Object.keys(i).forEach(s=>{i[s].type===r&&(o[s]=i[s])}),o}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(De(r=>Object.values(r)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(r){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",r),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}getSelectedAnnotationsContextIdMap(){try{return this.selectedAnnotationsContextIdMap$.value}catch(r){return this.loggingService.catch("Error in DomService getSelectedAnnotationsContextIdMap: ",r),{}}}getSelectedAnnotationsContextIdMap$(){return this.selectedAnnotationsContextIdMap$.asObservable()}toggleAnnotationSelection(r,i,o,s=!1,a,c){try{o==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let l=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{})),h=JSON.parse(JSON.stringify(this.selectedAnnotationsContextIdMap$.value||{}));l[r.annotationId]&&!s?delete l[r.annotationId]:((!this.isShiftKeyPressed||s)&&(l={}),l[r.annotationId]=r,d[r.annotationId]=i,c&&(h[r.annotationId]=c),a=r?.multiThreadAnnotationId||a,a&&(l[a]={annotationId:a,type:"multiThread"},d[a]=i,c&&(h[a]=c))),this.selectedAnnotationsMap$.next(l),Object.keys(d).forEach(f=>{l[f]||delete d[f]}),this.selectedAnnotationsLocationMap$.next(d),Object.keys(h).forEach(f=>{l[f]||delete h[f]}),this.selectedAnnotationsContextIdMap$.next(h)}catch(l){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",l)}}setSelectedAnnotationLocation(r,i){try{let o=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));o?.[r]!==i&&(o[r]=i,this.selectedAnnotationsLocationMap$.next(o))}catch(o){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",o)}}updateSelectedAnnotationInMap(r){try{let i=this.selectedAnnotationsMap$.value;r.forEach(o=>{i[o.annotationId]&&(i[o.annotationId]=o)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",r),ot([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode?.deref()}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.pipe(nn(null))}onSelectionChange$(){return this.documentSelectionChange$.pipe(nn(null))}onWindowClick$(){return this.windowClick$.pipe(nn(null))}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.pipe(nn(null))}onWindowKeyupDelete$(){return this.windowKeyupDelete$.pipe(nn(null))}onWindowKeyupEsc$(){return this.windowKeyupEsc$.pipe(nn(null))}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.pipe(nn(null))}getLastDocumentClickTarget(){return this.lastDocumentClickTarget?.deref()??null}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.pipe(nn(null))}onDomChange$(r){try{return this.mutationObserver||this.setMutationObserver(r),this.mutation$.pipe(nn(null))}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),ot([])}}getChildListMutation$(){return this.childListMutation$.pipe(nn(null))}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(r,i){try{let o={offsetTop:0,offsetLeft:0},s=r;if(s===i){let a=window.getComputedStyle(r);a.position==="static"&&a.transformStyle!="preserve-3d"&&a.transform=="none"&&(o.offsetLeft=r?.offsetLeft||0,o.offsetTop=r?.offsetTop||0)}if(s!==i)if(r?.closest("svg"))for(;s&&s!==i;){let c=window.getComputedStyle(s);if(s.tagName.toLowerCase()==="svg"||s instanceof SVGElement){let l=s.parentElement;if(l){let d=l.getBoundingClientRect(),h=s.getBoundingClientRect();o.offsetLeft+=h.left-d.left,o.offsetTop+=h.top-d.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0):(o.offsetLeft+=s.offsetLeft,o.offsetTop+=s.offsetTop);if(s=s.parentElement,r instanceof SVGElement&&s===i){let l=window.getComputedStyle(s);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0)}}else{let c=window.getComputedStyle(s);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0):(o.offsetLeft+=s.offsetLeft,o.offsetTop+=s.offsetTop)}return o}catch(o){return this.loggingService.catch("Error in DomService getElementOffset: ",o),{offsetTop:0,offsetLeft:0}}}isElementVisible(r){try{if(typeof r?.getBoundingClientRect=="function"){let{width:i,height:o,top:s,bottom:a}=r?.getBoundingClientRect();return i>0||o>0||s<window.innerHeight&&a>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(r){try{if(r){if(!(r instanceof Element))return!1;let i=r,o=window.getComputedStyle(i);return!(o.display==="none"||o.visibility==="hidden"||parseFloat(o.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new ue(r=>{let i=Hi(document,"mousedown").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),o=Hi(document,"mousemove").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),s=Hi(document,"mouseup").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),c=i.pipe(Zn(l=>o.pipe(sc(),De(([d,h])=>({startPoint:l,prevPoint:d,curPoint:h})),Is(s)))).subscribe(r);return()=>c.unsubscribe()})}drawRectangle(r,i){let o=document.querySelector(".rectangle");o||(o=document.createElement("div"),this.addClassToElement(o,"rectangle"),o.setAttribute(k.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),o.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(o));let s=Math.abs(i.x-r.x),a=Math.abs(i.y-r.y),c=Math.min(r.x,i.x),l=Math.min(r.y,i.y);return o.style.width=`${s}px`,o.style.height=`${a}px`,o.style.left=`${c}px`,o.style.top=`${l}px`,o.style.position="absolute",o.style.border="2px dashed #f00",o.style.pointerEvents="none",o.style.zIndex="2147483577",o}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let r=window.getSelection();if(r?.rangeCount)return r.getRangeAt(0)}return null}catch(r){return this.loggingService.catch("Error in DomService getRange: ",r),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(r){this.loggingService.catch("Error in DomService clearTextSelection: ",r)}}getTargetTextRangeFromSelectionRange(r){try{let i={},o=r.commonAncestorContainer;o?.nodeType===Node.TEXT_NODE&&(o=o.parentElement);let s=document.body;if(o){let c=this.getTextXPath(o);this.isXpathWithId(c)&&(s=o)}let a=this.getAdditionalLocationContainer(o);if(a&&(s=a),i.commonAncestorContainer=this.getTextXPath(s),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);if(c){i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let l=this.generateAnchorRecord(c);l&&(i.commonAncestorContainerAnchor=l)}}return i.text=r.toString(),i.occurrence=DR(s,0,r.startContainer,r.startOffset,r.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(r){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),r.nodeType===Node.TEXT_NODE){let i=1,o=r.previousSibling;for(;o;)o.nodeType===Node.TEXT_NODE&&i++,o=o.previousSibling;return this.getXPath(r.parentElement)}else return this.getXPath(r)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(r){try{if(k.NON_NESTABLE_ELEMENTS[r?.tagName?.toLowerCase()]){let o=r?.closest("picture");return o?o?.parentElement:r.parentElement}let i=r.closest("svg");return i?i?.parentElement:r}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),r}}isElementInsideAdditionalLocationContainer(r){try{return!!r?.closest(`[${k.ATTRIBUTES.VELT_LOCATION}], [${k.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(r){try{return r?.closest(`[${k.ATTRIBUTES.VELT_LOCATION}], [${k.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(r){try{return typeof r=="string"?!!r?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:r,elementClassNames:i,elementQuerySelectors:o}){try{let s=[];if(r?.length)for(let a=0;a<r.length;a++){let c=document.getElementById(r[a]);c&&s.push(c)}if(i?.length)for(let a=0;a<i.length;a++){let c=document.getElementsByClassName(i[a]);for(let l=0;l<c.length;l++){let d=c[l];d&&d instanceof HTMLElement&&s.push(d)}}if(o?.length)for(let a=0;a<o.length;a++){let c=document.querySelectorAll(o[a]);for(let l=0;l<c.length;l++){let d=c[l];d&&d instanceof HTMLElement&&s.push(d)}}return s}catch(s){return this.loggingService.catch("Error in DomService getListedElements: ",s),[]}}isElementInsideListedElementIds(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.getElementById(i[o]);if(s&&s.contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",o),!1}}isElementInsideListedElementClassNames(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.getElementsByClassName(i[o]);for(let a=0;a<s.length;a++)if(s[a].contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",o),!1}}isElementInsideListedElementQuerySelectors(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.querySelectorAll(i[o]);for(let a=0;a<s.length;a++)if(s[a].contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",o),!1}}addClassToElement(r,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),r&&(r.classList?.contains(i)||r.classList?.add(i))}catch(o){this.loggingService.catch("Error in DomService addClassToElement: ",o)}}removeClassFromElement(r,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),r&&r.classList?.contains(i)&&r.classList?.remove(i)}catch(o){this.loggingService.catch("Error in DomService removeClassFromElement: ",o)}}isElementInsideParentWithAttribute(r,i,o){try{let s=r;for(;s&&s!==document.body;){if(s?.getAttribute&&s?.getAttribute(i)===o)return!0;s=s.parentElement}return!1}catch(s){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",s),!1}}setVideoEditorHandlingDelete(r){try{this.isVideoEditorHandlingDelete=r}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(r){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",r),!1}}setCustomCss(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(r)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getCustomCss$: ",r),ot(null)}}injectCustomCss(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let o=r?.shadowRoot?.querySelector(`[${k.VELT_CUSTOM_CSS}]`);if(o&&o.remove(),i?.type==="link"){let s=document.createElement("link");s.href=i?.value,s.rel="stylesheet",s.setAttribute(k.VELT_CUSTOM_CSS,"true"),r?.shadowRoot?.appendChild(s)}else{let s=document.createElement("style");s.innerHTML=this.sanitizeHtml(i?.value),s.setAttribute(k.VELT_CUSTOM_CSS,"true"),r?.shadowRoot?.appendChild(s)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}subscribeInjectCustomCss(r){try{return this.customCss$.subscribe(()=>{this.injectCustomCss(r?.nativeElement)})}catch(i){return this.loggingService.catch("Error in DomService subscribeInjectCustomCss: ",i),new gt}}trimCommentHtml(r){try{let i=document.createElement("div");i.innerHTML=r,this.removeEmptyElements(i);let o=i.innerHTML;return o=o.replace(e.MULTIPLE_NBSP_REGEX," ").replace(e.TRIM_NBSP_REGEX,"").trim(),o}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),r}}removeEmptyElements(r){try{let s=function(a){return o.test(a.innerHTML)};var i=s;let o=/^\s*(<br\s*\/?>)?\s*$/;for(;r.firstChild&&s(r.firstChild);)r.removeChild(r.firstChild);for(;r.lastChild&&s(r.lastChild);)r.removeChild(r.lastChild)}catch(o){this.loggingService.catch("Error in DomService removeEmptyElements: ",o)}}normalizeWhitespace(r){try{r.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(r){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),Sy.sanitize(r,$2)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeHtmlForPaste(r){try{let i=this.convertStylesToTags(r);return Sy.sanitize(i,{ALLOWED_TAGS:["b","strong","i","em","u","a","br"],ALLOWED_ATTR:["href","target","rel"]})}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtmlForPaste: ",i),""}}convertStylesToTags(r){try{let i=document.createElement("div");return i.innerHTML=r,this.convertBlockElementsToBr(i),this.processNodeStyles(i),i.innerHTML}catch(i){return this.loggingService.catch("Error in DomService convertStylesToTags: ",i),r}}convertBlockElementsToBr(r){try{let i=["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","SECTION","ARTICLE","HEADER","FOOTER"],o;for(;(o=r.querySelector(i.join(",")))!==null;){let s=o.parentNode;if(!s)break;for(;o.firstChild;)s.insertBefore(o.firstChild,o);o.nextSibling&&s.insertBefore(document.createElement("br"),o),s.removeChild(o)}}catch(i){this.loggingService.catch("Error in DomService convertBlockElementsToBr: ",i)}}processNodeStyles(r){try{let i=Array.from(r.childNodes);for(let o of i)if(o.nodeType===Node.ELEMENT_NODE){this.processNodeStyles(o);let s=o,a=s.style,c=o,l=a?.fontWeight;if(l==="bold"||l==="700"||l==="800"||l==="900"){let d=s.tagName?.toLowerCase();if(d!=="b"&&d!=="strong"){let h=document.createElement("b");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}if(a?.fontStyle==="italic"){let d=s.tagName?.toLowerCase();if(d!=="i"&&d!=="em"){let h=document.createElement("i");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}if((a?.textDecorationLine?.includes("underline")||a?.textDecoration?.includes("underline"))&&s.tagName?.toLowerCase()!=="u"){let h=document.createElement("u");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}}catch(i){this.loggingService.catch("Error in DomService processNodeStyles: ",i)}}sanitizeSvg(r){try{return Sy.sanitize(r,$2)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),r}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let r=new Wr;this.deviceInfo$.next(r)}catch(r){this.loggingService.catch("Error in DomService setDeviceInfo: ",r)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",r),ot(new Wr)}}getTabId(){try{let r=sessionStorage.getItem(k.SESSION_STORAGE.VELT_TAB_ID);!r&&this.tabId&&(r=this.tabId,sessionStorage.setItem(k.SESSION_STORAGE.VELT_TAB_ID,r)),!this.tabId&&r&&(this.tabId=r);let i=this.getTabIdFromWindowName();return(!r||r!==i)&&(r=ad(),this.tabId=r,sessionStorage.setItem(k.SESSION_STORAGE.VELT_TAB_ID,r),this.setTabIdToWindowName(r)),r}catch(r){return this.loggingService.catch("Error in DomService getTabId: ",r),null}}getTabIdFromWindowName(){try{return window.name}catch(r){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",r),null}}setTabIdToWindowName(r){try{window.name=r}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(r){return this.loggingService.catch("Error in DomService getDeviceInfo: ",r),new Wr}}isMobileDevice(){try{return new Wr().getDeviceType()===Ir.MOBILE}catch(r){return this.loggingService.catch("Error in DomService isMobileDevice: ",r),!1}}isTabletDevice(){try{return new Wr().getDeviceType()===Ir.TABLET}catch(r){return this.loggingService.catch("Error in DomService isTabletDevice: ",r),!1}}isDesktopDevice(){try{return new Wr().getDeviceType()===Ir.DESKTOP}catch(r){return this.loggingService.catch("Error in DomService isDesktopDevice: ",r),!1}}deepCloneElement(r){try{var i=document.createElement(r?.tagName);return Array.from(r.attributes).forEach(o=>{i.setAttribute(o.nodeName,o.nodeValue)}),r.childNodes.forEach(o=>{o.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(o)):o.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(o.nodeValue))}),i}catch(o){return this.loggingService.catch("Error in DomService deepCloneElement: ",o),r}}setRandomNumberToElementRecursive(r){try{if(!r)return;let i=Math.random().toString(36).substring(7);r&&r.setAttribute&&typeof r.setAttribute=="function"&&(r.getAttribute("velt-wireframe-id")||r.setAttribute("velt-wireframe-id",i)),Array.from(r.children).forEach(s=>{this.setRandomNumberToElementRecursive(s)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(r){this.dialogOpenedInSidebar$.next(r)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(r){if(!r)return;Array.from(r.children).forEach(o=>{if(this.removeWireframeSuffixFromTags(o),o.tagName.toLowerCase().endsWith("-wireframe")){let s=o.tagName.toLowerCase().replace("-wireframe",""),a=document.createElement(s);for(Array.from(o.attributes).forEach(c=>{a.setAttribute(c.name,c.value)});o.firstChild;)a.appendChild(o.firstChild);o.parentNode.replaceChild(a,o)}})}isMonitorDevice(){try{return new Wr().getDeviceType()===Ir.MONITOR}catch(r){return this.loggingService.catch("Error in DomService isMonitorDevice: ",r),!1}}isElementOriginallyStatic(r){try{return window.getComputedStyle(r).position==="static"||r.hasAttribute(k.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_AREA_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_TAG_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_RECORDER_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_ARROW_PIN_HOST_STATIC)}catch(i){return this.loggingService.catch("Error in DomService isElementOriginallyStatic: ",i),!1}}};e.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,e.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,e.\u0275fac=function(i){return new(i||e)(z(Zs),z(Bo),z(Rt),z(aR))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function ol(t){let e=t?.refreshToken;return typeof e=="string"&&e.length>0?e:void 0}var iw=Symbol("velt-auth-state-pending");function mre(t,e){let n=B(B({},t),e||{});return n.userId=t.userId,n.userSnippylyId=t.userSnippylyId,n.type=t.type,n.organizationId=t.organizationId,n.clientOrganizationId=t.clientOrganizationId,n.groupId=t.groupId,n.clientGroupId=t.clientGroupId,n.contacts=t.contacts,n.plan=t.plan,n.isAdmin=t.isAdmin,n.isReadOnly=t.isReadOnly,n.isAnonymous=t.isAnonymous,n.isGuest=t.isGuest,n.color=e?.color||t.color,n.textColor=e?.textColor||t.textColor,n.initial=e?.initial||n.name?.charAt(0).toUpperCase()||n.email?.charAt(0).toUpperCase()||t.initial,n?.photoUrl===void 0&&(n.photoUrl=null),n}var Ere=["userId","userSnippylyId","organizationId","clientOrganizationId","isAdmin","isReadOnly","isAnonymous","isGuest","plan","contacts"];function _re(t){if(!t||typeof t!="object")return{};let e=B({},t);for(let n of Ere)delete e[n];return e}function z2(t,e){if(!e.length)return!0;if(t.length!==e.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}var vd=(()=>{let e=class e{constructor(r,i,o,s,a,c,l,d,h){this.afAuth=r,this.configService=i,this.avatarService=o,this.coreActionsService=s,this.domService=a,this.functions=c,this.analyticsService=l,this.loggingService=d,this.serviceBook=h,this.endpointsService=X(_y),this.portableBackend$=new le(null),this.portableAuthUser$=new le(null),this.user$=new le(null),this.userOptions$=new le(null),this.userContacts$=new le(null),this.userOrganization$=new le(null),this.isPrivateCommentsEnabled$=new le(!1),this.providedUser=new so,this.portableRefreshTimer=null,this.portableToken=null,this.portableRefreshInFlightEpoch=null,this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0,this.portableRefreshWarnedEpoch=null,this.portableVisibilityHandler=null,this.loggedInUserResolveRetryDelaysMs=[2e3,8e3,3e4],this.loggedInUserResolveRetryInFlightUserId=null,this.firebaseConfig$=new le(null),this.advancedQueries$=new le(null),this.planDetails$=new le(null),this.signOutPreviousUser$=new le(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.portableAutoLoginCalled=!1,this.portableAutoLoginInFlight=Promise.resolve(),this.portableSessionEpoch=0,this.portableLocalSessionEnds=0,this.portableSignOutOwnsEpochBump=!1,this.pendingPortableRestore=null,this.portableResumeUserId=null,this.portableStorageHandler=null,this.portableSessionIdentity=null,this.reportedPortableRefreshCodes=new Set,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.portablePlanSeeded=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.onRetrySubscription=null,this.authProviderListenerGeneration=0,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.cachedActivityConfig=null,this.portableChunkReady=null,this.viewsService=null,this.crdtService=null,this.portableSavedSessionRaw=null,this.portableRenewalStopped=null,this.portableSessionStartedAt=0,this.portablePersistInFlight=Promise.resolve(),this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;"),this.serviceBook.observe(vT).subscribe(f=>{this.commentService=f??void 0}),this.serviceBook.observe(ST).subscribe(f=>{this.reactionService=f??void 0}),this.serviceBook.observe(AT).subscribe(f=>{this.areaService=f??void 0}),this.serviceBook.observe(PU).subscribe(f=>{this.activityService=f??void 0,f&&this.cachedActivityConfig&&f.setActivityFeatureConfig(this.cachedActivityConfig)}),this.serviceBook.observe(xU).subscribe(f=>{this.viewsService=f??null}),this.serviceBook.observe(kU).subscribe(f=>{this.crdtService=f??null});try{try{let f=this.configService.getAuthProxyHost();if(f){let g=this.afAuth?.config;g&&(g.apiHost=f,g.tokenApiHost=f)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(f=>{this.config=f}),this.forceReLoggedIn=localStorage.getItem(k.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Ed(this.afAuth).pipe(nn(this.afAuth.currentUser),sc(),Zn(([f,g])=>this.domService.onNetworkStatusChange$().pipe(En(E=>E),_n(1),De(()=>({previousUser:f,currentUser:g}))))).subscribe(E=>y(this,[E],function*({previousUser:f,currentUser:g}){if(!g&&f){let I=f?.stsTokenManager?.expirationTime,S=new Date().getTime(),L=I-S;S>I&&(this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.getUserForTelemetry(this.user$.value??void 0),lastLoggedInUserData:this.lastLoggedInUserData?{user:this.getUserForTelemetry(this.lastLoggedInUserData.user),autoLogin:this.lastLoggedInUserData.autoLogin,hasAuthToken:!!this.lastLoggedInUserData.userOptions?.authToken}:null,timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&f?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserForTelemetry(this.lastLoggedInUserData.user),timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),f=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",f)}),this.getUser$().pipe(ai(pp)).subscribe(f=>{let g=wR(f);this.coreActionsService.triggerAction(oo.USER_UPDATE,g),this.coreActionsService.triggerAction(oo.INIT_UPDATE,{event:oo.USER_UPDATE,payload:{user:g}})})}catch(f){this.loggingService.catch("Error in AuthService constructor: ",f)}}setApiKey(r,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",r);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=r,this.configService.setApiKey(this.apiKey),i||(i=new wT),this.configService.initConfig(i);let o=this.configService.getProxyConfig();if(o?.authHost)try{let s=this.afAuth?.config;s&&(s.apiHost=o.authHost,s.tokenApiHost=o.authHost)}catch(s){this.loggingService.catch("Error setting auth proxy config: ",s)}else try{let s=this.afAuth?.config;s&&s.apiHost!=="identitytoolkit.googleapis.com"&&(s.apiHost="identitytoolkit.googleapis.com",s.tokenApiHost="securetoken.googleapis.com")}catch(s){this.loggingService.catch("Error resetting auth proxy config: ",s)}i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Ed(this.afAuth).pipe(_n(1)).subscribe(s=>y(this,null,function*(){if(this.autoLoginCalled=!0,s){let a=yield Pp(s,!0).catch(c=>null);if(a){let{user:c}=a?.claims;this.autoLoginRequired&&(c=yield this.updateUserWithColorAndTextColor(c),this.initializeClient(c,this.buildAutoLoginOptions(),new Date().getTime(),!0,"internal-autoLogin"))}}})),!this.portableAutoLoginCalled&&this.configService.getEnablePortableBackend()===!0&&(this.portableAutoLoginCalled=!0,this.portableAutoLoginInFlight=this.autoLoginPortableSession())}catch(o){this.loggingService.catch("Error in setApiKey: ",o)}}setUsersService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=r}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setUserPermissionService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=r}catch(i){this.loggingService.catch("Error in setUserPermissionService: ",i)}}setDocService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=r}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=r}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=r}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setCommentService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=r}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setCommonDbService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=r}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(r){if(this.isVersionGreaterThanOrEqualTo4()&&!r?.organizationId)if(this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)},!0,r.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}setVeltAuthProvider(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe(),this.authProviderListenerGeneration++;let i=null;if(!r.user)return null;r.generateToken&&typeof r.generateToken=="function"&&(i=yield r.generateToken());let o=yield NR(()=>window.Velt.identify(r.user,B(B({},r.options||{}),i&&{authToken:i}),{fromProvider:!0}).catch(s=>(r.onError&&typeof r.onError=="function"&&r.onError(s),Promise.reject(s))),r.retryConfig||{retryCount:0,retryDelay:0});return o&&r.generateToken&&typeof r.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(oo.ERROR).pipe(En(s=>s.code==="token_expired"),_n(10)).subscribe(s=>y(this,null,function*(){if(s.code==="token_expired"){let a=this.authProviderListenerGeneration,c=()=>a===this.authProviderListenerGeneration,l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],d=this.docService?.getOptionsFromDocumentPaths()??void 0,h=[],f=this.docService?.getLocation();f&&h.push(f.location);let g=this.docService?.getLocations();if(g&&Object.values(g).forEach(I=>{h.push(I.location)}),(yield NR(()=>y(this,null,function*(){try{let I=yield r.generateToken?.();return c()&&I?window.Velt.identify(r.user,B(B({},r.options||{}),I&&{authToken:I}),{fromProvider:!0}):!0}catch{return!1}}),r.retryConfig||{retryCount:0,retryDelay:0}))&&c()){let I=this.docService?.getDocumentIds()?.map(j=>j.clientDocumentId)??[];z2(l.map(j=>j.id),I)&&(yield this.docService?.setDocuments({documents:l,options:d,source:"internal"}));let S=[],L=this.docService?.getLocation();L?.location?.id&&S.push(L.location.id),Object.values(this.docService?.getLocations()??{}).forEach(j=>{j?.location?.id&&S.push(j.location.id)}),z2(h.map(j=>j?.id).filter(Boolean),S)&&(yield this.docService?.setLocations({locations:h,source:"internal",options:{appendLocation:!f}}))}}}))),o}catch(i){return this.loggingService.catch("Error in setVeltAuthProvider: ",i),null}})}setUserToStorage(r){return y(this,null,function*(){try{if(r){let i=yield UT(r,r?.userId??"");localStorage.setItem(k.LOCAL_STORAGE.VELT_IDENTIFY_USER,i)}}catch(i){this.loggingService.catch("Error in setUserToStorage: ",i)}})}getUserFromStorage(r){return y(this,null,function*(){try{let i=localStorage.getItem(k.LOCAL_STORAGE.VELT_IDENTIFY_USER);return i?yield hp(i,r?.userId??""):null}catch(i){return this.loggingService.catch("Error in getUserFromStorage: ",i),null}})}setIsPrivateCommentsEnabled(r){try{this.isPrivateCommentsEnabled$.next(r)}catch(i){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",i)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(r){return y(this,null,function*(){try{let i=JSON.parse(JSON.stringify(r??{})),o=yield this.getUserFromStorage(i);return!o||Object.keys(o).length===0?(delete i?.color,delete i?.textColor,i):(o?.color&&(i.color=o?.color),o?.textColor&&(i.textColor=o?.textColor),i)}catch(i){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",i),r}})}updateUserIfRequired(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let i=yield this.getUserFromStorage(r),o={};r.color&&r.color!==i?.color&&(o.color=r.color),r.textColor&&r.textColor!==i?.textColor&&(o.textColor=r.textColor),Object.keys(o).length>0&&r.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:r.clientOrganizationId,user:me(B({},o),{userId:r.userId})})}catch(i){this.loggingService.catch("Error in updateUserIfRequired: ",i)}})}initializeClient(r,i,o,s,a){return y(this,null,function*(){try{if(this.autoLoginRequired=!1,this.portableResumeUserId=null,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=r,this.pendingUserLoginSource=a;else{r.userSnippylyId=YV(this.configService.getApiKey(),r.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=o;let c=this.portableSessionEpoch,l=this.portableLocalSessionEnds,d=yield Ed(this.afAuth).pipe(_n(1)).toPromise().catch(E=>null),h=!0;this.providedUser=JSON.parse(JSON.stringify(r));let f=!d&&s?this.takePendingPortableRestore(r,i):null,g=f?.envelope??null;if(g){if(this.loggingService.log("%c[WB] Calling FUNCTION: restorePortableSession","color: green;"),this.validateOrganizationId(r),!(yield this.applyIdentifyResponse(r,g.res,s)))return;h=!1,this.trackAutoAuthSuccess(r,a)}else if(!d&&s&&a==="internal-autoLogin"&&this.configService?.getEnablePortableBackend()===!0)return f?.resume?(qn("session.resume-skipped",f.overtaken?"overtaken":"not restorable"),this.loggingService.log("Velt [portable backend]: not following the session another page saved; waiting for identify().")):f?.overtaken?(qn("session.restore-discarded"),this.loggingService.log("Velt [portable backend]: discarding a reload restore that a sign-out or a new identify overtook."),this.clearPersistedPortableSessionIfUnchanged(f.raw)):(this.loggingService.log("Velt [portable backend]: nothing restorable on reload; waiting for identify()."),this.clearPersistedPortableSession()),this.initializeClientToken=0,this.checkForPendingLogin(),null;if(d){let E=yield Pp(d,!0).catch(j=>null);if(!E)return;let{user:I,firebaseConfig:S,advancedQueries:L}=E.claims;$N({userSnippylyId:d?.uid,groupId:I?.groupId,organizationId:I?.organizationId},r,i)||!s&&r?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(r)||this.forceReLoginRequiredForRegion(r,S)||this.forceReLoginRequiredForCommentViews(r)?(localStorage.setItem(k.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(k.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal"),c=this.portableSessionEpoch,l=this.portableLocalSessionEnds):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(r),this.validateOrganizationId(r),this.setFirebaseConfig(S),this.setAdvancedQueries(L),I&&(this.providedUser.isAdmin=!!I.isAdmin),this.initializeSignedInUser(d,s,r),h=!1,this.trackAutoAuthSuccess(r,a))}else if(h&&c===this.portableSessionEpoch&&this.isPortableIdentityChange(r,i)){let E=this.signOutUser("internal");c=this.portableSessionEpoch,l=this.portableLocalSessionEnds,yield E}if(h){this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:a},!0,r.userSnippylyId,r.userId);let E=yield this.requestIdentify(r,i?.authToken);if(E.error){if(this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_FAILED,me(B({apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)},E),{source:a}),!0,r.userSnippylyId,r.userId),E.error&&typeof E.error=="string")if(this.isTokenExpiredIdentifyError(E))this.emitIdentifyTokenExpiredError(E,r,a);else{let S=E;this.coreActionsService.triggerAction(oo.ERROR,S)}throw E}else this.tokenExpiredErrorCount=0;if(this.shouldHandlePortableBackend(E)&&this.isPortableIdentifyOvertaken(c,l,s))return this.loggingService.log("Velt [portable backend]: discarding an identify response that a sign-out overtook."),this.initializeClientToken=0,this.checkForPendingLogin(),null;if(this.shouldHandlePortableBackend(E)&&c!==this.portableSessionEpoch&&(this.autoLoginRequired=!1,this.portableResumeUserId=null),this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:a},!0,r.userSnippylyId,r.userId),this.validateOrganizationId(r),!(yield this.applyIdentifyResponse(r,E,s)))return}this.initializeClientToken=0,this.lastLoggedInUserData={user:r,userOptions:i,initializeClientToken:o,autoLogin:s},this.checkForPendingLogin()}return r}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),i?.throwError?Promise.reject(c):Promise.resolve(null)}})}isPortableIdentifyOvertaken(r,i,o){let s=this.portableSessionEpoch-r;return o?s!==0:s!==this.portableLocalSessionEnds-i}isPortableIdentityChange(r,i){try{if(!this.portableAuthUser$.value)return!1;let o=this.portableSessionIdentity?.user??this.user$.value;return o?$N(o,r,i):!1}catch(o){return this.loggingService.catch("Error in isPortableIdentityChange: ",o),!1}}isVersionGreaterThanOrEqualTo4(){try{let r=Wc();return(r?parseInt(r.split(".")?.[0]||"0"):0)>=4}catch(r){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",r),!1}}isVersion4Point5(){try{let r=Wc();if(r){let i=r.split("."),o=parseInt(i[0]||"0"),s=parseInt(i[1]||"0"),a=parseInt(i[2]||"0");if(o>=4&&s>=5)return o===4&&s===5&&a===0?!r.toLowerCase().includes("beta"):!0}return!1}catch(r){return this.loggingService.catch("Error in isVersion4Point5: ",r),!1}}forceReLoginRequiredForAdvancedQueries(r){try{let i=this.isVersionGreaterThanOrEqualTo4(),o=!1;try{let s=localStorage.getItem(k.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);s&&(o=JSON.parse(s)?.advancedQueriesEnabled)}catch(s){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",s)}return!!(i&&r.organizationId&&!o)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForCommentViews(r){try{let i=this.isVersion4Point5(),o=!1;try{let s=localStorage.getItem(k.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);s&&(o=JSON.parse(s))}catch(s){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",s)}return!!(i&&r.organizationId&&!o)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",i),!1}}forceReLoginRequiredForRegion(r,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&r.organizationId&&!i?.region)}catch(o){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",o),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(r){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:B(B({},this.endpointsService.getFirebaseConfig()),r)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}requestIdentify(r,i){return y(this,null,function*(){let o=Wc();this.usersService?.userResolverConfigured?.()&&(r=MR(r));let s=this.endpointsService.getPortableIdentifyUrl();return s?ZG({url:s,apiKey:this.apiKey,user:r,version:o,authToken:i}):(yield Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("validateClient"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.apiKey,user:r,version:o,authToken:i}))?.data})}requestPortableRefresh(r){return y(this,null,function*(){let i=this.endpointsService.getPortableIdentifyUrl();return!i||$c(i)?UN("the portable identify URL is not configured; the renewal credential was not sent"):n2({url:t2(i,"refresh"),apiKey:this.apiKey,refreshToken:r,timeoutMs:QG()})})}reportPortableRefreshMisconfigured(r){try{let i=String(r?.code??"unknown");if(this.reportedPortableRefreshCodes.has(i))return;if(this.reportedPortableRefreshCodes.add(i),i===e.PORTABLE_NO_CREDENTIAL_ENVELOPE.code){console.error("Velt [portable backend]: this session has no renewal credential for the configured gateway (the identify answer carried no refreshToken, or selfHosted.portableBackendUrl changed after sign-in), so it cannot be renewed: it is signed out and the app must identify() again. Every identify answer from portable-v0.1.6 or later carries one.");return}let o=r?.message?` (${r.message})`:"";console.error(i==="invalid-argument"?`Velt [portable backend]: the gateway rejected the session renewal as malformed: invalid-argument${o}. The SDK and gateway versions disagree on /identify/refresh; renewal is stopped for this session.`:`Velt [portable backend]: the gateway refused the session renewal: ${i}${o}. A deployment setting is wrong (the allowed origins, or the identify configuration for this API key). Renewal is stopped for this session; after the setting is fixed, a reload renews from the saved session.`)}catch{}}emitIdentifyTokenExpiredError(r,i,o){if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let s={code:"token_expired",message:"Token expired",error:r?.error,source:r?.source};this.coreActionsService.triggerAction(oo.ERROR,s)}else{let s={code:"too_many_retries",message:"Token expired. Too many retries.",error:r?.error,source:r?.source};this.coreActionsService.triggerAction(oo.ERROR,s),this.analyticsService.trackEvent(vt.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:i.userId,snippylyUserId:i.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:o},!0,i.userSnippylyId,i.userId)}}isTokenExpiredIdentifyError(r){try{return r?.code==="token_expired"||!!r?.error?.toLowerCase?.()?.includes("token expired")}catch{return!1}}shouldHandlePortableBackend(r){try{return this.configService?.getEnablePortableBackend()===!0&&p2(r)}catch(i){return this.loggingService.catch("Error in shouldHandlePortableBackend: ",i),!1}}applyIdentifyResponse(r,i,o){return y(this,null,function*(){if(this.shouldHandlePortableBackend(i)){this.portableSessionEpoch++;let s=this.portableSessionEpoch,a=ol(i),c=a?this.endpointsService.getPortableIdentifyUrl()??void 0:void 0;this.portableSessionIdentity=B({user:r,epoch:s},a?{refreshToken:a,refreshTokenIssuer:c}:{}),this.portableSessionStartedAt=Date.now();let l=this.handlePortableBackendResponse(i);this.planDetails$.value||(this.getPlanDetailsCalled=!0,this.portablePlanSeeded=!0,this.planDetails$.next({planInfo:null,isPlanExpired:!1})),yield this.applyPortableProjectConfig(i);let d=null;if(i?.token&&this.usersService?.externalUserDataProviderAvailable())try{d=yield this.resolveSignedInUserWithProvider(r,this.providedUser?.clientOrganizationId||r.clientOrganizationId)}catch(f){this.loggingService.catch("Error in resolveSignedInUserWithProvider (Tier B sign-in): ",f),d=null}if(s!==this.portableSessionEpoch)return qn("session.adopt-discarded"),this.loggingService.log("Velt [portable backend]: discarding a portable sign-in that a sign-out or a new identify overtook."),!0;let h=this.initializePortableSignedInUser(r,i,d);h&&this.probeIdentifyPermissionWhenPortableReady(h,s,l)}else if(i.firebaseConfig){this.clearPortableBackendState(),this.setFirebaseConfig(i.firebaseConfig),yield this.signInWithCustomToken(r,i.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let s=yield Pp(this.afAuth.currentUser,!0).catch(l=>null);if(!s)return!1;let{user:a,advancedQueries:c}=s.claims;this.setAdvancedQueries(c),this.providedUser.isAdmin=!!a?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,o,r)}return!0})}applyPortableProjectConfig(r){return y(this,null,function*(){try{let i=yield HN({apiEndpoint:r?.apiEndpoint,token:r?.token});if(!i)return;this.applyProjectConfig(i)}catch(i){this.loggingService.catch("Error in applyPortableProjectConfig: ",i)}})}applyProjectConfig(r){this.setIsPrivateCommentsEnabled(!!r?.isPrivateCommentsEnabled);let i=r?.activityConfig??{immutable:!1,isEnabled:!1};this.cachedActivityConfig=i,this.activityService?.setActivityFeatureConfig(i)}handlePortableBackendResponse(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: handlePortableBackendResponse","color: green;"),this.portableBackend$.next({backend:r?.backend,wsEndpoint:r?.wsEndpoint,apiEndpoint:r?.apiEndpoint});let i=g2({backend:r?.backend,token:r?.token??null,wsEndpoint:r?.wsEndpoint,apiEndpoint:r?.apiEndpoint});return this.portableChunkReady=i,this.schedulePortableTokenRefresh(r?.token??null),i}catch(i){return this.loggingService.catch("Error in handlePortableBackendResponse: ",i),null}}schedulePortableTokenRefresh(r){try{if(this.clearPortableTokenRefresh(),this.portableToken=r,!r)return;this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0;let i=l2(xp(r),Date.now());if(i!==null?this.armPortableRefreshTimer(i,"expiry"):this.loggingService.log("Velt [portable backend]: no proactive token refresh scheduled (token expiry unreadable or already past)."),typeof document<"u"&&typeof document.addEventListener=="function"){this.portableVisibilityHandler=o=>{try{let s=jN(this.portableToken,Date.now());if(qn(`page.${o?.type??"lifecycle"}`,`visibility=${typeof document<"u"?document.visibilityState:"?"} credentialExpired=${s}`),o?.type==="pageshow"&&o.persisted===!1)return;s?this.refreshPortableToken("focus"):this.checkPortableSessionAgainstStorage(`page.${o?.type??"lifecycle"}`),E2()}catch{}};for(let o of e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS)document.addEventListener(o,this.portableVisibilityHandler);typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("pageshow",this.portableVisibilityHandler)}this.armPortableStorageListener()}catch(i){this.loggingService.catch("Error scheduling portable token refresh: ",i)}}readStoredPortableSessionRaw(){try{return localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{return}}readPortableSavedSession(r){return y(this,null,function*(){try{let i;try{i=localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{return{verdict:"persist"}}if(!i){let a=this.readPortableSignOutAt();return{verdict:a!==null&&a>=this.portableSessionStartedAt?"stop":"persist"}}if(i===this.portableSavedSessionRaw)return{verdict:"persist"};let o=null;try{o=yield hp(i,this.apiKey??"")}catch{o=null}return o?.v!==1||o?.apiKey!==this.apiKey||!o?.user?.userId?{verdict:"renew-only"}:o.user.userId!==r?{verdict:"stop"}:{verdict:"persist",sharedRefreshToken:(o?.portableBackendUrl??null)===(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)?ol(o?.res):void 0}}catch(i){return this.loggingService.catch("Error in AuthService readPortableSavedSession: ",i),{verdict:"persist"}}})}recordPortableSignOut(){try{if(!this.apiKey)return;let r={};try{let i=JSON.parse(localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{r={}}r[this.apiKey]=Date.now(),localStorage.setItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT,JSON.stringify(r))}catch{}}armPortableRefreshTimer(r,i){this.cancelPortableRefreshTimer(),this.portableRefreshTimer=setTimeout(()=>this.refreshPortableToken(i),r)}cancelPortableRefreshTimer(){this.portableRefreshTimer&&(clearTimeout(this.portableRefreshTimer),this.portableRefreshTimer=null)}readPortableSignOutAt(){try{let r=JSON.parse(localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)??"null"),i=r&&this.apiKey?r[this.apiKey]:void 0;return typeof i=="number"&&Number.isFinite(i)?i:null}catch{return null}}clearPortableTokenRefresh(){try{if(this.cancelPortableRefreshTimer(),this.portableVisibilityHandler&&typeof document<"u")for(let r of e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS)document.removeEventListener(r,this.portableVisibilityHandler);this.portableVisibilityHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("pageshow",this.portableVisibilityHandler),this.portableVisibilityHandler=null,this.portableStorageHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("storage",this.portableStorageHandler),this.portableStorageHandler=null}catch{}}refreshPortableToken(r){return y(this,null,function*(){let i=this.portableSessionEpoch;if(this.portableRefreshInFlightEpoch!==i){this.portableRefreshInFlightEpoch=i;try{let o=this.portableSessionIdentity,s=o?.user;if(!o||o.epoch!==i||!s?.userId||!this.portableBackend$.value)return;if(this.portableRenewalStopped?.epoch===i){qn("credential.refresh-skipped",`${this.portableRenewalStopped.reason}; waiting for identify()`);return}let a=yield this.readPortableSavedSession(s.userId);if(i!==this.portableSessionEpoch)return;if(a.verdict==="stop"){this.endPortableSessionFromAnotherPage(s,`refresh:${r}`);return}let c=a.sharedRefreshToken,l=this.endpointsService.getPortableIdentifyUrl()??void 0;c&&l&&this.portableSessionIdentity&&c!==this.portableSessionIdentity.refreshToken&&(qn("credential.shared-adopted"),this.portableSessionIdentity=me(B({},this.portableSessionIdentity),{refreshToken:c,refreshTokenIssuer:l}));let d=this.portableSessionIdentity??o,h=d.refreshToken&&d.refreshTokenIssuer===l?d.refreshToken:void 0;if(!h){this.reportPortableRefreshMisconfigured(e.PORTABLE_NO_CREDENTIAL_ENVELOPE),this.endPortableSessionForDeadCredential(s,e.PORTABLE_NO_CREDENTIAL_ENVELOPE,r);return}this.loggingService.log(`Velt [portable backend]: refreshing the gateway credential (${r}).`),qn("credential.refresh-requested",`reason=${r} via=refresh`);let f=yield this.requestPortableRefresh(h);if(i!==this.portableSessionEpoch){qn("credential.refresh-discarded",`reason=${r}`),this.loggingService.log("Velt [portable backend]: discarding a credential refresh that a sign-out or a new identify overtook.");return}if(!this.shouldHandlePortableBackend(f)||!f?.token){if(f?.code===VN){this.endPortableSessionForDeadCredential(s,f,r);return}if(BN.has(f?.code)){qn("credential.refresh-misconfigured",`code=${f?.code}`),this.portableRenewalStopped={epoch:i,reason:`renewal refused: ${f?.code}`},this.cancelPortableRefreshTimer(),this.reportPortableRefreshMisconfigured(f);return}this.portableRefreshFailures++,this.portableRefreshFailures>=e.PORTABLE_REFRESH_WARN_AFTER_FAILURES&&this.reportPortableRefreshFailing(f,i);let S=Date.now();jN(this.portableToken,S)&&this.portableRefreshFailuresPastExpiry++,this.armPortableRefreshTimer(u2(xp(this.portableToken),S,this.portableRefreshFailuresPastExpiry),r);return}let g=this.readStoredPortableSessionRaw(),E=yield this.readPortableSavedSession(s.userId);if(i!==this.portableSessionEpoch){qn("credential.refresh-discarded",`reason=${r}`);return}if(E.verdict==="stop"){this.endPortableSessionFromAnotherPage(s,`refresh-answered:${r}`);return}qn("credential.refreshed"),this.handlePortableBackendResponse(f);let I=ol(f)??h;this.portableSessionIdentity?.epoch===i&&(this.portableSessionIdentity=me(B({},this.portableSessionIdentity),{refreshToken:I,refreshTokenIssuer:l})),E.verdict==="persist"&&this.persistPortableSession(s,me(B({},f),{refreshToken:I}),{expectStoredRaw:g})}catch(o){this.loggingService.catch("Error refreshing portable token: ",o)}finally{this.portableRefreshInFlightEpoch===i&&(this.portableRefreshInFlightEpoch=null)}}})}reportPortableRefreshFailing(r,i){try{if(this.portableRefreshWarnedEpoch===i)return;this.portableRefreshWarnedEpoch=i,console.warn(`Velt [portable backend]: could not renew the gateway credential (${this.portableRefreshFailures} attempts in a row${r?.code?`, last: ${r.code}`:""}). The SDK keeps retrying \u2014 every 30 s while the current token is valid; once it has expired, after 30 s, doubling up to every 16 minutes, and each time the page becomes active again \u2014 and the realtime session is unavailable from the moment the token expires until a renewal succeeds. Check that the gateway's /identify/refresh endpoint is reachable and the API key is enabled.`)}catch{}}endPortableSessionForDeadCredential(r,i,o){qn("credential.refresh-credential-invalid",`reason=${o}`),this.portableSavedSessionRaw&&this.clearPersistedPortableSessionIfUnchanged(this.portableSavedSessionRaw),this.endPortableSessionLocally(r),this.emitIdentifyTokenExpiredError(i,r,"internal-portableRefresh")}endPortableSessionFromAnotherPage(r,i){qn("session.ended-elsewhere",i),this.loggingService.log("Velt [portable backend]: another page signed out or signed in another user; this page's session ends too."),this.endPortableSessionLocally(r)}checkPortableSessionAgainstStorage(r){return y(this,null,function*(){try{let i=this.portableSessionEpoch,o=this.portableSessionIdentity;if(!o||o.epoch!==i||!o.user?.userId)return;let{verdict:s}=yield this.readPortableSavedSession(o.user.userId);s==="stop"&&i===this.portableSessionEpoch&&this.endPortableSessionFromAnotherPage(o.user,r)}catch(i){this.loggingService.catch("Error checking the portable session against storage: ",i)}})}armPortableStorageListener(){try{if(this.portableStorageHandler||typeof window>"u"||typeof window.addEventListener!="function")return;this.portableStorageHandler=r=>{try{let i=r?.key;if(i!==null&&i!==k.LOCAL_STORAGE.VELT_PORTABLE_SESSION&&i!==k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)return;this.portableSessionIdentity?this.checkPortableSessionAgainstStorage("storage"):this.portableResumeUserId&&this.resumePortableSessionFromAnotherPage()}catch{}},window.addEventListener("storage",this.portableStorageHandler)}catch(r){this.loggingService.catch("Error arming the portable storage listener: ",r)}}resumePortableSessionFromAnotherPage(){let r=this.portableResumeUserId;!r||this.portableSessionIdentity||this.initializeClientToken||!this.autoLoginRequired||this.configService?.getEnablePortableBackend()!==!0||(this.portableAutoLoginInFlight=this.portableAutoLoginInFlight.then(()=>this.autoLoginPortableSession({onlyUserId:r})).catch(()=>{}))}initializePortableSignedInUser(r,i,o=null){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: initializePortableSignedInUser","color: green;"),!i?.token)return this.portableAuthUser$.value&&(this.userPermissionService?.invalidateAllPermissionsState(),this.releaseLiveUserSession("clear")),null;let s=new so;s.type="signedIn",s=B(B(B({},s),r),_re(o)),WN(s,{provided:me(B({},r),{isAdmin:c2(i?.token)}),resolved:o,avatarColor:c=>this.getUserAvatarColor(c),textColor:c=>this.getUserTextColor(c)}),this.setUserToStorage(s),this.persistPortableSession(s,i);let a=Object.assign({},s);return delete a.contacts,this.analyticsService.identifyUser(s.userSnippylyId,a,{forceReset:this.userOptions$.value?.forceReset}),this.user$.next(s),this.portableAuthUser$.next({uid:s.userSnippylyId}),s}catch(s){return this.loggingService.catch("Error in initializePortableSignedInUser: ",s),null}}clearPortableBackendState(){try{this.portableSignOutOwnsEpochBump||this.portableSessionEpoch++,this.releasePortableSession({clearStorage:!0})}catch(r){this.loggingService.catch("Error clearing portable backend state: ",r)}}releaseLiveUserSession(r){this.resetServicesCache(),this.user$.next(null),r==="local"?this.releasePortableSession({clearStorage:!1}):this.clearPortableBackendState()}releasePortableSession(r){this.portablePlanSeeded&&(this.portablePlanSeeded=!1,this.getPlanDetailsCalled=!1),this.pendingPortableRestore=null,this.portableSessionIdentity=null,r.clearStorage&&(this.portableAutoLoginCalled||this.configService?.getEnablePortableBackend()===!0)&&this.clearPersistedPortableSession(),!(!this.portableBackend$.value&&!this.portableAuthUser$.value)&&(this.clearPortableTokenRefresh(),this.portableToken=null,this.portableChunkReady=null,this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0,this.portableBackend$.next(null),this.portableAuthUser$.next(null),this.user$.next(null),m2())}endPortableSessionLocally(r){try{this.userPermissionService?.invalidateAllPermissionsState(),this.portableSessionEpoch++,this.portableLocalSessionEnds++,this.releaseLiveUserSession("local"),this.autoLoginRequired=!0,this.portableResumeUserId=r?.userId??null,this.armPortableStorageListener()}catch(i){this.loggingService.catch("Error ending the portable session: ",i)}}trackAutoAuthSuccess(r,i){this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:i})}buildAutoLoginOptions(){return this.userOptions$?.value?me(B({},this.userOptions$.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{}}persistPortableSession(r,i,o){let s=this.portableSessionEpoch;return this.portablePersistInFlight=this.portablePersistInFlight.then(()=>this.writePortableSessionEnvelope(r,i,s,o?.expectStoredRaw)).catch(()=>{}),this.portablePersistInFlight}writePortableSessionEnvelope(r,i,o,s){return y(this,null,function*(){try{if(!i?.token||!r?.userId||!this.apiKey)return;let a=this.user$.value;if(a?.userSnippylyId&&r.userSnippylyId&&a.userSnippylyId!==r.userSnippylyId)return;let c=this.getUserWithoutContacts(r);if(!c)return;let l={v:1,apiKey:this.apiKey,portableBackendUrl:this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null,user:c,res:B({backend:i.backend,wsEndpoint:i.wsEndpoint,apiEndpoint:i.apiEndpoint,token:i.token},ol(i)?{refreshToken:ol(i)}:{})},d=yield UT(l,this.apiKey);if(o!==this.portableSessionEpoch){this.loggingService.log("Velt [portable backend]: dropping a session envelope write that a sign-out or a new identify overtook.");return}if(s!==void 0&&localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)!==s){this.loggingService.log("Velt [portable backend]: not re-persisting a refreshed credential \u2014 another page changed the saved session meanwhile.");return}let h=this.readPortableSignOutAt();if(h!==null&&h>this.portableSessionStartedAt){this.loggingService.log("Velt [portable backend]: not persisting the session \u2014 another page signed out after it began.");return}typeof d=="string"&&!d.startsWith("{")&&d!==JSON.stringify(l)&&(localStorage.setItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION,d),this.portableSavedSessionRaw=d)}catch(a){this.loggingService.catch("Error in writePortableSessionEnvelope: ",a)}})}readPersistedPortableSession(){return y(this,null,function*(){try{let r=localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION);if(!r)return null;let i=yield hp(r,this.apiKey??"");return i?i.v!==1||i.apiKey!==this.apiKey||!i.user?.userId||!i.res?.token?(this.clearPersistedPortableSession(),null):(this.portableSavedSessionRaw=r,{envelope:i,raw:r}):null}catch(r){return this.loggingService.catch("Error in readPersistedPortableSession: ",r),null}})}clearPersistedPortableSession(){this.portableSavedSessionRaw=null;try{localStorage.removeItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{}}clearPersistedPortableSessionIfUnchanged(r){try{r&&localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)===r&&this.clearPersistedPortableSession()}catch{}}isPortableTokenNearExpiry(r){let i=xp(r);return i===null||i-Date.now()<=GN}isPortableRestoreConfigured(){try{let r=this.endpointsService?.getPortableIdentifyUrl?.();return this.configService?.getEnablePortableBackend()===!0&&!!r&&!$c(r)}catch{return!1}}isRestorablePortableSession(r,i,o){try{if(!this.isPortableRestoreConfigured()||o?.forceReset||r.portableBackendUrl!==(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)||!nl(r.res?.apiEndpoint)||r.user?.userSnippylyId!==i?.userSnippylyId)return!1;let s=this.user$.value;return s?.userSnippylyId&&s.userSnippylyId!==r.user.userSnippylyId||this.isPortableTokenNearExpiry(r.res.token)?!1:this.shouldHandlePortableBackend(r.res)}catch(s){return this.loggingService.catch("Error in isRestorablePortableSession: ",s),!1}}takePendingPortableRestore(r,i){let o=this.pendingPortableRestore;if(this.pendingPortableRestore=null,!o)return null;let s=o.resume===!0;return o.epoch!==this.portableSessionEpoch?{envelope:null,overtaken:!0,raw:o.raw,resume:s}:{envelope:this.isRestorablePortableSession(o.envelope,r,i)?o.envelope:null,overtaken:!1,raw:o.raw,resume:s}}autoLoginPortableSession(r){return y(this,null,function*(){let i=this.portableSessionEpoch,o=()=>i!==this.portableSessionEpoch||!this.autoLoginRequired,s=!!r?.onlyUserId;try{let a=yield this.readPersistedPortableSession(),c=a?.envelope;if(!a||!c||o()||s&&c.user?.userId!==r?.onlyUserId)return;if(!this.isPortableRestoreConfigured()){s||this.clearPersistedPortableSession();return}if(c.portableBackendUrl!==(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)){s||(this.loggingService.log("Velt [portable backend]: the persisted session belongs to a different gateway; dropped."),this.clearPersistedPortableSession());return}let l=c;if(this.isPortableTokenNearExpiry(c.res.token)){let h=ol(c.res);if(!h){this.loggingService.log("Velt [portable backend]: the persisted session has no renewal credential; waiting for identify()."),this.clearPersistedPortableSessionIfUnchanged(a.raw);return}qn("credential.restore-renew","via=refresh");let f=yield this.requestPortableRefresh(h);if(o())return;if(!this.shouldHandlePortableBackend(f)||!f?.token){if(f?.code==="network_error"){this.loggingService.log("Velt [portable backend]: could not reach the gateway to renew the persisted session; keeping it for the next attempt.");return}if(BN.has(f?.code)&&this.reportPortableRefreshMisconfigured(f),f?.code!==VN){this.loggingService.log(`Velt [portable backend]: the persisted session's renewal was refused for now (${f?.code??"no code"}); keeping it for the next attempt.`);return}this.loggingService.log("Velt [portable backend]: the persisted session could not be renewed on reload; waiting for identify()."),this.clearPersistedPortableSessionIfUnchanged(a.raw);return}let g=ol(f)??h;l=me(B({},c),{res:{backend:f.backend,wsEndpoint:f.wsEndpoint,apiEndpoint:f.apiEndpoint,token:f.token,refreshToken:g}})}if(o())return;this.pendingPortableRestore=B({envelope:l,epoch:i,raw:a.raw},s?{resume:!0}:{});let d=this.buildAutoLoginOptions();s&&delete d.forceReset,yield this.initializeClient(B({},l.user),d,new Date().getTime(),!0,"internal-autoLogin")}catch(a){this.loggingService.catch("Error in autoLoginPortableSession: ",a)}finally{this.pendingPortableRestore=null}})}getPortableBackend(){return this.portableBackend$.value}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(r){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{r&&typeof r=="object"&&localStorage.setItem(k.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(r)),this.advancedQueries$.next(r)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled(r){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&(r||!!this.getAdvancedQueries()?.advancedQueriesEnabled)}catch(i){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",i),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser||this.portableAuthUser$.value?this.user$.value:null}getProvidedOrCurrentUserId(){try{return this.providedUser?.userId??this.user$.value?.userId??void 0}catch(r){this.loggingService.catch("Error in getProvidedOrCurrentUserId: ",r);return}}scheduleLoggedInUserResolveRetry(r,i){return y(this,null,function*(){try{if(!r||this.loggedInUserResolveRetryInFlightUserId===r)return;this.loggedInUserResolveRetryInFlightUserId=r;let o=this.loggedInUserResolveRetryDelaysMs;for(let s=0;s<o.length;s++){if(yield new Promise(l=>setTimeout(l,o[s])),(this.providedUser?.userId??this.user$.value?.userId)!==r)return;let a=yield this.usersService?.resolveUsers({userIds:[r],organizationId:i,skipUserCheck:!0,forceResolve:!0,moduleName:bT.IDENTIFY});if((this.providedUser?.userId??this.user$.value?.userId)!==r)return;let c=a?.[r];if(c&&this.applyLateResolvedLoggedInUser(r,c))return}this.loggingService.catch(`User resolver did not return the logged-in user after ${o.length} retry attempts \u2014 comments created by this author will have no resolved profile until the resolver returns them`,{userId:r,organizationId:i,attempts:o.length})}catch(o){this.loggingService.catch("Error in scheduleLoggedInUserResolveRetry: ",o)}finally{this.loggedInUserResolveRetryInFlightUserId===r&&(this.loggedInUserResolveRetryInFlightUserId=null)}})}applyLateResolvedLoggedInUser(r,i){try{let o=this.user$.value;if(!o||o.userId!==r)return!1;if(!this.afAuth?.currentUser&&!this.portableAuthUser$.value)return!0;let s=mre(o,i);return this.setUserToStorage(s),this.user$.next(s),!0}catch(o){return this.loggingService.catch("Error in applyLateResolvedLoggedInUser: ",o),!1}}combinedAuthBearer$(){let r=!1;return oc([Ed(this.afAuth).pipe(nn(iw)),this.portableAuthUser$]).pipe(En(([i,o])=>(o!==null&&(r=!0),!!(i!==iw||o!==null||r))),De(([i,o])=>(i===iw?null:i)??o))}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),this.combinedAuthBearer$().pipe(Zn(r=>r?this.user$.asObservable():ot(null)),ai(pp))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getAuthState$(){return this.combinedAuthBearer$()}getIdTokenResultForUser(r,i){return Pp(r,i)}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(r){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(r.userId&&r.userId!==i?.userId||r?.groupId&&r?.groupId!==i?.groupId||r?.organizationId&&r?.organizationId!==i?.organizationId)this.providedUser=r,this.initializeClient(r,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=B(B({},this.providedUser),r),i){let o=B(B({},i),r);this.updateUserInternally(o)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(r,i,o="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return FG(this.afAuth,i).then(s=>(this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:o,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)}),s)).catch(s=>(this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:o,forceReset:this.userOptions$.value?.forceReset,message:s.message,user:this.getUserForTelemetry(r)}),s))}catch(s){return this.loggingService.catch("Error in signInWithCustomToken: ",s),Promise.reject(s)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.activityService?.resetActivityFeatureConfig()}catch(r){this.loggingService.catch("Error in clearCache: ",r)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.serviceBook.get(IT)?.clearCache(),this.viewsService?.clearCache()}catch(r){this.loggingService.catch("Error in resetServicesCache: ",r)}}initializeSignedInUser(r,i,o){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let s=new so;s.userSnippylyId=r.uid,s.type="signedIn",o&&(s=B(B({},s),o)),this.setUserToStorage(s),this.mergeUserWithProvidedUserData(s,i)}catch(s){this.loggingService.catch("Error in initializeSignedInUser: ",s)}}resolveSignedInUserWithProvider(r,i){return y(this,null,function*(){{let o=ad(),s=bT.IDENTIFY;this.coreActionsService.triggerAction(oo.USER_RESOLVER,{event:vt.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:fR.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:s,source:"internal",payload:{userIds:[r.userId],organizationId:i}});let a=yield this.usersService?.resolveUsers({userIds:[r.userId],organizationId:i,skipUserCheck:!0,uniqueId:o,moduleName:s});return a&&a[r.userId]?JSON.parse(JSON.stringify(a[r.userId]||{})):(this.scheduleLoggedInUserResolveRetry(r.userId,i),null)}})}mergeUserWithProvidedUserData(r,i){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{r.userId=this.providedUser?.userId||r.userId;let o=null;if(this.usersService?.externalUserDataProviderAvailable()){let s=this.providedUser?.clientOrganizationId||r.clientOrganizationId;o=yield this.resolveSignedInUserWithProvider(r,s),r=B(B({},r),o||{})}WN(r,{provided:this.providedUser,resolved:o,avatarColor:s=>this.getUserAvatarColor(s),textColor:s=>this.getUserTextColor(s)}),this.updateUserInternally(r)}catch(o){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",o)}})}updateUserInternally(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},r);delete i.contacts,this.analyticsService.identifyUser(r.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset});let o=this.portableBackend$.value,s=this.portableSessionEpoch;!this.getPlanDetailsCalled&&!o&&this.getPlanDetailsFromDb();let a;if(o)a=HN({apiEndpoint:o.apiEndpoint,token:this.portableToken});else{let h=Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));a=cB({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:h,userId:r?.userId??""})}let c=Promise.resolve();o?this.probeIdentifyPermissionWhenPortableReady(r,s,this.portableChunkReady):c=this.buildIdentifyPermissionProbe(r);let[l,d]=yield Promise.allSettled([a,c]);if(o){if(s!==this.portableSessionEpoch){this.loggingService.log("Velt [portable backend]: discarding an updateUser() that a sign-out or a new identify overtook.");return}l.status==="fulfilled"&&l.value&&this.applyProjectConfig(l.value)}else l.status==="fulfilled"?this.applyProjectConfig(l.value?.data):this.loggingService.warn("Failed to fetch project config:",l.reason);this.afAuth.currentUser?(this.user$.next(r),this.updateUserToFirebase(r)):this.portableAuthUser$.value&&this.user$.next(r)}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}buildIdentifyPermissionProbe(r){if(this.userPermissionService?.isPermissionProviderAvailable()&&r.clientOrganizationId){let i=[{userId:r.userId,resource:{id:r.clientOrganizationId,type:iV.ORGANIZATION,source:OT.IDENTIFY,organizationId:r.clientOrganizationId}}],o=ad();return this.coreActionsService.triggerAction(oo.PERMISSION_PROVIDER,{event:vt.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:OT.IDENTIFY,uniqueId:o,timestamp:new Date().getTime(),source:"internal",payload:{requests:i}}),this.userPermissionService?.onResourceAccessRequired({requests:i,uniqueId:o,userId:r.userId,methodName:OT.IDENTIFY,fromCache:!1})??Promise.resolve()}return Promise.resolve()}probeIdentifyPermissionWhenPortableReady(r,i,o){return y(this,null,function*(){try{if(yield o,i!==this.portableSessionEpoch||this.user$.value?.userId!==r.userId||!q2()||this.commonDbService?.isPortableBackendActive?.()!==!0)return;yield this.buildIdentifyPermissionProbe(r)}catch(s){this.loggingService.catch("Error in probeIdentifyPermissionWhenPortableReady: ",s)}})}updateUserToFirebase(r){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(r)),o=me(B({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return y(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("getPlanDetails"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Wc(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(vt.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(r){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",r),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(En(r=>!!r),De(r=>!!r?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(r,i){try{this.preSignOutFunctions.set(r,i)}catch(o){this.loggingService.catch("Error in addPreSignOutFuction: ",o)}}setUserOrganization(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===r?.organizationId?(i.metadata=r,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=r,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(Zn(r=>r?this.userOrganization$.asObservable().pipe(De(i=>i?.metadata?.organizationId===r.organizationId?i:null)):ot(null)))}signOutUser(r="internal"){return y(this,null,function*(){try{this.userPermissionService?.invalidateAllPermissionsState(),this.portableSessionEpoch++,this.portableSignOutOwnsEpochBump=!0,this.pendingPortableRestore=null,this.portableResumeUserId=null,this.portableSessionIdentity=null,(this.portableAutoLoginCalled||this.configService?.getEnablePortableBackend()===!0)&&(this.clearPersistedPortableSession(),this.recordPortableSignOut(),this.clearPortableTokenRefresh()),r==="external"&&(this.onRetrySubscription?.unsubscribe(),this.authProviderListenerGeneration++),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:r==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserForTelemetry(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:r});let i=yield Ed(this.afAuth).pipe(_n(1)).toPromise().catch(o=>null);if(i){this.releaseLiveUserSession("clear");for(let[o,s]of this.preSignOutFunctions)try{yield s(i)}catch(a){this.loggingService.catch(`Error in signOutUser ${o} function: `,a)}return this.user$.next(null),yield tB(1e3),UG(this.afAuth).catch(o=>{this.loggingService.catch("Error in signOutUser:",o)})}else return(this.portableAuthUser$.value||this.portableBackend$.value)&&this.releaseLiveUserSession("clear"),Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}finally{this.portableSignOutOwnsEpochBump=!1}})}isFeatureAllowed(r){return WV(this.config,this.user$.value,r)}getUserWithoutContacts(r){try{if(r){let i=JSON.parse(JSON.stringify(r));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForTelemetry(r){try{let i=this.getUserWithoutContacts(r);return i?this.usersService?.userResolverConfigured?.()?MR(i):i:null}catch(i){return this.loggingService.catch("Error in getUserForTelemetry: ",i),null}}getUserForClient(r){try{return wR(r)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}getUserAvatarColor(r){try{return r?this.avatarService.generateUserColor(jc(r)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(r){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(r){try{r.forEach(i=>{try{i?.color||(i.color=this.getUserAvatarColor(i?.userId)),i?.textColor||(i.textColor=this.getUserTextColor(i?.userId)),!i?.initial&&(i?.name||i?.email)&&(i.initial=i.name?.charAt(0).toUpperCase()||i.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};e.PORTABLE_REFRESH_WARN_AFTER_FAILURES=3,e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS=["visibilitychange","resume"],e.PORTABLE_NO_CREDENTIAL_ENVELOPE={error:"No renewal credential.",code:"no_renewal_credential",message:"the session has no renewal credential for the configured gateway",source:"identify"},e.\u0275fac=function(i){return new(i||e)(z(Zc),z(fo),z(T2),z(y2),z(W2),z(Zo),z(Zs),z(Rt),z(CT))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Y2="@firebase/database",X2="1.0.20";var ub="";function Tre(t){ub=t}var hw=class{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Pt(n))}get(e){let n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:hd(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}};var fw=class{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return zr(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}};var Nj=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){let e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new hw(e)}}catch{}return new fw},al=Nj("localStorage"),pw=Nj("sessionStorage");var Dd=new qr("@firebase/database"),wj=(function(){let t=1;return function(){return t++}})(),bj=function(t){let e=bB(t),n=new HT;n.update(e);let r=n.digest();return fd.encodeByteArray(r)},cg=function(...t){let e="";for(let n=0;n<t.length;n++){let r=t[n];Array.isArray(r)||r&&typeof r=="object"&&typeof r.length=="number"?e+=cg.apply(null,r):typeof r=="object"?e+=Pt(r):e+=r,e+=" "}return e},cl=null,Q2=!0,yre=function(t,e){Y(!e||t===!0||t===!1,"Can't turn on custom loggers persistently."),t===!0?(Dd.logLevel=we.VERBOSE,cl=Dd.log.bind(Dd),e&&pw.set("logging_enabled",!0)):typeof t=="function"?cl=t:(cl=null,pw.remove("logging_enabled"))},ln=function(...t){if(Q2===!0&&(Q2=!1,cl===null&&pw.get("logging_enabled")===!0&&yre(!0)),cl){let e=cg.apply(null,t);cl(e)}},lg=function(t){return function(...e){ln(t,...e)}},gw=function(...t){let e="FIREBASE INTERNAL ERROR: "+cg(...t);Dd.error(e)},rs=function(...t){let e=`FIREBASE FATAL ERROR: ${cg(...t)}`;throw Dd.error(e),new Error(e)},Fn=function(...t){let e="FIREBASE WARNING: "+cg(...t);Dd.warn(e)},Ire=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&Fn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Xy=function(t){return typeof t=="number"&&(t!==t||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)},vre=function(t){if(co()||document.readyState==="complete")t();else{let e=!1,n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}e||(e=!0,t())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},ul="[MIN_NAME]",sa="[MAX_NAME]",ml=function(t,e){if(t===e)return 0;if(t===ul||e===sa)return-1;if(e===ul||t===sa)return 1;{let n=J2(t),r=J2(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}},Sre=function(t,e){return t===e?0:t<e?-1:1},Gp=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+Pt(e))},db=function(t){if(typeof t!="object"||t===null)return Pt(t);let e=[];for(let r in t)e.push(r);e.sort();let n="{";for(let r=0;r<e.length;r++)r!==0&&(n+=","),n+=Pt(e[r]),n+=":",n+=db(t[e[r]]);return n+="}",n},Oj=function(t,e){let n=t.length;if(n<=e)return[t];let r=[];for(let i=0;i<n;i+=e)i+e>n?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r};function un(t,e){for(let n in t)t.hasOwnProperty(n)&&e(n,t[n])}var Mj=function(t){Y(!Xy(t),"Invalid JSON number");let e=11,n=52,r=(1<<e-1)-1,i,o,s,a,c;t===0?(o=0,s=0,i=1/t===-1/0?1:0):(i=t<0,t=Math.abs(t),t>=Math.pow(2,1-r)?(a=Math.min(Math.floor(Math.log(t)/Math.LN2),r),o=a+r,s=Math.round(t*Math.pow(2,n-a)-Math.pow(2,n))):(o=0,s=Math.round(t/Math.pow(2,1-r-n))));let l=[];for(c=n;c;c-=1)l.push(s%2?1:0),s=Math.floor(s/2);for(c=e;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);l.push(i?1:0),l.reverse();let d=l.join(""),h="";for(c=0;c<64;c+=8){let f=parseInt(d.substr(c,8),2).toString(16);f.length===1&&(f="0"+f),h=h+f}return h.toLowerCase()},Are=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Cre=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function Dre(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");let r=new Error(t+" at "+e._path.toString()+": "+n);return r.code=t.toUpperCase(),r}var Rre=new RegExp("^-?(0*)\\d{1,10}$"),Nre=-2147483648,wre=2147483647,J2=function(t){if(Rre.test(t)){let e=Number(t);if(e>=Nre&&e<=wre)return e}return null},xd=function(t){try{t()}catch(e){setTimeout(()=>{let n=e.stack||"";throw Fn("Exception was thrown by user callback.",n),e},Math.floor(0))}},bre=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Wp=function(t,e){let n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};var mw=class{constructor(e,n){this.appCheckProvider=n,this.appName=e.name,rr(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=n?.getImmediate({optional:!0}),this.appCheck||n?.get().then(r=>this.appCheck=r)}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((n,r)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(r=>r.addTokenListener(e))}notifyForInvalidToken(){Fn(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}};var Ew=class{constructor(e,n,r){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(ln("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,r)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.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/.',Fn(e)}},zp=(()=>{class t{constructor(n){this.accessToken=n}getToken(n){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(n){n(this.accessToken)}removeTokenChangeListener(n){}notifyForInvalidToken(){}}t.OWNER="owner";return t})(),Cy="5",Lj="v",Pj="s",xj="r",kj="f",Fj=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Uj="ls",Vj="p",_w="ac",Bj="websocket",Gj="long_polling";var Dy=class{constructor(e,n,r,i,o=!1,s="",a=!1,c=!1,l=null){this.secure=n,this.namespace=r,this.webSocketOnly=i,this.nodeAdmin=o,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=al.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()&&al.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}};function Ore(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function jj(t,e,n){Y(typeof e=="string","typeof type must == string"),Y(typeof n=="object","typeof params must == object");let r;if(e===Bj)r=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===Gj)r=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);Ore(t)&&(n.ns=t.namespace);let i=[];return un(n,(o,s)=>{i.push(o+"="+s)}),r+i.join("&")}var Tw=class{constructor(){this.counters_={}}incrementCounter(e,n=1){zr(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return EB(this.counters_)}};var ow={},sw={};function hb(t){let e=t.toString();return ow[e]||(ow[e]=new Tw),ow[e]}function Mre(t,e){let n=t.toString();return sw[n]||(sw[n]=e()),sw[n]}var yw=class{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,n){for(this.pendingResponses[e]=n;this.pendingResponses[this.currentResponseNum];){let r=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<r.length;++i)r[i]&&xd(()=>{this.onMessage_(r[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}};var Z2="start",Lre="close",Pre="pLPCommand",xre="pRTLPCB",Hj="id",$j="pw",Wj="ser",kre="cb",Fre="seg",Ure="ts",Vre="d",Bre="dframe",zj=1870,qj=30,Gre=zj-qj,jre=25e3,Hre=3e4,Ry=class t{constructor(e,n,r,i,o,s,a){this.connId=e,this.repoInfo=n,this.applicationId=r,this.appCheckToken=i,this.authToken=o,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=lg(e),this.stats_=hb(n),this.urlFn=c=>(this.appCheckToken&&(c[_w]=this.appCheckToken),jj(n,Gj,c))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new yw(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Hre)),vre(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Iw((...o)=>{let[s,a,c,l,d]=o;if(this.incrementIncomingBytes_(o),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,s===Z2)this.id=a,this.password=c;else if(s===Lre)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+s)},(...o)=>{let[s,a]=o;this.incrementIncomingBytes_(o),this.myPacketOrderer.handleResponse(s,a)},()=>{this.onClosed_()},this.urlFn);let r={};r[Z2]="t",r[Wj]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(r[kre]=this.scriptTagHolder.uniqueCallbackIdentifier),r[Lj]=Cy,this.transportSessionId&&(r[Pj]=this.transportSessionId),this.lastSessionId&&(r[Uj]=this.lastSessionId),this.applicationId&&(r[Vj]=this.applicationId),this.appCheckToken&&(r[_w]=this.appCheckToken),typeof location<"u"&&location.hostname&&Fj.test(location.hostname)&&(r[xj]=kj);let i=this.urlFn(r);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){t.forceAllow_=!0}static forceDisallow(){t.forceDisallow_=!0}static isAvailable(){return co()?!1:t.forceAllow_?!0:!t.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!Are()&&!Cre()}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){let n=Pt(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);let r=UR(n),i=Oj(r,Gre);for(let o=0;o<i.length;o++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[o]),this.curSegmentNum++}addDisconnectPingFrame(e,n){if(co())return;this.myDisconnFrame=document.createElement("iframe");let r={};r[Bre]="t",r[Hj]=e,r[$j]=n,this.myDisconnFrame.src=this.urlFn(r),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let n=Pt(e).length;this.bytesReceived+=n,this.stats_.incrementCounter("bytes_received",n)}},Iw=class t{constructor(e,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0,co())this.commandCB=e,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=wj(),window[Pre+this.uniqueCallbackIdentifier]=e,window[xre+this.uniqueCallbackIdentifier]=n,this.myIFrame=t.createIFrame_();let o="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(o='<script>document.domain="'+document.domain+'";<\/script>');let s="<html><body>"+o+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(s),this.myIFrame.doc.close()}catch(a){ln("frame writing exception"),a.stack&&ln(a.stack),ln(a)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||ln("No IE domain setting required")}catch{let r=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+r+"';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)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;let e={};e[Hj]=this.myID,e[$j]=this.myPW,e[Wj]=this.currentSerial;let n=this.urlFn(e),r="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+qj+r.length<=zj;){let s=this.pendingSegs.shift();r=r+"&"+Fre+i+"="+s.seg+"&"+Ure+i+"="+s.ts+"&"+Vre+i+"="+s.d,i++}return n=n+r,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,r){this.pendingSegs.push({seg:e,ts:n,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);let r=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(r,Math.floor(jre)),o=()=>{clearTimeout(i),r()};this.addTag(e,o)}addTag(e,n){co()?this.doNodeLongPoll(e,n):setTimeout(()=>{try{if(!this.sendNewPolls)return;let r=this.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){let i=r.readyState;(!i||i==="loaded"||i==="complete")&&(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),n())},r.onerror=()=>{ln("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(r)}catch{}},Math.floor(1))}};var $re=16384,Wre=45e3,Ny=null;typeof MozWebSocket<"u"?Ny=MozWebSocket:typeof WebSocket<"u"&&(Ny=WebSocket);var Ad=(()=>{class t{constructor(n,r,i,o,s,a,c){this.connId=n,this.applicationId=i,this.appCheckToken=o,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=lg(this.connId),this.stats_=hb(r),this.connURL=t.connectionURL_(r,a,c,o,i),this.nodeAdmin=r.nodeAdmin}static connectionURL_(n,r,i,o,s){let a={};return a[Lj]=Cy,!co()&&typeof location<"u"&&location.hostname&&Fj.test(location.hostname)&&(a[xj]=kj),r&&(a[Pj]=r),i&&(a[Uj]=i),o&&(a[_w]=o),s&&(a[Vj]=s),jj(n,Bj,a)}open(n,r){this.onDisconnect=r,this.onMessage=n,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,al.set("previous_websocket_failure",!0);try{let i;if(co()){let o=this.nodeAdmin?"AdminNode":"Node";i={headers:{"User-Agent":`Firebase/${Cy}/${ub}/${process.platform}/${o}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(i.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(i.headers["X-Firebase-AppCheck"]=this.appCheckToken);let s=process.env,a=this.connURL.indexOf("wss://")===0?s.HTTPS_PROXY||s.https_proxy:s.HTTP_PROXY||s.http_proxy;a&&(i.proxy={origin:a})}this.mySock=new Ny(this.connURL,[],i)}catch(i){this.log_("Error instantiating WebSocket.");let o=i.message||i.data;o&&this.log_(o),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.");let o=i.message||i.data;o&&this.log_(o),this.onClosed_()}}start(){}static forceDisallow(){t.forceDisallow_=!0}static isAvailable(){let n=!1;if(typeof navigator<"u"&&navigator.userAgent){let r=/Android ([0-9]{0,}\.[0-9]{0,})/,i=navigator.userAgent.match(r);i&&i.length>1&&parseFloat(i[1])<4.4&&(n=!0)}return!n&&Ny!==null&&!t.forceDisallow_}static previouslyFailed(){return al.isInMemoryStorage||al.get("previous_websocket_failure")===!0}markConnectionHealthy(){al.remove("previous_websocket_failure")}appendFrame_(n){if(this.frames.push(n),this.frames.length===this.totalFrames){let r=this.frames.join("");this.frames=null;let i=hd(r);this.onMessage(i)}}handleNewFrameCount_(n){this.totalFrames=n,this.frames=[]}extractFrameCount_(n){if(Y(this.frames===null,"We already have a frame buffer"),n.length<=6){let r=Number(n);if(!isNaN(r))return this.handleNewFrameCount_(r),null}return this.handleNewFrameCount_(1),n}handleIncomingFrame(n){if(this.mySock===null)return;let r=n.data;if(this.bytesReceived+=r.length,this.stats_.incrementCounter("bytes_received",r.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(r);else{let i=this.extractFrameCount_(r);i!==null&&this.appendFrame_(i)}}send(n){this.resetKeepAlive();let r=Pt(n);this.bytesSent+=r.length,this.stats_.incrementCounter("bytes_sent",r.length);let i=Oj(r,$re);i.length>1&&this.sendString_(String(i.length));for(let o=0;o<i.length;o++)this.sendString_(i[o])}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(Wre))}sendString_(n){try{this.mySock.send(n)}catch(r){this.log_("Exception thrown from WebSocket.send():",r.message||r.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}t.responsesRequiredToBeHealthy=2,t.healthyTimeout=3e4;return t})(),Kj=(()=>{class t{static get ALL_TRANSPORTS(){return[Ry,Ad]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(n){this.initTransports_(n)}initTransports_(n){let r=Ad&&Ad.isAvailable(),i=r&&!Ad.previouslyFailed();if(n.webSocketOnly&&(r||Fn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),i=!0),i)this.transports_=[Ad];else{let o=this.transports_=[];for(let s of t.ALL_TRANSPORTS)s&&s.isAvailable()&&o.push(s);t.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}}t.globalTransportInitialized_=!1;return t})(),zre=6e4,qre=5e3,Kre=10*1024,Yre=100*1024,aw="t",ej="d",Xre="s",tj="r",Qre="e",nj="o",rj="a",ij="n",oj="p",Jre="h",vw=class{constructor(e,n,r,i,o,s,a,c,l,d){this.id=e,this.repoInfo_=n,this.applicationId_=r,this.appCheckToken_=i,this.authToken_=o,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=d,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=lg("c:"+this.id+":"),this.transportManager_=new Kj(n),this.log_("Connection created"),this.start_()}start_(){let 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;let n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,r)},Math.floor(0));let i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Wp(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Yre?(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>Kre?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(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){let n={t:"d",d:e};this.sendData_(n)}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(aw in e){let n=e[aw];n===rj?this.upgradeIfSecondaryHealthy_():n===tj?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===nj&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let n=Gp("t",e),r=Gp("d",e);if(n==="c")this.onSecondaryControl_(r);else if(n==="d")this.pendingDataMessages.push(r);else throw new Error("Unknown protocol layer: "+n)}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:oj,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:rj,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:ij,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let n=Gp("t",e),r=Gp("d",e);n==="c"?this.onControl_(r):n==="d"&&this.onDataMessage_(r)}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){let n=Gp(aw,e);if(ej in e){let r=e[ej];if(n===Jre){let i=Object.assign({},r);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===ij){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else n===Xre?this.onConnectionShutdown_(r):n===tj?this.onReset_(r):n===Qre?gw("Server Error: "+r):n===nj?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):gw("Unknown control packet command: "+n)}}onHandshake_(e){let n=e.ts,r=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,n),Cy!==r&&Fn("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){let 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;let n=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,r),Wp(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(zre))}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,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Wp(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(qre))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:oj,d:{}}}))}onSecondaryConnectionLost_(){let 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()&&(al.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)}};var wy=class{put(e,n,r,i){}merge(e,n,r,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,r){}onDisconnectMerge(e,n,r){}onDisconnectCancel(e,n){}reportStats(e){}};var by=class{constructor(e){this.allowedEvents_=e,this.listeners_={},Y(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){let r=[...this.listeners_[e]];for(let i=0;i<r.length;i++)r[i].callback.apply(r[i].context,n)}}on(e,n,r){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:n,context:r});let i=this.getInitialEvent(e);i&&n.apply(r,i)}off(e,n,r){this.validateEventType_(e);let i=this.listeners_[e]||[];for(let o=0;o<i.length;o++)if(i[o].callback===n&&(!r||r===i[o].context)){i.splice(o,1);return}}validateEventType_(e){Y(this.allowedEvents_.find(n=>n===e),"Unknown event: "+e)}};var Oy=class t extends by{static getInstance(){return new t}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!_p()&&(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 Y(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}};var sj=32,aj=768,He=class{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let r=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[r]=this.pieces_[i],r++);this.pieces_.length=r,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n<this.pieces_.length;n++)this.pieces_[n]!==""&&(e+="/"+this.pieces_[n]);return e||"/"}};function je(){return new He("")}function be(t){return t.pieceNum_>=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function aa(t){return t.pieces_.length-t.pieceNum_}function ct(t){let e=t.pieceNum_;return e<t.pieces_.length&&e++,new He(t.pieces_,e)}function fb(t){return t.pieceNum_<t.pieces_.length?t.pieces_[t.pieces_.length-1]:null}function Zre(t){let e="";for(let n=t.pieceNum_;n<t.pieces_.length;n++)t.pieces_[n]!==""&&(e+="/"+encodeURIComponent(String(t.pieces_[n])));return e||"/"}function Xp(t,e=0){return t.pieces_.slice(t.pieceNum_+e)}function Yj(t){if(t.pieceNum_>=t.pieces_.length)return null;let e=[];for(let n=t.pieceNum_;n<t.pieces_.length-1;n++)e.push(t.pieces_[n]);return new He(e,0)}function At(t,e){let n=[];for(let r=t.pieceNum_;r<t.pieces_.length;r++)n.push(t.pieces_[r]);if(e instanceof He)for(let r=e.pieceNum_;r<e.pieces_.length;r++)n.push(e.pieces_[r]);else{let r=e.split("/");for(let i=0;i<r.length;i++)r[i].length>0&&n.push(r[i])}return new He(n,0)}function Oe(t){return t.pieceNum_>=t.pieces_.length}function Kn(t,e){let n=be(t),r=be(e);if(n===null)return e;if(n===r)return Kn(ct(t),ct(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function eie(t,e){let n=Xp(t,0),r=Xp(e,0);for(let i=0;i<n.length&&i<r.length;i++){let o=ml(n[i],r[i]);if(o!==0)return o}return n.length===r.length?0:n.length<r.length?-1:1}function pb(t,e){if(aa(t)!==aa(e))return!1;for(let n=t.pieceNum_,r=e.pieceNum_;n<=t.pieces_.length;n++,r++)if(t.pieces_[n]!==e.pieces_[r])return!1;return!0}function Yr(t,e){let n=t.pieceNum_,r=e.pieceNum_;if(aa(t)>aa(e))return!1;for(;n<t.pieces_.length;){if(t.pieces_[n]!==e.pieces_[r])return!1;++n,++r}return!0}var Sw=class{constructor(e,n){this.errorPrefix_=n,this.parts_=Xp(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=vp(this.parts_[r]);Xj(this)}};function tie(t,e){t.parts_.length>0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=vp(e),Xj(t)}function nie(t){let e=t.parts_.pop();t.byteLength_-=vp(e),t.parts_.length>0&&(t.byteLength_-=1)}function Xj(t){if(t.byteLength_>aj)throw new Error(t.errorPrefix_+"has a key path longer than "+aj+" bytes ("+t.byteLength_+").");if(t.parts_.length>sj)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+sj+") or object contains a cycle "+sl(t))}function sl(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}var Aw=class t extends by{static getInstance(){return new t}constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{let r=!document[e];r!==this.visible_&&(this.visible_=r,this.trigger("visible",r))},!1)}getInitialEvent(e){return Y(e==="visible","Unknown event type: "+e),[this.visible_]}};var jp=1e3,rie=300*1e3,cj=30*1e3,iie=1.3,oie=3e4,sie="server_kill",lj=3,gb=(()=>{class t extends wy{constructor(n,r,i,o,s,a,c,l){if(super(),this.repoInfo_=n,this.applicationId_=r,this.onDataUpdate_=i,this.onConnectStatus_=o,this.onServerInfoUpdate_=s,this.authTokenProvider_=a,this.appCheckTokenProvider_=c,this.authOverride_=l,this.id=t.nextPersistentConnectionId_++,this.log_=lg("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_=jp,this.maxReconnectDelay_=rie,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,l&&!co())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Aw.getInstance().on("visible",this.onVisible_,this),n.host.indexOf("fblocal")===-1&&Oy.getInstance().on("online",this.onOnline_,this)}sendRequest(n,r,i){let o=++this.requestNumber_,s={r:o,a:n,b:r};this.log_(Pt(s)),Y(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),i&&(this.requestCBHash_[o]=i)}get(n){this.initConnection_();let r=new an,o={action:"g",request:{p:n._path.toString(),q:n._queryObject},onComplete:a=>{let c=a.d;a.s==="ok"?r.resolve(c):r.reject(c)}};this.outstandingGets_.push(o),this.outstandingGetCount_++;let s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),r.promise}listen(n,r,i,o){this.initConnection_();let s=n._queryIdentifier,a=n._path.toString();this.log_("Listen called for "+a+" "+s),this.listens.has(a)||this.listens.set(a,new Map),Y(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Y(!this.listens.get(a).has(s),"listen() called twice for same path/queryId.");let c={onComplete:o,hashFn:r,query:n,tag:i};this.listens.get(a).set(s,c),this.connected_&&this.sendListen_(c)}sendGet_(n){let r=this.outstandingGets_[n];this.sendRequest("g",r.request,i=>{delete this.outstandingGets_[n],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),r.onComplete&&r.onComplete(i)})}sendListen_(n){let r=n.query,i=r._path.toString(),o=r._queryIdentifier;this.log_("Listen on "+i+" for "+o);let s={p:i},a="q";n.tag&&(s.q=r._queryObject,s.t=n.tag),s.h=n.hashFn(),this.sendRequest(a,s,c=>{let l=c.d,d=c.s;t.warnOnListenWarnings_(l,r),(this.listens.get(i)&&this.listens.get(i).get(o))===n&&(this.log_("listen response",c),d!=="ok"&&this.removeListen_(i,o),n.onComplete&&n.onComplete(d,l))})}static warnOnListenWarnings_(n,r){if(n&&typeof n=="object"&&zr(n,"w")){let i=$s(n,"w");if(Array.isArray(i)&&~i.indexOf("no_index")){let o='".indexOn": "'+r._queryParams.getIndex().toString()+'"',s=r._path.toString();Fn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${o} at ${s} to your security rules for better performance.`)}}}refreshAuthToken(n){this.authToken_=n,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(n)}reduceReconnectDelayIfAdminCredential_(n){(n&&n.length===40||NB(n))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=cj)}refreshAppCheckToken(n){this.appCheckToken_=n,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let n=this.authToken_,r=RB(n)?"auth":"gauth",i={cred:n};this.authOverride_===null?i.noauth=!0:typeof this.authOverride_=="object"&&(i.authvar=this.authOverride_),this.sendRequest(r,i,o=>{let s=o.s,a=o.d||"error";this.authToken_===n&&(s==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(s,a))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},n=>{let r=n.s,i=n.d||"error";r==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(r,i)})}unlisten(n,r){let i=n._path.toString(),o=n._queryIdentifier;this.log_("Unlisten called for "+i+" "+o),Y(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,o)&&this.connected_&&this.sendUnlisten_(i,o,n._queryObject,r)}sendUnlisten_(n,r,i,o){this.log_("Unlisten on "+n+" for "+r);let s={p:n},a="n";o&&(s.q=i,s.t=o),this.sendRequest(a,s)}onDisconnectPut(n,r,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",n,r,i):this.onDisconnectRequestQueue_.push({pathString:n,action:"o",data:r,onComplete:i})}onDisconnectMerge(n,r,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",n,r,i):this.onDisconnectRequestQueue_.push({pathString:n,action:"om",data:r,onComplete:i})}onDisconnectCancel(n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",n,null,r):this.onDisconnectRequestQueue_.push({pathString:n,action:"oc",data:null,onComplete:r})}sendOnDisconnect_(n,r,i,o){let s={p:r,d:i};this.log_("onDisconnect "+n,s),this.sendRequest(n,s,a=>{o&&setTimeout(()=>{o(a.s,a.d)},Math.floor(0))})}put(n,r,i,o){this.putInternal("p",n,r,i,o)}merge(n,r,i,o){this.putInternal("m",n,r,i,o)}putInternal(n,r,i,o,s){this.initConnection_();let a={p:r,d:i};s!==void 0&&(a.h=s),this.outstandingPuts_.push({action:n,request:a,onComplete:o}),this.outstandingPutCount_++;let c=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(c):this.log_("Buffering put: "+r)}sendPut_(n){let r=this.outstandingPuts_[n].action,i=this.outstandingPuts_[n].request,o=this.outstandingPuts_[n].onComplete;this.outstandingPuts_[n].queued=this.connected_,this.sendRequest(r,i,s=>{this.log_(r+" response",s),delete this.outstandingPuts_[n],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),o&&o(s.s,s.d)})}reportStats(n){if(this.connected_){let r={c:n};this.log_("reportStats",r),this.sendRequest("s",r,i=>{if(i.s!=="ok"){let s=i.d;this.log_("reportStats","Error sending stats: "+s)}})}}onDataMessage_(n){if("r"in n){this.log_("from server: "+Pt(n));let r=n.r,i=this.requestCBHash_[r];i&&(delete this.requestCBHash_[r],i(n.b))}else{if("error"in n)throw"A server-side error has occurred: "+n.error;"a"in n&&this.onDataPush_(n.a,n.b)}}onDataPush_(n,r){this.log_("handleServerMessage",n,r),n==="d"?this.onDataUpdate_(r.p,r.d,!1,r.t):n==="m"?this.onDataUpdate_(r.p,r.d,!0,r.t):n==="c"?this.onListenRevoked_(r.p,r.q):n==="ac"?this.onAuthRevoked_(r.s,r.d):n==="apc"?this.onAppCheckRevoked_(r.s,r.d):n==="sd"?this.onSecurityDebugPacket_(r):gw("Unrecognized action received from server: "+Pt(n)+`
|
|
150
|
+
`+fn),dt&&(fn=qa(fn)),R&&ru?Lr(fn):fn},e.setConfig=function(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};au(H),eu=!0,tu=rt,Oi=lt},e.clearConfig=function(){xi=null,eu=!1,tu=null,Oi=null,R=D,O=""},e.isValidAttribute=function(H,T,N){xi||au({});let G=pt(H),V=pt(T);return typeof N=="string"&&(Om(T,N)||!bt&&In(P2,N))?!1:Xh(G,V,N)},e.addHook=function(H,T){typeof T=="function"&&sr(nt,H)&&Fp(nt[H],T)},e.removeHook=function(H,T){if(sr(nt,H)){if(T!==void 0){let N=jne(nt[H],T);return N===-1?void 0:$ne(nt[H],N,1)[0]}return S2(nt[H])}},e.removeHooks=function(H){sr(nt,H)&&(nt[H]=[])},e.removeAllHooks=function(){nt=x2()},e}var Sy=G2();var fre=/^\/\/\*\[@id='([^']+)'\]/;function rw(t){try{if(typeof t!="string")return null;let e=fre.exec(t);if(!e)return null;let n=e[1],r=t.slice(e[0].length);if(!r)return{rootId:n,segments:[]};if(!r.startsWith("/"))return null;let i=[],o="",s=0,a=null;for(let c=1;c<r.length;c++){let l=r[c];if(a){l===a&&(a=null),o+=l;continue}if(l==="'"||l==='"')a=l;else if(l==="[")s++;else if(l==="]")s--;else if(l==="/"&&s===0){if(!o)return null;i.push(o),o="";continue}o+=l}return!o||a||s!==0?null:(i.push(o),{rootId:n,segments:i})}catch{return null}}var pre=[/:r[0-9a-z]+:/i,/_r_[0-9a-z]+_/i,/«r[0-9a-z]+»/i,/^radix-/i];function H2(t){try{return t?pre.some(e=>e.test(t)):!1}catch{return!1}}function S1e(t){if(Array.isArray(t))return j2(t);if(!t||typeof t!="object"||!("documentIds"in t))return{documentIds:null};let e=t.documentIds;return Array.isArray(e)?j2(e):{documentIds:[],problem:"not-an-array"}}function j2(t){let e=t.filter(n=>typeof n=="string"||typeof n=="number"&&Number.isFinite(n)).map(n=>String(n)).filter(n=>n.length>0);return B({documentIds:Array.from(new Set(e)).sort()},e.length<t.length?{problem:"dropped-entries"}:{})}function A1e(t,e){return t===null||e===null?t===e:t.length===e.length&&t.every((n,r)=>n===e[r])}var $2={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},W2=(()=>{let e=class e{constructor(r,i,o,s){this.analyticsService=r,this.rendererFactory2=i,this.loggingService=o,this.sanitizer=s,this.smoothScrollShieldHandler=null,this.smoothScrollShieldLoadListener=null,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new le(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new le([]),this.mousedown=!1,this.windowMouseDown$=new Be,this.windowPointerMove$=new le(null),this.windowPointerUp$=new Be,this.documentSelectionChange$=new Be,this.windowClick$=new Be,this.windowScroll$=new le(null),this.windowResize$=new le(null),this.windowKeyupBackspace$=new Be,this.windowKeyupDelete$=new Be,this.windowKeyupEsc$=new Be,this.windowPopState$=new le(null),this.documentClick$=new Be,this.lastDocumentClickTarget=null,this.documentClickSubject$=new Be,this.documentFocus$=new Be,this.isShiftKeyPressed=!1,this.mutation$=new Be,this.childListMutation$=new Be,this.networkStatus$=new le(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new le({}),this.selectedAnnotationsLocationMap$=new le({}),this.selectedAnnotationsContextIdMap$=new le({}),this.recordingInProgress$=new le({}),this.deleteAnnotations$=new le([]),this.pinHighlighterClass$=new le(null),this.dialogOpenedInSidebar$=new le(!1),this.textHighlighterClass$=new le(null),this.commentPinHighlighter$=new le(!1),this.deviceInfo$=new le(new Wr),this.customCss$=new le(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=a=>{try{let c=[];return a.forEach(l=>{if(!ao(l))if(l instanceof HTMLElement){if(l.className.includes("cdk-overlay-container")||l.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(l.className.includes("cdk-overlay")){let d=!1;l.childNodes.forEach(h=>{ao(h)&&(d=!0)}),d||c.push(l)}else c.push(l)}else c.push(l)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let a=this.calculateScreenSize();this.currentScreenSize$=new le(a),this.currentMousePosition$=new le(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(sc(),lE(([c,l])=>{try{let d=l.filter(f=>!c.includes(f)),h=c.filter(f=>!l.includes(f));h.length&&h.map(g=>document.getElementById(g)).filter(g=>g).forEach(g=>{this.unlistenElementScroll&&this.unlistenElementScroll[g.id]&&this.unlistenElementScroll[g.id]()}),d.length&&d.map(g=>document.getElementById(g)).filter(g=>g).forEach(g=>{this.unlistenElementScroll[g.id]=this.renderer.listen(g,"scroll",E=>{let I=this.calculateScreenSize();this.currentScreenSize$.next(I)})})}catch(d){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",d)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?iB("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):oB("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(a){this.loggingService.catch("Error in DomService constructor: ",a)}}setDocService(r){try{this.docService=r,this.subscribeToDomEvents()}catch(i){this.loggingService.catch("Error in DomService setDocService: ",i)}}setDynamicIdPatterns(r){try{let i=r.map(o=>typeof o=="string"?new RegExp(o):o).filter(Boolean);i.length&&(this.dynamicIdPatterns=i)}catch(i){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",i)}}isLikelyDynamicId(r){try{return r?this.dynamicIdPatterns.some(i=>i.test(r)):!1}catch{return!1}}isGeneratedId(r){return this.isLikelyDynamicId(r)||H2(r)}getStableAttributes(r){try{let i={};if(!r.getAttributeNames)return i;let o=new Set(["id","class","style"]);return r.getAttributeNames().forEach(a=>{if(o.has(a)||a.includes("snippyly")||a.includes("velt"))return;let c=r.getAttribute(a);c&&c.length<=256&&(i[a]=c)}),i}catch{return{}}}buildStableElementSelector(r,i){try{if(Object.keys(i).length===0)return;let s=[r.tagName?.toLowerCase()],a=["data-","aria-","role","name","title","type"];return Object.keys(i).sort((l,d)=>{let h=a.findIndex(g=>l.startsWith(g)),f=a.findIndex(g=>d.startsWith(g));return(h===-1?99:h)-(f===-1?99:f)}).slice(0,4).forEach(l=>{let d=CSS.escape(i[l]);s.push(`[${l}="${d}"]`)}),s.join("")}catch{return}}getVisibleText(r,i=400){try{let o=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),s="",a,c=0;for(;(a=o.nextNode())&&s.length<i;){let l=(a.textContent||"").replace(/\s+/g," ").trim();if(l&&(s+=(s?" ":"")+l),c++,c>100)break}return s.slice(0,i)}catch{return""}}hashText(r){try{return GV(r)}catch{return}}generateRobustXPath(r,i){try{let o=i?.maxDepth||10,s=i?.useAbsolutePath||!1,a=[],c=r,l=0;for(;c&&c!==document.documentElement&&l<o;){let g=this.buildRobustXPathSegment(c);if(g&&(a.unshift(g),this.isStrongAnchorSegment(g)))break;c=c.parentElement,l++}if(a.length===0)return;let h=(s?"/":"//")+a.join("/");return a.some(g=>g.includes("[@")||g.includes("[contains(@class"))?h:void 0}catch{return}}buildRobustXPathSegment(r){try{let i=r.tagName.toLowerCase(),o=r.id;if(o&&!this.isLikelyDynamicId(o)&&document.querySelectorAll(`[id="${CSS.escape(o)}"]`).length===1)return`*[@id=${this.escapeXPathValue(o)}]`;let s=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let g of s){let E=r.getAttribute(g);if(E)return`${i}[@${g}=${this.escapeXPathValue(E)}]`}let a=Array.from(r.attributes).filter(g=>g.name.startsWith("data-")&&!g.name.includes("snippyly")&&!g.name.includes("velt")&&g.value.length<100).sort((g,E)=>g.value.length-E.value.length);if(a.length>0){let g=a[0];return`${i}[@${g.name}=${this.escapeXPathValue(g.value)}]`}let c=r.getAttribute("role");if(c)return`${i}[@role=${this.escapeXPathValue(c)}]`;let l=r.getAttribute("aria-label");if(l&&l.length<50)return`${i}[@aria-label=${this.escapeXPathValue(l)}]`;let d=r.getAttribute("name");if(d)return`${i}[@name=${this.escapeXPathValue(d)}]`;let h=r.getAttribute("type");if(h)return`${i}[@type=${this.escapeXPathValue(h)}]`;let f=Array.from(r.classList||[]).filter(g=>g.length>0&&g.length<40&&!g.includes("yui")&&!g.includes("velt")&&!g.includes("snippyly")&&!this.excludeClassList.includes(g)).slice(0,2);if(f.length>0){let g=f.map(E=>`contains(@class, ${this.escapeXPathValue(E)})`).join(" and ");return`${i}[${g}]`}if(r.parentElement){let g=Array.from(r.parentElement.children).filter(E=>E.tagName===r.tagName);if(g.length>1){let E=g.indexOf(r)+1;return`${i}[${E}]`}}return i}catch{return}}isStrongAnchorSegment(r){try{return!!(r.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(s=>r.includes(`[@role='${s}']`))||["data-region","data-instanceid","data-activityid"].some(s=>r.includes(`[@${s}=`)))}catch{return!1}}escapeXPathValue(r,i=!0){try{return r.includes("'")?r.includes('"')?`concat(${r.split("'").map(a=>`'${a}'`).join(`,"'",`)})`:i?`"${r}"`:r:i?`'${r}'`:r}catch{try{return`concat(${r.split("'").map(c=>`'${c}'`).join(`,"'",`)})`}catch{return i?`'${r}'`:r}}}getElementFromRobustXPath(r){try{return document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(r){try{let i=document.evaluate(r,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),o=[];for(let s=0;s<i.snapshotLength;s++){let a=i.snapshotItem(s);a instanceof Element&&o.push(a)}return o}catch{return[]}}generateAnchorRecord(r,i){try{let o=this.generateAnchorRecordForElement(r,i),s=null;if(r.parentElement&&r.parentElement instanceof HTMLElement&&cd(r.parentElement)&&r.parentElement!==document.body&&(s=r.parentElement),o&&s){let a=this.generateAnchorRecordForElement(s,i);a&&(o.parent=a)}return o}catch(o){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",o),null}}generateAnchorRecordForElement(r,i){try{if(!r)return null;let o=r,s=o.tagName?.toUpperCase();if(!s)return null;let a=o.id&&!this.isLikelyDynamicId(o.id)?o.id:void 0,c=this.getStableAttributes(o),l=this.buildStableElementSelector(o,c),d=this.getVisibleText(o),h=this.hashText(d||""),f=this.generateRobustXPath(o),g=this.getXPath(o,!1,!1,void 0,{ignoreGeneratedIds:i?.ignoreGeneratedIds}),E=this.getXPath(o,!0),I=this.getXPath(o,!0,!0);return{version:"1.0",id:a,tagName:s,elementSelector:l,robustXPath:f||void 0,xPath:g||void 0,fXPath:E||void 0,cfXPath:I||void 0,contentHash:h?{value:h,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(o){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",o),null}}resolveAnchorRecord(r){try{let i=[],o=null,s=(h,f,g=0)=>{let E=[],I=g;if(E.push({method:f,score:g}),r.tagName&&h.tagName?.toUpperCase()===r.tagName&&(I+=10,E.push({method:"tagName-match",score:10})),r.contentHash?.value){let S=this.getVisibleText(h);this.hashText(S)===r.contentHash.value&&(I+=30,E.push({method:"contentHash-match",score:30}))}i.push({el:h,score:I,by:f,scoreBreakdown:E})};if(r.id){let h=document.querySelectorAll(`#${CSS.escape(r.id)}`);if(h.length===1)return{element:h[0],matchedBy:"id",score:90};h.length>1&&h.forEach(f=>s(f,"id-duplicate",70))}if(r.elementSelector){let h=document.querySelectorAll(r.elementSelector);if(h.length===1)return{element:h[0],matchedBy:"element-selector",score:80};h.forEach(f=>s(f,"element-selector-duplicate",60))}r.robustXPath&&this.getAllElementsFromRobustXPath(r.robustXPath).slice(0,20).forEach(E=>s(E,"robustXPath",50)),r?.parent&&(o=this.resolveAnchorRecord(r.parent),o.element&&o.element.querySelectorAll(r.tagName?.toLowerCase()||"*").forEach(f=>s(f,"parent+tag",40)));let a=(h,f,g)=>{if(!h)return;let E=this.getElementFromXPath(h);E&&s(E,f||"xpath",g||30)};if(a(r.xPath,"xPath",30),a(r.cfXPath,"cfXPath",30),a(r.fXPath,"fXPath",30),r.contentHash?.value&&i.length===0){let f=g=>{let E=0;for(let I=0;I<g.length&&E<400;I++){let S=g[I];if(E++,!this.isElementVisible(S))continue;let L=this.getVisibleText(S),j=this.hashText(L);j&&j===r.contentHash?.value&&s(S,"contentHash",15)}};if(o?.element&&o?.element instanceof Element){let g=o?.element?.querySelectorAll("*");f(g)}}if(!i.length)return{element:null};i.sort((h,f)=>f.score-h.score);let c=i[0].score,l=i.filter(h=>h.score===c);if(l.length>1){let h=[{path:r.xPath,label:"xPath"},{path:r.cfXPath,label:"cfXPath"},{path:r.fXPath,label:"fXPath"}];for(let f of h)if(f.path){let g=this.getElementFromXPath(f.path);if(g){let E=l.find(I=>I.el===g);if(E)return{element:E.el,matchedBy:`${E.by}+position`,score:E.score,scoreBreakdown:E.scoreBreakdown}}}}let d=i[0];return{element:d.el,matchedBy:d.by,score:d.score,scoreBreakdown:d.scoreBreakdown}}catch(i){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",i),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(De(r=>{r?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentFocus(),this.setupSmoothScrollShield()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver(),this.teardownSmoothScrollShield())})).subscribe(),this.onDocumentClick()}catch(r){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",r)}}setScrollableElementsIds(r){try{r&&r.length&&this.scrollableElementsIds$.next(Array.from(new Set(r)))}catch(i){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",i)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(r){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+r,"color: green;"),this.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(i=>{try{if(i?.find(s=>s?.attributeName===k.VELT_IGNORE_CHANGE_DETECTION))return;let o=i.filter(s=>s.type==="childList").filter(s=>{let a=s.target;return s.removedNodes.forEach(c=>{let l=c;if(typeof l.getAttribute=="function"){let d=l.getAttribute(k.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(d!==null&&d!==""){let h=this.xpathCacheId.get(d);h!==void 0&&(this.xpathCacheId.delete(d),this.xpathCache.delete(h))}}}),ao(a)?!1:!!(this.filterSnippylyNodes(s.addedNodes).length||this.filterSnippylyNodes(s.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(o.filter(s=>!this.isAnimatingElement(s.target))):this.childListMutation$.next(o),o.push(...i.filter(s=>s.type==="attributes").filter(s=>!ao(s.target)).filter(s=>this.filterSnippylyNodes([s.target]).length).filter(s=>{if(s){let a=s.target;return a?.classList?.contains("snippyly-sidebar-panel")?!1:a?!a.getAttribute(k.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),o=o.filter(s=>{let a=!0;return Object.keys(k.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{s.target?.closest(c)&&(a=!1)}),a}),o=o.filter(s=>s.target&&cd(s.target)),this.animationFilterEnabled&&(o=o.filter(s=>!this.isAnimatingElement(s.target))),o.length&&this.mutation$.next(o)}catch(o){this.loggingService.catch("Error in DomService change detection: ",o)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let r=window;return r.gsap||r.TweenMax||r.TweenLite||r.TimelineMax||r.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):r.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):r.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):r.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):r.lottie||r.Lottie||r.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(r){try{if(!r||typeof r.closest!="function")return!1;let i=window;if(i.gsap&&typeof i.gsap.isTweening=="function"){if(i.gsap.isTweening(r))return!0;if(typeof i.gsap.getTweensOf=="function")try{if(i.gsap.getTweensOf(r).length>0)return!0}catch{}}else if(i.TweenMax&&typeof i.TweenMax.isTweening=="function"){if(i.TweenMax.isTweening(r))return!0;if(typeof i.TweenMax.getTweensOf=="function")try{if(i.TweenMax.getTweensOf(r).length>0)return!0}catch{}}let o=r.style?.cssText||"";if(o){let l=o.includes("transform")||o.includes("translate3d")||o.includes("translate(")||o.includes("scale3d")||o.includes("rotate"),d=o.includes("will-change")&&o.includes("transform"),h=o.includes("transform-style")&&o.includes("preserve-3d");if(l&&(d||h))return!0}if(r.style&&(r.style.animation!==""&&r.style.animation!=="none"||r.style.transition!==""&&r.style.transition!=="none")||r.classList?.contains("animate")||r.classList?.contains("animating")||r.classList?.contains("animated")||r.classList?.contains("animation"))return!0;let s=this.staticAnimationCache.get(r);if(s!==void 0)return s;let a=!1,c=r.className||"";return typeof c=="string"&&(c.includes("slider")&&(c.includes("bullet")||c.includes("pagination"))&&(a=!0),c.includes("swiper-pagination")&&(a=!0)),!a&&(r.hasAttribute("data-aos")||r.hasAttribute("data-motion"))&&(a=!0),!a&&r.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(a=!0),this.staticAnimationCache.set(r,a),a}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(r){this.loggingService.catch("Error in DomService unsetMutationObserver: ",r)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{vs(Hi(window,"offline").pipe(De(()=>!1)),Hi(window,"online").pipe(De(()=>!0)),new ue(r=>{r.next(navigator.onLine),r.complete()})).subscribe(r=>{this.networkStatus$.next(r)})}catch(r){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",r)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",r=>{this.windowResize$.next(r);let i=this.calculateScreenSize();this.deviceInfo$.next(new Wr),this.currentScreenSize$.next(i)})}catch(r){this.loggingService.catch("Error in DomService onWindowResize: ",r)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",r)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",r=>{this.windowScroll$.next(r);let i=this.calculateScreenSize();this.currentScreenSize$.next(i)})}catch(r){this.loggingService.catch("Error in DomService onWindowScroll: ",r)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",r)}}setupSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: setupSmoothScrollShield","color: green;");try{if(typeof window>"u"||typeof document>"u"||this.smoothScrollShieldHandler)return;if(this.isSmoothScrollLibPresent()){this.attachSmoothScrollShield();return}if(document.readyState!=="complete"&&!this.smoothScrollShieldLoadListener){let r=()=>{this.smoothScrollShieldLoadListener=null;try{if(this.smoothScrollShieldHandler)return;this.isSmoothScrollLibPresent()&&this.attachSmoothScrollShield()}catch(i){this.loggingService.catch("Error in DomService smooth-scroll shield load re-check: ",i)}};window.addEventListener("load",r,{once:!0}),this.smoothScrollShieldLoadListener=()=>window.removeEventListener("load",r)}}catch(r){this.loggingService.catch("Error in DomService setupSmoothScrollShield: ",r)}}isSmoothScrollLibPresent(){try{if(typeof window>"u"||typeof document>"u")return!1;if(window.ET_SmoothScroll)return!0;let i=document.body;return!!(i&&i.classList&&i.classList.contains("et_smooth_scroll"))}catch(r){return this.loggingService.catch("Error in DomService isSmoothScrollLibPresent: ",r),!1}}attachSmoothScrollShield(){if(this.smoothScrollShieldHandler)return;let r=/^(VELT-|SUPERFLOW-|SNIPPYLY-)/,i=s=>{try{let a=typeof s.composedPath=="function"?s.composedPath():[];for(let c=0;c<a.length;c++){let l=a[c];if(!(!l||l.nodeType!==1)&&l.tagName&&r.test(l.tagName)){s.stopImmediatePropagation();return}}}catch(a){this.loggingService.catch("Error in DomService smoothScrollShield handler: ",a)}};this.smoothScrollShieldHandler=i;let o={capture:!0,passive:!0};window.addEventListener("wheel",i,o),window.addEventListener("mousewheel",i,o),window.addEventListener("touchmove",i,o),this.unlistenWindowWheelShield=()=>window.removeEventListener("wheel",i,o),this.unlistenWindowMouseWheelShield=()=>window.removeEventListener("mousewheel",i,o),this.unlistenWindowTouchMoveShield=()=>window.removeEventListener("touchmove",i,o)}teardownSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: teardownSmoothScrollShield","color: green;");try{try{this.smoothScrollShieldLoadListener&&typeof this.smoothScrollShieldLoadListener=="function"&&(this.smoothScrollShieldLoadListener(),this.smoothScrollShieldLoadListener=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (load): ",r)}try{this.unlistenWindowWheelShield&&typeof this.unlistenWindowWheelShield=="function"&&(this.unlistenWindowWheelShield(),this.unlistenWindowWheelShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (wheel): ",r)}try{this.unlistenWindowMouseWheelShield&&typeof this.unlistenWindowMouseWheelShield=="function"&&(this.unlistenWindowMouseWheelShield(),this.unlistenWindowMouseWheelShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (mousewheel): ",r)}try{this.unlistenWindowTouchMoveShield&&typeof this.unlistenWindowTouchMoveShield=="function"&&(this.unlistenWindowTouchMoveShield(),this.unlistenWindowTouchMoveShield=null)}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (touchmove): ",r)}this.smoothScrollShieldHandler=null}catch(r){this.loggingService.catch("Error in DomService teardownSmoothScrollShield: ",r)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",r=>{this.mousedown=!0,this.windowMouseDown$.next(r),this.setPointerPosition(r)})}catch(r){this.loggingService.catch("Error in DomService onPointerDown: ",r)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",r)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",r=>{this.windowClick$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowClick: ",r)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",r)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",r=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",r)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",r)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",r=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",r)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",r)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",r=>{this.windowKeyupEsc$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",r)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",r)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",r=>{this.windowPopState$.next(r)})}catch(r){this.loggingService.catch("Error in DomService onWindowPopState: ",r)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",r)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=r=>{r?.target?.tagName?.toLowerCase()!==k.TAGS.SUPERFLOW_TOOLBAR&&(this.lastDocumentClickTarget=r?.target?new WeakRef(r.target):null,this.documentClick$.next(r),this.documentClickSubject$.next(r))},document.addEventListener("click",this.documentClickListener,!0)}catch(r){this.loggingService.catch("Error in DomService onDocumentClick: ",r)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",r)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=r=>{this.documentFocus$.next(r)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(r){this.loggingService.catch("Error in DomService onDocumentFocus: ",r)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",r)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",()=>{this.isShiftKeyPressed=!0})}catch(r){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",r)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",r)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",()=>{this.isShiftKeyPressed=!1})}catch(r){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",r)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",r)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return Hi(window,"keydown")}catch(r){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",r),nc}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",r=>{this.windowPointerMove$.next(r),this.mouseMoveEvent=r})}catch(r){this.loggingService.catch("Error in DomService addPointerMoveListener: ",r)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",r)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",r=>{this.windowPointerUp$.next(r)})}catch(r){this.loggingService.catch("Error in DomService addPointerUpListener: ",r)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",r)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",r=>{this.documentSelectionChange$.next(r)})}catch(r){this.loggingService.catch("Error in DomService addPointerUpListener: ",r)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(r){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",r)}}updateCurrentMousePosition(r){try{if(this.currentMousePosition.pageX=r.pageX,this.currentMousePosition.pageY=r.pageY,this.currentMousePosition.clientX=r.clientX,this.currentMousePosition.clientY=r.clientY,r.target){let i=this.getXPath(r.target),o=r.target;if(i?.includes("name()='svg'")){let h=this.getXPath(i);h&&(o=h.iterateNext()||r.target)}let s=o.getBoundingClientRect(),a=r.clientX-s.x,c=r.clientY-s.y,l=a*100/(s.width||1),d=c*100/(s.height||1);this.currentMousePosition.element={xpath:i,topPercentage:d,leftPercentage:l}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(i){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",i)}}getTargetElementForCursorPosition(r,i=!0,o=!1,s=!0,a,c=!0,l,d){try{let h=r,f=h?.touches?.length?h.touches[0]?.clientX:h?.clientX,g=h?.touches?.length?h.touches[0]?.clientY:h?.clientY;l&&(f=l.clientX,g=l.clientY);let E=this.getBackgroundElement(f,g,i,o);if(E&&a&&typeof a=="function"&&(E=a(E)),E){let I=this.getXPath(E,!1,!1,void 0,d),S=this.getXPath(E,!0),L=E.getBoundingClientRect(),j=f-L.x,K=g-L.y,te=j*100/(L.width||1),pe=K*100/(L.height||1),ie={xpath:I,fXpath:S,leftPercentage:te,topPercentage:pe};if(s){let A=this.getXPath(E,!0,!0);ie.cfXpath=A}if(c){let A=this.generateAnchorRecord(E,d);A&&(ie.anchor=A)}return ie}else return null}catch(h){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",h),null}}getBackgroundElement(r,i,o=!0,s=!1){try{let a=document.elementsFromPoint(r,i),c=[];a.forEach(d=>{ao(d)?c=[]:cd(d)&&c.push(d)}),s&&(c=c.filter(d=>this.isElementVisibleOnScreen(d)));let l=0;return o||c?.forEach((d,h)=>{d.tagName.toLowerCase()==="svg"&&(l=h)}),c[l]}catch(a){return this.loggingService.catch("Error in DomService getBackgroundElement: ",a),null}}getBackgroundVeltElement(r,i){try{let o=document.elementsFromPoint(r,i),s=[];return o.forEach(a=>{ao(a)&&cd(a)&&s.push(a)}),s[0]}catch(o){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",o),null}}setPointerPosition(r){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=r.pageX,this.previousMousePosition.pageY=r.pageY,this.currentMousePosition.pageX=r.pageX,this.currentMousePosition.pageY=r.pageY}catch(i){this.loggingService.catch("Error in DomService setPointerPosition: ",i)}}getCurrentWindowSize$(r){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let r=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),i=this.currentMousePosition?.pageX||r.x+200,o=Math.min(i,r.width/2),s=Math.abs(r.y),a=r.y-20;return s>50&&(a=Math.abs(r.y)+180),this.loggingService.log(r),this.loggingService.log(o),this.loggingService.log(a),{topPositionX:o,topPositionY:a}}catch(r){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",r),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(r){this.pinHighlighterClass$.next(r)}setTextHighlighterClass(r){this.textHighlighterClass$.next(r)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(r,i,o){if(r&&!Gc(r)){if(!o&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(r,this.pinHighlighterClass$.value):this.addClassToElement(r,k.SNIPPYLY_HIGHLIGHT)),i&&!r.hasAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)){let s=r.style.getPropertyValue("cursor"),a=r.style.getPropertyPriority("cursor"),c=s?{defaultCursorValue:s,defaultCursorPriority:a}:"";r.setAttribute(k.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),r.style.setProperty("cursor",i,"important")}r.setAttribute(k.SNIPPYLY_HIGHLIGHT,"true"),r.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(r){if(r&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(r,this.pinHighlighterClass$.value),this.removeClassFromElement(r,k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.VELT_IGNORE_CHANGE_DETECTION),r.hasAttribute(k.ATTRIBUTES.DEFAULT_CURSOR))){try{if(r.style.removeProperty("cursor"),r.getAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)){let i=JSON.parse(r.getAttribute(k.ATTRIBUTES.DEFAULT_CURSOR));r.style.setProperty("cursor",i.defaultCursorValue,i.defaultCursorPriority)}}catch{}r.removeAttribute(k.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(r,i,o,s=!1){try{r&&(this.addClassToElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT),s&&this.addClassToElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),r.setAttribute(k.SNIPPYLY_HIGHLIGHT,"true"),r.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true"),i&&!r.style.getPropertyValue(k.VELT_SELECTION_COLOR)&&r.style.setProperty(k.VELT_SELECTION_COLOR,i),o&&r.setAttribute(k.SNIPPYLY_HIGHLIGHT_USER_NAME,o))}catch(a){this.loggingService.catch("Error in DomService highlightUserElement: ",a)}}removeHighlightUserFromElement(r){try{r&&(this.removeClassFromElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(r,k.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT),r.removeAttribute(k.VELT_IGNORE_CHANGE_DETECTION),r.removeAttribute(k.VELT_SELECTION_COLOR),r.removeAttribute(k.SNIPPYLY_HIGHLIGHT_USER_NAME),r.style.removeProperty(k.VELT_SELECTION_COLOR))}catch(i){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",i)}}previewHighlightElement(r){r&&r.setAttribute(k.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(r){r&&r.removeAttribute(k.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(r,i=!1,o=!1,s,a){try{let c=this.calculateXPath(r,i,o,s,a);if(c&&typeof c=="string"&&c.includes("/svg")){let l=c.split("/"),d=!1;l.forEach((h,f)=>{h.includes("svg")&&(d=!0),d&&(l[f]="svg:"+h)}),c=l.join("/")}return c}catch(c){this.loggingService.catch("Error in DomService getXPath:",c)}}namespaceResolver(r){return r==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(r,i,o,s,a){try{if(r){if(typeof r=="string")return document.evaluate(r,s||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!r||r.nodeType!=1)return"";if(r.id&&document.querySelectorAll(`[id='${r.id}']`)?.length===1&&!i&&!(a?.ignoreGeneratedIds&&this.isGeneratedId(r.id)))return"//*[@id='"+r.id+"']";if(o&&r.className&&r.className.split){let l=r.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(l){let d=this.calculateXPath(r.parentNode,i,o,s,a)+"/"+r.tagName.toLowerCase(),h=Array.from(r.parentNode?.children||[]).filter(f=>f.nodeType===1&&f.tagName===r.tagName?f.className?.split(" ")?.filter(E=>E?.includes("snippyly")||E?.includes("velt")||["show-pin-cursor"].includes(E))[0]===l:!1);if(h.length>1){let f=h.indexOf(r)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${l} ')][${f}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${l} ')]`;return d}}let c=[].filter.call(r.parentNode?.children?r.parentNode?.children:[],function(l){return l.tagName==r.tagName});return this.calculateXPath(r.parentNode,i,o,void 0,a)+"/"+r.tagName.toLowerCase()+(c.length>1?"["+([].indexOf.call(c,r)+1)+"]":"")}}catch(c){this.loggingService.catch("Error in DomService calculateXPath:",c)}}getElementFromXPath(r,i=document){try{if(this.xpathCache.has(r)){let s=this.xpathCache.get(r);if(s!==void 0&&document.contains(s))return s;this.xpathCache.delete(r)}let o=this.getXPath(r,!1,!1,i);if(o){let s=o?.iterateNext();if(s!==null&&typeof s.setAttribute=="function"&&!Gc(s)){let a=ad();s.setAttribute(k.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,a),this.xpathCacheId.set(a,r)}return this.xpathCache.set(r,s),s}return null}catch(o){return this.loggingService.catch("Error in DomService getElementFromXPath:",o),null}}getElementFromTargetElement(r){try{let i=null;if(r?.anchor){let o=this.resolveAnchorRecord(r.anchor);o?.element&&(i=o.element)}else r?.xpath?i=this.getElementFromXPath(r.xpath):r?.cfXpath?i=this.getElementFromXPath(r.cfXpath):r?.fXpath&&(i=this.getElementFromXPath(r.fXpath));return i}catch(i){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",i),null}}resolveIdScopedTarget(r){try{let i=r?.anchor?.xPath||r?.xpath,o=rw(i);if(!i||!o||this.isGeneratedId(o.rootId))return{applicable:!1,element:null};let s=this.getUniqueElementById(o.rootId);if(!s||!this.isElementVisible(s)||!cd(s))return{applicable:!0,element:null};let a=d=>!!d&&s.contains(d)&&this.isElementVisible(d),c=this.getElementFromXPath(i);if(a(c))return{applicable:!0,element:c,matchedBy:"exact"};let l=r?.anchor?.robustXPath;if(l&&rw(l)?.rootId===o.rootId){let d=this.getElementFromRobustXPath(l);if(a(d))return{applicable:!0,element:d,matchedBy:"robust"}}return{applicable:!0,element:s,matchedBy:"root"}}catch(i){return this.loggingService.catch("Error in DomService resolveIdScopedTarget: ",i),{applicable:!1,element:null}}}getUniqueElementById(r){try{let i=document.querySelectorAll(`[id="${CSS.escape(r)}"]`);return i.length===1?i[0]:null}catch{return null}}getElementFromTargetTextRange(r){try{let i=null;if(r?.commonAncestorContainerAnchor){let o=this.resolveAnchorRecord(r.commonAncestorContainerAnchor);o?.element&&(i=o.element)}else r?.commonAncestorContainer&&(i=this.getElementFromXPath(r.commonAncestorContainer));return i}catch(i){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",i),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let r=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],i=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight);let o=new lp;return o.screenWidth=Math.max(...i),o.screenHeight=Math.max(...r),o.screenScrollHeight=this.pageScrollHeight,o}catch(r){return this.loggingService.catch("Error in DomService calculateScreenSize:",r),new lp}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.highestNode=void 0;let r=this.findLongestNode(document?.documentElement?.childNodes);this.highestNode=r?new WeakRef(r):void 0}catch(r){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",r)}}removeSnippylyContent(r){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let o=new DOMParser().parseFromString(r,"text/html");o.querySelectorAll("[data-snippyly-cache-id]").forEach(f=>{f.removeAttribute("data-snippyly-cache-id")}),o.querySelectorAll("[data-velt-cache-id]").forEach(f=>{f.removeAttribute("data-velt-cache-id")}),o.querySelectorAll(".comment-text-highlight").forEach(f=>{f?.parentNode?.insertBefore(document.createTextNode(f?.textContent),f),f.remove()});let l=document.createNodeIterator(o,NodeFilter.SHOW_COMMENT),d;for(;d=l.nextNode();)d?.remove();return this.mergeAdjacentTextNodes(o.body),this.sanitizeHtml(o.body.innerHTML)}catch(i){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",i),r}}mergeAdjacentTextNodes(r){try{let i=r.firstChild;for(;i;){if(i.nodeType===Node.TEXT_NODE){let o=i.nextSibling;for(;o&&o.nodeType===Node.TEXT_NODE;)i.textContent+=o.textContent,o.remove(),o=i.nextSibling}i=i.nextSibling}}catch(i){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",i)}}findLongestNode(r){let i;try{for(let o=r.length-1;o>=0;o--){if(r[o]?.scrollHeight&&r[o]?.clientHeight){let s=Math.max(r[o]?.scrollHeight,r[o]?.clientHeight);s>=this.pageScrollHeight&&(this.pageScrollHeight=s,i=r[o])}r[o]?.childNodes?.length&&(i=this.findLongestNode(r[o]?.childNodes)??i)}}catch(o){this.loggingService.catch("Error in DomService findLongestNode: ",o)}return i}resetSelectedAnnotationsMap(r=!0,i){try{let s=this.getDraftAnnotationRefs().map(d=>d.classList.contains("velt-annotation-draft-checked")?(d.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(d,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(d,"velt-comment-dialog-shake"),d.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||d.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(d,"velt-annotation-draft-checked")},100),d.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(d=>d),a=Object.keys(this.getRecordingInProgress()||{});s=[...s,...a];let c=this.selectedAnnotationsMap$.value;if(r&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let d=[];Object.keys(c).forEach(h=>{if(c[h]?.type==="tag"){let f=c[h];f?.to?.length||s.includes(h)||d.push(f)}else c[h]?.comments?.length||s.includes(h)||d.push(c[h])}),this.deleteAnnotations$.next(d),this.deleteAnnotations$.next([])}let l={};Object.keys(c).forEach(d=>{s.includes(d)&&(l[d]=c[d]),i&&(i==="comment"?["comment","videoPin"].includes(c[d]?.type)||(l[d]=c[d]):c[d]?.type!==i&&(l[d]=c[d]))}),Object.keys(l).forEach(d=>{let h=l[d]?.multiThreadAnnotationId;h&&!l[h]&&(l[h]={annotationId:h,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(l)&&this.selectedAnnotationsMap$.next(l),this.setDialogOpenedInSidebar(!1)}catch(o){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",o)}}getDraftAnnotationRefs(){let r=Array.from(document.querySelectorAll(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`));return r.push(...this.getDraftCommentAnnotationDialogs()||[]),Array.from(new Set(r))}isEmptyDraftAnnotation(r){try{let i=this.selectedAnnotationsMap$.value?.[r];return!i||i.type==="tag"||i.type==="multiThread"||i.comments?.length||Object.prototype.hasOwnProperty.call(this.getRecordingInProgress()||{},r)?!1:!this.getDraftAnnotationRefs().some(o=>o.getAttribute(k.ATTRIBUTES.VELT_ANNOTATION_DRAFT)===r)}catch(i){return this.loggingService.catch("Error in DomService isEmptyDraftAnnotation: ",i),!1}}discardEmptyDraftAnnotation(r){try{let i=this.selectedAnnotationsMap$.value||{};if(!r||!this.isEmptyDraftAnnotation(r))return!1;this.deleteAnnotations$.next([i[r]]),this.deleteAnnotations$.next([]);let o=B({},i);return delete o[r],this.selectedAnnotationsMap$.next(o),!0}catch(i){return this.loggingService.catch("Error in DomService discardEmptyDraftAnnotation: ",i),!1}}setRecordingInProgress(r,i){try{if(i)this.recordingInProgress$.next(me(B({},this.recordingInProgress$.value),{[r]:i}));else{let o=this.recordingInProgress$.value;delete o[r],this.recordingInProgress$.next(o)}}catch(o){this.loggingService.catch("Error in DomService setRecordingInProgress: ",o)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(r){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",r)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(r){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",r),{}}}getDraftCommentAnnotationDialogs(){try{let r=[],i=Array.from(document.querySelectorAll(`${k.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),o=Array.from(document.querySelectorAll(`${k.TAGS.VELT_COMMENT_DIALOG}`));return[...i,...o].forEach(a=>{if(a?.shadowRoot){let c=a.shadowRoot.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);c&&r.push(c)}else{let c=a.querySelector(`${k.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(c?.shadowRoot){let l=c.shadowRoot?.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);l&&r.push(l)}else{let l=a.querySelector(`[${k.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);l&&r.push(l)}}}),r}catch(r){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",r),[]}}getSelectedAnnotationsMap(r){try{let i=this.selectedAnnotationsMap$.value;if(r){let o={};return Object.keys(i).forEach(s=>{r==="comment"?["comment","videoPin"].includes(i[s].type)&&(o[s]=i[s]):i[s].type===r&&(o[s]=i[s])}),o}else return i}catch(i){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",i),{}}}getSelectedAnnotationsMap$(r){return this.selectedAnnotationsMap$.asObservable().pipe(De(i=>{if(r){let o={};return Object.keys(i).forEach(s=>{i[s].type===r&&(o[s]=i[s])}),o}else return i}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(De(r=>Object.values(r)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(r){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",r),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}getSelectedAnnotationsContextIdMap(){try{return this.selectedAnnotationsContextIdMap$.value}catch(r){return this.loggingService.catch("Error in DomService getSelectedAnnotationsContextIdMap: ",r),{}}}getSelectedAnnotationsContextIdMap$(){return this.selectedAnnotationsContextIdMap$.asObservable()}toggleAnnotationSelection(r,i,o,s=!1,a,c){try{o==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let l=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{})),h=JSON.parse(JSON.stringify(this.selectedAnnotationsContextIdMap$.value||{}));l[r.annotationId]&&!s?delete l[r.annotationId]:((!this.isShiftKeyPressed||s)&&(l={}),l[r.annotationId]=r,d[r.annotationId]=i,c&&(h[r.annotationId]=c),a=r?.multiThreadAnnotationId||a,a&&(l[a]={annotationId:a,type:"multiThread"},d[a]=i,c&&(h[a]=c))),this.selectedAnnotationsMap$.next(l),Object.keys(d).forEach(f=>{l[f]||delete d[f]}),this.selectedAnnotationsLocationMap$.next(d),Object.keys(h).forEach(f=>{l[f]||delete h[f]}),this.selectedAnnotationsContextIdMap$.next(h)}catch(l){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",l)}}setSelectedAnnotationLocation(r,i){try{let o=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));o?.[r]!==i&&(o[r]=i,this.selectedAnnotationsLocationMap$.next(o))}catch(o){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",o)}}updateSelectedAnnotationInMap(r){try{let i=this.selectedAnnotationsMap$.value;r.forEach(o=>{i[o.annotationId]&&(i[o.annotationId]=o)}),this.selectedAnnotationsMap$.next(i)}catch(i){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",i)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",r),ot([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode?.deref()}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.pipe(nn(null))}onSelectionChange$(){return this.documentSelectionChange$.pipe(nn(null))}onWindowClick$(){return this.windowClick$.pipe(nn(null))}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.pipe(nn(null))}onWindowKeyupDelete$(){return this.windowKeyupDelete$.pipe(nn(null))}onWindowKeyupEsc$(){return this.windowKeyupEsc$.pipe(nn(null))}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.pipe(nn(null))}getLastDocumentClickTarget(){return this.lastDocumentClickTarget?.deref()??null}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.pipe(nn(null))}onDomChange$(r){try{return this.mutationObserver||this.setMutationObserver(r),this.mutation$.pipe(nn(null))}catch(i){return this.loggingService.catch("Error in DomService onDomChange$: ",i),ot([])}}getChildListMutation$(){return this.childListMutation$.pipe(nn(null))}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(r,i){try{let o={offsetTop:0,offsetLeft:0},s=r;if(s===i){let a=window.getComputedStyle(r);a.position==="static"&&a.transformStyle!="preserve-3d"&&a.transform=="none"&&(o.offsetLeft=r?.offsetLeft||0,o.offsetTop=r?.offsetTop||0)}if(s!==i)if(r?.closest("svg"))for(;s&&s!==i;){let c=window.getComputedStyle(s);if(s.tagName.toLowerCase()==="svg"||s instanceof SVGElement){let l=s.parentElement;if(l){let d=l.getBoundingClientRect(),h=s.getBoundingClientRect();o.offsetLeft+=h.left-d.left,o.offsetTop+=h.top-d.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0):(o.offsetLeft+=s.offsetLeft,o.offsetTop+=s.offsetTop);if(s=s.parentElement,r instanceof SVGElement&&s===i){let l=window.getComputedStyle(s);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0)}}else{let c=window.getComputedStyle(s);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(o.offsetLeft+=s?.offsetLeft||0,o.offsetTop+=s?.offsetTop||0):(o.offsetLeft+=s.offsetLeft,o.offsetTop+=s.offsetTop)}return o}catch(o){return this.loggingService.catch("Error in DomService getElementOffset: ",o),{offsetTop:0,offsetLeft:0}}}isElementVisible(r){try{if(typeof r?.getBoundingClientRect=="function"){let{width:i,height:o,top:s,bottom:a}=r?.getBoundingClientRect();return i>0||o>0||s<window.innerHeight&&a>0}else return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisible: ",i),!1}}isElementVisibleOnScreen(r){try{if(r){if(!(r instanceof Element))return!1;let i=r,o=window.getComputedStyle(i);return!(o.display==="none"||o.visibility==="hidden"||parseFloat(o.opacity)===0)}return!1}catch(i){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",i),!1}}getClickAndDragPointsObservable(){return new ue(r=>{let i=Hi(document,"mousedown").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),o=Hi(document,"mousemove").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),s=Hi(document,"mouseup").pipe(De(l=>({type:l.type,x:l.clientX+window.scrollX,y:l.clientY+window.scrollY,event:l}))),c=i.pipe(Zn(l=>o.pipe(sc(),De(([d,h])=>({startPoint:l,prevPoint:d,curPoint:h})),Is(s)))).subscribe(r);return()=>c.unsubscribe()})}drawRectangle(r,i){let o=document.querySelector(".rectangle");o||(o=document.createElement("div"),this.addClassToElement(o,"rectangle"),o.setAttribute(k.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),o.setAttribute(k.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(o));let s=Math.abs(i.x-r.x),a=Math.abs(i.y-r.y),c=Math.min(r.x,i.x),l=Math.min(r.y,i.y);return o.style.width=`${s}px`,o.style.height=`${a}px`,o.style.left=`${c}px`,o.style.top=`${l}px`,o.style.position="absolute",o.style.border="2px dashed #f00",o.style.pointerEvents="none",o.style.zIndex="2147483577",o}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let r=window.getSelection();if(r?.rangeCount)return r.getRangeAt(0)}return null}catch(r){return this.loggingService.catch("Error in DomService getRange: ",r),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(r){this.loggingService.catch("Error in DomService clearTextSelection: ",r)}}getTargetTextRangeFromSelectionRange(r){try{let i={},o=r.commonAncestorContainer;o?.nodeType===Node.TEXT_NODE&&(o=o.parentElement);let s=document.body;if(o){let c=this.getTextXPath(o);this.isXpathWithId(c)&&(s=o)}let a=this.getAdditionalLocationContainer(o);if(a&&(s=a),i.commonAncestorContainer=this.getTextXPath(s),i.commonAncestorContainer){let c=this.getElementFromXPath(i.commonAncestorContainer);if(c){i.commonAncestorContainerFXpath=this.getXPath(c,!0),i.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let l=this.generateAnchorRecord(c);l&&(i.commonAncestorContainerAnchor=l)}}return i.text=r.toString(),i.occurrence=DR(s,0,r.startContainer,r.startOffset,r.toString())+1,i}catch(i){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",i);return}}getTextXPath(r){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),r.nodeType===Node.TEXT_NODE){let i=1,o=r.previousSibling;for(;o;)o.nodeType===Node.TEXT_NODE&&i++,o=o.previousSibling;return this.getXPath(r.parentElement)}else return this.getXPath(r)}catch(i){this.loggingService.catch("Error in DomService getTextXPath: ",i);return}}getHostElement(r){try{if(k.NON_NESTABLE_ELEMENTS[r?.tagName?.toLowerCase()]){let o=r?.closest("picture");return o?o?.parentElement:r.parentElement}let i=r.closest("svg");return i?i?.parentElement:r}catch(i){return this.loggingService.catch("Error in DomService getHostElement: ",i),r}}isElementInsideAdditionalLocationContainer(r){try{return!!r?.closest(`[${k.ATTRIBUTES.VELT_LOCATION}], [${k.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(i){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",i),!1}}getAdditionalLocationContainer(r){try{return r?.closest(`[${k.ATTRIBUTES.VELT_LOCATION}], [${k.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(i){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",i),null}}isXpathWithId(r){try{return typeof r=="string"?!!r?.includes("[@id="):!1}catch(i){return this.loggingService.catch("Error in DomService isXpathWithId: ",i),!1}}getListedElements({elementIds:r,elementClassNames:i,elementQuerySelectors:o}){try{let s=[];if(r?.length)for(let a=0;a<r.length;a++){let c=document.getElementById(r[a]);c&&s.push(c)}if(i?.length)for(let a=0;a<i.length;a++){let c=document.getElementsByClassName(i[a]);for(let l=0;l<c.length;l++){let d=c[l];d&&d instanceof HTMLElement&&s.push(d)}}if(o?.length)for(let a=0;a<o.length;a++){let c=document.querySelectorAll(o[a]);for(let l=0;l<c.length;l++){let d=c[l];d&&d instanceof HTMLElement&&s.push(d)}}return s}catch(s){return this.loggingService.catch("Error in DomService getListedElements: ",s),[]}}isElementInsideListedElementIds(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.getElementById(i[o]);if(s&&s.contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",o),!1}}isElementInsideListedElementClassNames(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.getElementsByClassName(i[o]);for(let a=0;a<s.length;a++)if(s[a].contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",o),!1}}isElementInsideListedElementQuerySelectors(r,i){try{if(i?.length){for(let o=0;o<i.length;o++){let s=document.querySelectorAll(i[o]);for(let a=0;a<s.length;a++)if(s[a].contains(r))return!0}return!1}return!0}catch(o){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",o),!1}}addClassToElement(r,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),r&&(r.classList?.contains(i)||r.classList?.add(i))}catch(o){this.loggingService.catch("Error in DomService addClassToElement: ",o)}}removeClassFromElement(r,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),r&&r.classList?.contains(i)&&r.classList?.remove(i)}catch(o){this.loggingService.catch("Error in DomService removeClassFromElement: ",o)}}isElementInsideParentWithAttribute(r,i,o){try{let s=r;for(;s&&s!==document.body;){if(s?.getAttribute&&s?.getAttribute(i)===o)return!0;s=s.parentElement}return!1}catch(s){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",s),!1}}setVideoEditorHandlingDelete(r){try{this.isVideoEditorHandlingDelete=r}catch(i){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",i)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(r){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",r),!1}}setCustomCss(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(r)}catch(i){this.loggingService.catch("Error in DomService setCustomCss: ",i)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getCustomCss$: ",r),ot(null)}}injectCustomCss(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let i=this.customCss$.value;if(i){let o=r?.shadowRoot?.querySelector(`[${k.VELT_CUSTOM_CSS}]`);if(o&&o.remove(),i?.type==="link"){let s=document.createElement("link");s.href=i?.value,s.rel="stylesheet",s.setAttribute(k.VELT_CUSTOM_CSS,"true"),r?.shadowRoot?.appendChild(s)}else{let s=document.createElement("style");s.innerHTML=this.sanitizeHtml(i?.value),s.setAttribute(k.VELT_CUSTOM_CSS,"true"),r?.shadowRoot?.appendChild(s)}}}catch(i){this.loggingService.catch("Error in DomService injectCustomCss: ",i)}}subscribeInjectCustomCss(r){try{return this.customCss$.subscribe(()=>{this.injectCustomCss(r?.nativeElement)})}catch(i){return this.loggingService.catch("Error in DomService subscribeInjectCustomCss: ",i),new gt}}trimCommentHtml(r){try{let i=document.createElement("div");i.innerHTML=r,this.removeEmptyElements(i);let o=i.innerHTML;return o=o.replace(e.MULTIPLE_NBSP_REGEX," ").replace(e.TRIM_NBSP_REGEX,"").trim(),o}catch(i){return this.loggingService.catch("Error in DomService trimCommentHtml: ",i),r}}removeEmptyElements(r){try{let s=function(a){return o.test(a.innerHTML)};var i=s;let o=/^\s*(<br\s*\/?>)?\s*$/;for(;r.firstChild&&s(r.firstChild);)r.removeChild(r.firstChild);for(;r.lastChild&&s(r.lastChild);)r.removeChild(r.lastChild)}catch(o){this.loggingService.catch("Error in DomService removeEmptyElements: ",o)}}normalizeWhitespace(r){try{r.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?i.nodeValue=i.nodeValue?.replace(/\s+/g," ").trim()??"":i.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(i)})}catch(i){this.loggingService.catch("Error in DomService normalizeWhitespace: ",i)}}sanitizeHtml(r){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),Sy.sanitize(r,$2)}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtml: ",i),""}}sanitizeHtmlForPaste(r){try{let i=this.convertStylesToTags(r);return Sy.sanitize(i,{ALLOWED_TAGS:["b","strong","i","em","u","a","br"],ALLOWED_ATTR:["href","target","rel"]})}catch(i){return this.loggingService.catch("Error in DomService sanitizeHtmlForPaste: ",i),""}}convertStylesToTags(r){try{let i=document.createElement("div");return i.innerHTML=r,this.convertBlockElementsToBr(i),this.processNodeStyles(i),i.innerHTML}catch(i){return this.loggingService.catch("Error in DomService convertStylesToTags: ",i),r}}convertBlockElementsToBr(r){try{let i=["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","SECTION","ARTICLE","HEADER","FOOTER"],o;for(;(o=r.querySelector(i.join(",")))!==null;){let s=o.parentNode;if(!s)break;for(;o.firstChild;)s.insertBefore(o.firstChild,o);o.nextSibling&&s.insertBefore(document.createElement("br"),o),s.removeChild(o)}}catch(i){this.loggingService.catch("Error in DomService convertBlockElementsToBr: ",i)}}processNodeStyles(r){try{let i=Array.from(r.childNodes);for(let o of i)if(o.nodeType===Node.ELEMENT_NODE){this.processNodeStyles(o);let s=o,a=s.style,c=o,l=a?.fontWeight;if(l==="bold"||l==="700"||l==="800"||l==="900"){let d=s.tagName?.toLowerCase();if(d!=="b"&&d!=="strong"){let h=document.createElement("b");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}if(a?.fontStyle==="italic"){let d=s.tagName?.toLowerCase();if(d!=="i"&&d!=="em"){let h=document.createElement("i");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}if((a?.textDecorationLine?.includes("underline")||a?.textDecoration?.includes("underline"))&&s.tagName?.toLowerCase()!=="u"){let h=document.createElement("u");c.parentNode.insertBefore(h,c),h.appendChild(c),c=h}}}catch(i){this.loggingService.catch("Error in DomService processNodeStyles: ",i)}}sanitizeSvg(r){try{return Sy.sanitize(r,$2)}catch(i){return this.loggingService.catch("Error in DomService sanitizeSvg: ",i),r}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let r=new Wr;this.deviceInfo$.next(r)}catch(r){this.loggingService.catch("Error in DomService setDeviceInfo: ",r)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(r){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",r),ot(new Wr)}}getTabId(){try{let r=sessionStorage.getItem(k.SESSION_STORAGE.VELT_TAB_ID);!r&&this.tabId&&(r=this.tabId,sessionStorage.setItem(k.SESSION_STORAGE.VELT_TAB_ID,r)),!this.tabId&&r&&(this.tabId=r);let i=this.getTabIdFromWindowName();return(!r||r!==i)&&(r=ad(),this.tabId=r,sessionStorage.setItem(k.SESSION_STORAGE.VELT_TAB_ID,r),this.setTabIdToWindowName(r)),r}catch(r){return this.loggingService.catch("Error in DomService getTabId: ",r),null}}getTabIdFromWindowName(){try{return window.name}catch(r){return this.loggingService.catch("Error in DomService getTabIdFromWindowName: ",r),null}}setTabIdToWindowName(r){try{window.name=r}catch(i){this.loggingService.catch("Error in DomService setTabIdToWindowName: ",i)}}getDeviceInfo(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo","color: green;"),this.deviceInfo$.value}catch(r){return this.loggingService.catch("Error in DomService getDeviceInfo: ",r),new Wr}}isMobileDevice(){try{return new Wr().getDeviceType()===Ir.MOBILE}catch(r){return this.loggingService.catch("Error in DomService isMobileDevice: ",r),!1}}isTabletDevice(){try{return new Wr().getDeviceType()===Ir.TABLET}catch(r){return this.loggingService.catch("Error in DomService isTabletDevice: ",r),!1}}isDesktopDevice(){try{return new Wr().getDeviceType()===Ir.DESKTOP}catch(r){return this.loggingService.catch("Error in DomService isDesktopDevice: ",r),!1}}deepCloneElement(r){try{var i=document.createElement(r?.tagName);return Array.from(r.attributes).forEach(o=>{i.setAttribute(o.nodeName,o.nodeValue)}),r.childNodes.forEach(o=>{o.nodeType===Node.ELEMENT_NODE?i.appendChild(this.deepCloneElement(o)):o.nodeType===Node.TEXT_NODE&&i.appendChild(document.createTextNode(o.nodeValue))}),i}catch(o){return this.loggingService.catch("Error in DomService deepCloneElement: ",o),r}}setRandomNumberToElementRecursive(r){try{if(!r)return;let i=Math.random().toString(36).substring(7);r&&r.setAttribute&&typeof r.setAttribute=="function"&&(r.getAttribute("velt-wireframe-id")||r.setAttribute("velt-wireframe-id",i)),Array.from(r.children).forEach(s=>{this.setRandomNumberToElementRecursive(s)})}catch(i){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",i)}}setDialogOpenedInSidebar(r){this.dialogOpenedInSidebar$.next(r)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(r){if(!r)return;Array.from(r.children).forEach(o=>{if(this.removeWireframeSuffixFromTags(o),o.tagName.toLowerCase().endsWith("-wireframe")){let s=o.tagName.toLowerCase().replace("-wireframe",""),a=document.createElement(s);for(Array.from(o.attributes).forEach(c=>{a.setAttribute(c.name,c.value)});o.firstChild;)a.appendChild(o.firstChild);o.parentNode.replaceChild(a,o)}})}isMonitorDevice(){try{return new Wr().getDeviceType()===Ir.MONITOR}catch(r){return this.loggingService.catch("Error in DomService isMonitorDevice: ",r),!1}}isElementOriginallyStatic(r){try{return window.getComputedStyle(r).position==="static"||r.hasAttribute(k.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_AREA_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_TAG_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_RECORDER_PIN_HOST_STATIC)||r.hasAttribute(k.ATTRIBUTES.VELT_ARROW_PIN_HOST_STATIC)}catch(i){return this.loggingService.catch("Error in DomService isElementOriginallyStatic: ",i),!1}}};e.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,e.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,e.\u0275fac=function(i){return new(i||e)(z(Zs),z(Bo),z(Rt),z(aR))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function ol(t){let e=t?.refreshToken;return typeof e=="string"&&e.length>0?e:void 0}var iw=Symbol("velt-auth-state-pending");function mre(t,e){let n=B(B({},t),e||{});return n.userId=t.userId,n.userSnippylyId=t.userSnippylyId,n.type=t.type,n.organizationId=t.organizationId,n.clientOrganizationId=t.clientOrganizationId,n.groupId=t.groupId,n.clientGroupId=t.clientGroupId,n.contacts=t.contacts,n.plan=t.plan,n.isAdmin=t.isAdmin,n.isReadOnly=t.isReadOnly,n.isAnonymous=t.isAnonymous,n.isGuest=t.isGuest,n.color=e?.color||t.color,n.textColor=e?.textColor||t.textColor,n.initial=e?.initial||n.name?.charAt(0).toUpperCase()||n.email?.charAt(0).toUpperCase()||t.initial,n?.photoUrl===void 0&&(n.photoUrl=null),n}var Ere=["userId","userSnippylyId","organizationId","clientOrganizationId","isAdmin","isReadOnly","isAnonymous","isGuest","plan","contacts"];function _re(t){if(!t||typeof t!="object")return{};let e=B({},t);for(let n of Ere)delete e[n];return e}function z2(t,e){if(!e.length)return!0;if(t.length!==e.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}var vd=(()=>{let e=class e{constructor(r,i,o,s,a,c,l,d,h){this.afAuth=r,this.configService=i,this.avatarService=o,this.coreActionsService=s,this.domService=a,this.functions=c,this.analyticsService=l,this.loggingService=d,this.serviceBook=h,this.endpointsService=X(_y),this.portableBackend$=new le(null),this.portableAuthUser$=new le(null),this.user$=new le(null),this.userOptions$=new le(null),this.userContacts$=new le(null),this.userOrganization$=new le(null),this.isPrivateCommentsEnabled$=new le(!1),this.providedUser=new so,this.portableRefreshTimer=null,this.portableToken=null,this.portableRefreshInFlightEpoch=null,this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0,this.portableRefreshWarnedEpoch=null,this.portableVisibilityHandler=null,this.loggedInUserResolveRetryDelaysMs=[2e3,8e3,3e4],this.loggedInUserResolveRetryInFlightUserId=null,this.firebaseConfig$=new le(null),this.advancedQueries$=new le(null),this.planDetails$=new le(null),this.signOutPreviousUser$=new le(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.portableAutoLoginCalled=!1,this.portableAutoLoginInFlight=Promise.resolve(),this.portableSessionEpoch=0,this.portableLocalSessionEnds=0,this.portableSignOutOwnsEpochBump=!1,this.pendingPortableRestore=null,this.portableResumeUserId=null,this.portableStorageHandler=null,this.portableSessionIdentity=null,this.reportedPortableRefreshCodes=new Set,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.portablePlanSeeded=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.onRetrySubscription=null,this.authProviderListenerGeneration=0,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.cachedActivityConfig=null,this.portableChunkReady=null,this.viewsService=null,this.crdtService=null,this.portableSavedSessionRaw=null,this.portableRenewalStopped=null,this.portableSessionStartedAt=0,this.portablePersistInFlight=Promise.resolve(),this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;"),this.serviceBook.observe(vT).subscribe(f=>{this.commentService=f??void 0}),this.serviceBook.observe(ST).subscribe(f=>{this.reactionService=f??void 0}),this.serviceBook.observe(AT).subscribe(f=>{this.areaService=f??void 0}),this.serviceBook.observe(PU).subscribe(f=>{this.activityService=f??void 0,f&&this.cachedActivityConfig&&f.setActivityFeatureConfig(this.cachedActivityConfig)}),this.serviceBook.observe(xU).subscribe(f=>{this.viewsService=f??null}),this.serviceBook.observe(kU).subscribe(f=>{this.crdtService=f??null});try{try{let f=this.configService.getAuthProxyHost();if(f){let g=this.afAuth?.config;g&&(g.apiHost=f,g.tokenApiHost=f)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(f=>{this.config=f}),this.forceReLoggedIn=localStorage.getItem(k.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Ed(this.afAuth).pipe(nn(this.afAuth.currentUser),sc(),Zn(([f,g])=>this.domService.onNetworkStatusChange$().pipe(En(E=>E),_n(1),De(()=>({previousUser:f,currentUser:g}))))).subscribe(E=>y(this,[E],function*({previousUser:f,currentUser:g}){if(!g&&f){let I=f?.stsTokenManager?.expirationTime,S=new Date().getTime(),L=I-S;S>I&&(this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.getUserForTelemetry(this.user$.value??void 0),lastLoggedInUserData:this.lastLoggedInUserData?{user:this.getUserForTelemetry(this.lastLoggedInUserData.user),autoLogin:this.lastLoggedInUserData.autoLogin,hasAuthToken:!!this.lastLoggedInUserData.userOptions?.authToken}:null,timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&f?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(vt.Events.Core.SDK_SESSION_RE_LOGIN_TRIGGERED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,user:this.getUserForTelemetry(this.lastLoggedInUserData.user),timeLeft:L,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),f=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",f)}),this.getUser$().pipe(ai(pp)).subscribe(f=>{let g=wR(f);this.coreActionsService.triggerAction(oo.USER_UPDATE,g),this.coreActionsService.triggerAction(oo.INIT_UPDATE,{event:oo.USER_UPDATE,payload:{user:g}})})}catch(f){this.loggingService.catch("Error in AuthService constructor: ",f)}}setApiKey(r,i){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",r);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=r,this.configService.setApiKey(this.apiKey),i||(i=new wT),this.configService.initConfig(i);let o=this.configService.getProxyConfig();if(o?.authHost)try{let s=this.afAuth?.config;s&&(s.apiHost=o.authHost,s.tokenApiHost=o.authHost)}catch(s){this.loggingService.catch("Error setting auth proxy config: ",s)}else try{let s=this.afAuth?.config;s&&s.apiHost!=="identitytoolkit.googleapis.com"&&(s.apiHost="identitytoolkit.googleapis.com",s.tokenApiHost="securetoken.googleapis.com")}catch(s){this.loggingService.catch("Error resetting auth proxy config: ",s)}i.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Ed(this.afAuth).pipe(_n(1)).subscribe(s=>y(this,null,function*(){if(this.autoLoginCalled=!0,s){let a=yield Pp(s,!0).catch(c=>null);if(a){let{user:c}=a?.claims;this.autoLoginRequired&&(c=yield this.updateUserWithColorAndTextColor(c),this.initializeClient(c,this.buildAutoLoginOptions(),new Date().getTime(),!0,"internal-autoLogin"))}}})),!this.portableAutoLoginCalled&&this.configService.getEnablePortableBackend()===!0&&(this.portableAutoLoginCalled=!0,this.portableAutoLoginInFlight=this.autoLoginPortableSession())}catch(o){this.loggingService.catch("Error in setApiKey: ",o)}}setUsersService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=r}catch(i){this.loggingService.catch("Error in setUsersService: ",i)}}setUserPermissionService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=r}catch(i){this.loggingService.catch("Error in setUserPermissionService: ",i)}}setDocService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=r}catch(i){this.loggingService.catch("Error in setDocService: ",i)}}setContactService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=r}catch(i){this.loggingService.catch("Error in setContactService: ",i)}}setIamService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=r}catch(i){this.loggingService.catch("Error in setIamService: ",i)}}setCommentService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=r}catch(i){this.loggingService.catch("Error in setCommentService: ",i)}}setCommonDbService(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=r}catch(i){this.loggingService.catch("Error in setCommonDbService: ",i)}}validateOrganizationId(r){if(this.isVersionGreaterThanOrEqualTo4()&&!r?.organizationId)if(this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_FAILED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,message:"Organization Id is not set",forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)},!0,r.userSnippylyId),this.configService.getSF())this.loggingService.catch("OrganizationId is not set in Identify method",void 0,void 0,!0);else throw new Error("OrganizationId is not set in Identify method")}setVeltAuthProvider(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe(),this.authProviderListenerGeneration++;let i=null;if(!r.user)return null;r.generateToken&&typeof r.generateToken=="function"&&(i=yield r.generateToken());let o=yield NR(()=>window.Velt.identify(r.user,B(B({},r.options||{}),i&&{authToken:i}),{fromProvider:!0}).catch(s=>(r.onError&&typeof r.onError=="function"&&r.onError(s),Promise.reject(s))),r.retryConfig||{retryCount:0,retryDelay:0});return o&&r.generateToken&&typeof r.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(oo.ERROR).pipe(En(s=>s.code==="token_expired"),_n(10)).subscribe(s=>y(this,null,function*(){if(s.code==="token_expired"){let a=this.authProviderListenerGeneration,c=()=>a===this.authProviderListenerGeneration,l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],d=this.docService?.getOptionsFromDocumentPaths()??void 0,h=[],f=this.docService?.getLocation();f&&h.push(f.location);let g=this.docService?.getLocations();if(g&&Object.values(g).forEach(I=>{h.push(I.location)}),(yield NR(()=>y(this,null,function*(){try{let I=yield r.generateToken?.();return c()&&I?window.Velt.identify(r.user,B(B({},r.options||{}),I&&{authToken:I}),{fromProvider:!0}):!0}catch{return!1}}),r.retryConfig||{retryCount:0,retryDelay:0}))&&c()){let I=this.docService?.getDocumentIds()?.map(j=>j.clientDocumentId)??[];z2(l.map(j=>j.id),I)&&(yield this.docService?.setDocuments({documents:l,options:d,source:"internal"}));let S=[],L=this.docService?.getLocation();L?.location?.id&&S.push(L.location.id),Object.values(this.docService?.getLocations()??{}).forEach(j=>{j?.location?.id&&S.push(j.location.id)}),z2(h.map(j=>j?.id).filter(Boolean),S)&&(yield this.docService?.setLocations({locations:h,source:"internal",options:{appendLocation:!f}}))}}}))),o}catch(i){return this.loggingService.catch("Error in setVeltAuthProvider: ",i),null}})}setUserToStorage(r){return y(this,null,function*(){try{if(r){let i=yield UT(r,r?.userId??"");localStorage.setItem(k.LOCAL_STORAGE.VELT_IDENTIFY_USER,i)}}catch(i){this.loggingService.catch("Error in setUserToStorage: ",i)}})}getUserFromStorage(r){return y(this,null,function*(){try{let i=localStorage.getItem(k.LOCAL_STORAGE.VELT_IDENTIFY_USER);return i?yield hp(i,r?.userId??""):null}catch(i){return this.loggingService.catch("Error in getUserFromStorage: ",i),null}})}setIsPrivateCommentsEnabled(r){try{this.isPrivateCommentsEnabled$.next(r)}catch(i){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",i)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(r){return y(this,null,function*(){try{let i=JSON.parse(JSON.stringify(r??{})),o=yield this.getUserFromStorage(i);return!o||Object.keys(o).length===0?(delete i?.color,delete i?.textColor,i):(o?.color&&(i.color=o?.color),o?.textColor&&(i.textColor=o?.textColor),i)}catch(i){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",i),r}})}updateUserIfRequired(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let i=yield this.getUserFromStorage(r),o={};r.color&&r.color!==i?.color&&(o.color=r.color),r.textColor&&r.textColor!==i?.textColor&&(o.textColor=r.textColor),Object.keys(o).length>0&&r.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:r.clientOrganizationId,user:me(B({},o),{userId:r.userId})})}catch(i){this.loggingService.catch("Error in updateUserIfRequired: ",i)}})}initializeClient(r,i,o,s,a){return y(this,null,function*(){try{if(this.autoLoginRequired=!1,this.portableResumeUserId=null,this.userOptions$.next(i),this.initializeClientToken)this.pendingUserLogin=r,this.pendingUserLoginSource=a;else{r.userSnippylyId=YV(this.configService.getApiKey(),r.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=o;let c=this.portableSessionEpoch,l=this.portableLocalSessionEnds,d=yield Ed(this.afAuth).pipe(_n(1)).toPromise().catch(E=>null),h=!0;this.providedUser=JSON.parse(JSON.stringify(r));let f=!d&&s?this.takePendingPortableRestore(r,i):null,g=f?.envelope??null;if(g){if(this.loggingService.log("%c[WB] Calling FUNCTION: restorePortableSession","color: green;"),this.validateOrganizationId(r),!(yield this.applyIdentifyResponse(r,g.res,s)))return;h=!1,this.trackAutoAuthSuccess(r,a)}else if(!d&&s&&a==="internal-autoLogin"&&this.configService?.getEnablePortableBackend()===!0)return f?.resume?(qn("session.resume-skipped",f.overtaken?"overtaken":"not restorable"),this.loggingService.log("Velt [portable backend]: not following the session another page saved; waiting for identify().")):f?.overtaken?(qn("session.restore-discarded"),this.loggingService.log("Velt [portable backend]: discarding a reload restore that a sign-out or a new identify overtook."),this.clearPersistedPortableSessionIfUnchanged(f.raw)):(this.loggingService.log("Velt [portable backend]: nothing restorable on reload; waiting for identify()."),this.clearPersistedPortableSession()),this.initializeClientToken=0,this.checkForPendingLogin(),null;if(d){let E=yield Pp(d,!0).catch(j=>null);if(!E)return;let{user:I,firebaseConfig:S,advancedQueries:L}=E.claims;$N({userSnippylyId:d?.uid,groupId:I?.groupId,organizationId:I?.organizationId},r,i)||!s&&r?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(r)||this.forceReLoginRequiredForRegion(r,S)||this.forceReLoginRequiredForCommentViews(r)?(localStorage.setItem(k.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(k.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal"),c=this.portableSessionEpoch,l=this.portableLocalSessionEnds):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(r),this.validateOrganizationId(r),this.setFirebaseConfig(S),this.setAdvancedQueries(L),I&&(this.providedUser.isAdmin=!!I.isAdmin),this.initializeSignedInUser(d,s,r),h=!1,this.trackAutoAuthSuccess(r,a))}else if(h&&c===this.portableSessionEpoch&&this.isPortableIdentityChange(r,i)){let E=this.signOutUser("internal");c=this.portableSessionEpoch,l=this.portableLocalSessionEnds,yield E}if(h){this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:a},!0,r.userSnippylyId,r.userId);let E=yield this.requestIdentify(r,i?.authToken);if(E.error){if(this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_FAILED,me(B({apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,message:E.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)},E),{source:a}),!0,r.userSnippylyId,r.userId),E.error&&typeof E.error=="string")if(this.isTokenExpiredIdentifyError(E))this.emitIdentifyTokenExpiredError(E,r,a);else{let S=E;this.coreActionsService.triggerAction(oo.ERROR,S)}throw E}else this.tokenExpiredErrorCount=0;if(this.shouldHandlePortableBackend(E)&&this.isPortableIdentifyOvertaken(c,l,s))return this.loggingService.log("Velt [portable backend]: discarding an identify response that a sign-out overtook."),this.initializeClientToken=0,this.checkForPendingLogin(),null;if(this.shouldHandlePortableBackend(E)&&c!==this.portableSessionEpoch&&(this.autoLoginRequired=!1,this.portableResumeUserId=null),this.analyticsService.trackEvent(vt.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:a},!0,r.userSnippylyId,r.userId),this.validateOrganizationId(r),!(yield this.applyIdentifyResponse(r,E,s)))return}this.initializeClientToken=0,this.lastLoggedInUserData={user:r,userOptions:i,initializeClientToken:o,autoLogin:s},this.checkForPendingLogin()}return r}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),i?.throwError?Promise.reject(c):Promise.resolve(null)}})}isPortableIdentifyOvertaken(r,i,o){let s=this.portableSessionEpoch-r;return o?s!==0:s!==this.portableLocalSessionEnds-i}isPortableIdentityChange(r,i){try{if(!this.portableAuthUser$.value)return!1;let o=this.portableSessionIdentity?.user??this.user$.value;return o?$N(o,r,i):!1}catch(o){return this.loggingService.catch("Error in isPortableIdentityChange: ",o),!1}}isVersionGreaterThanOrEqualTo4(){try{let r=Wc();return(r?parseInt(r.split(".")?.[0]||"0"):0)>=4}catch(r){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",r),!1}}isVersion4Point5(){try{let r=Wc();if(r){let i=r.split("."),o=parseInt(i[0]||"0"),s=parseInt(i[1]||"0"),a=parseInt(i[2]||"0");if(o>=4&&s>=5)return o===4&&s===5&&a===0?!r.toLowerCase().includes("beta"):!0}return!1}catch(r){return this.loggingService.catch("Error in isVersion4Point5: ",r),!1}}forceReLoginRequiredForAdvancedQueries(r){try{let i=this.isVersionGreaterThanOrEqualTo4(),o=!1;try{let s=localStorage.getItem(k.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);s&&(o=JSON.parse(s)?.advancedQueriesEnabled)}catch(s){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",s)}return!!(i&&r.organizationId&&!o)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",i),!1}}forceReLoginRequiredForCommentViews(r){try{let i=this.isVersion4Point5(),o=!1;try{let s=localStorage.getItem(k.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);s&&(o=JSON.parse(s))}catch(s){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",s)}return!!(i&&r.organizationId&&!o)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",i),!1}}forceReLoginRequiredForRegion(r,i){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&r.organizationId&&!i?.region)}catch(o){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",o),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(r){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:B(B({},this.endpointsService.getFirebaseConfig()),r)})}catch(i){this.loggingService.catch("Error in setFirebaseConfig: ",i)}}requestIdentify(r,i){return y(this,null,function*(){let o=Wc();this.usersService?.userResolverConfigured?.()&&(r=MR(r));let s=this.endpointsService.getPortableIdentifyUrl();return s?ZG({url:s,apiKey:this.apiKey,user:r,version:o,authToken:i}):(yield Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("validateClient"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.apiKey,user:r,version:o,authToken:i}))?.data})}requestPortableRefresh(r){return y(this,null,function*(){let i=this.endpointsService.getPortableIdentifyUrl();return!i||$c(i)?UN("the portable identify URL is not configured; the renewal credential was not sent"):n2({url:t2(i,"refresh"),apiKey:this.apiKey,refreshToken:r,timeoutMs:QG()})})}reportPortableRefreshMisconfigured(r){try{let i=String(r?.code??"unknown");if(this.reportedPortableRefreshCodes.has(i))return;if(this.reportedPortableRefreshCodes.add(i),i===e.PORTABLE_NO_CREDENTIAL_ENVELOPE.code){console.error("Velt [portable backend]: this session has no renewal credential for the configured gateway (the identify answer carried no refreshToken, or selfHosted.portableBackendUrl changed after sign-in), so it cannot be renewed: it is signed out and the app must identify() again. Every identify answer from portable-v0.1.6 or later carries one.");return}let o=r?.message?` (${r.message})`:"";console.error(i==="invalid-argument"?`Velt [portable backend]: the gateway rejected the session renewal as malformed: invalid-argument${o}. The SDK and gateway versions disagree on /identify/refresh; renewal is stopped for this session.`:`Velt [portable backend]: the gateway refused the session renewal: ${i}${o}. A deployment setting is wrong (the allowed origins, or the identify configuration for this API key). Renewal is stopped for this session; after the setting is fixed, a reload renews from the saved session.`)}catch{}}emitIdentifyTokenExpiredError(r,i,o){if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let s={code:"token_expired",message:"Token expired",error:r?.error,source:r?.source};this.coreActionsService.triggerAction(oo.ERROR,s)}else{let s={code:"too_many_retries",message:"Token expired. Too many retries.",error:r?.error,source:r?.source};this.coreActionsService.triggerAction(oo.ERROR,s),this.analyticsService.trackEvent(vt.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:i.userId,snippylyUserId:i.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:o},!0,i.userSnippylyId,i.userId)}}isTokenExpiredIdentifyError(r){try{return r?.code==="token_expired"||!!r?.error?.toLowerCase?.()?.includes("token expired")}catch{return!1}}shouldHandlePortableBackend(r){try{return this.configService?.getEnablePortableBackend()===!0&&p2(r)}catch(i){return this.loggingService.catch("Error in shouldHandlePortableBackend: ",i),!1}}applyIdentifyResponse(r,i,o){return y(this,null,function*(){if(this.shouldHandlePortableBackend(i)){this.portableSessionEpoch++;let s=this.portableSessionEpoch,a=ol(i),c=a?this.endpointsService.getPortableIdentifyUrl()??void 0:void 0;this.portableSessionIdentity=B({user:r,epoch:s},a?{refreshToken:a,refreshTokenIssuer:c}:{}),this.portableSessionStartedAt=Date.now();let l=this.handlePortableBackendResponse(i);this.planDetails$.value||(this.getPlanDetailsCalled=!0,this.portablePlanSeeded=!0,this.planDetails$.next({planInfo:null,isPlanExpired:!1})),yield this.applyPortableProjectConfig(i);let d=null;if(i?.token&&this.usersService?.externalUserDataProviderAvailable())try{d=yield this.resolveSignedInUserWithProvider(r,this.providedUser?.clientOrganizationId||r.clientOrganizationId)}catch(f){this.loggingService.catch("Error in resolveSignedInUserWithProvider (Tier B sign-in): ",f),d=null}if(s!==this.portableSessionEpoch)return qn("session.adopt-discarded"),this.loggingService.log("Velt [portable backend]: discarding a portable sign-in that a sign-out or a new identify overtook."),!0;let h=this.initializePortableSignedInUser(r,i,d);h&&this.probeIdentifyPermissionWhenPortableReady(h,s,l)}else if(i.firebaseConfig){this.clearPortableBackendState(),this.setFirebaseConfig(i.firebaseConfig),yield this.signInWithCustomToken(r,i.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let s=yield Pp(this.afAuth.currentUser,!0).catch(l=>null);if(!s)return!1;let{user:a,advancedQueries:c}=s.claims;this.setAdvancedQueries(c),this.providedUser.isAdmin=!!a?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,o,r)}return!0})}applyPortableProjectConfig(r){return y(this,null,function*(){try{let i=yield HN({apiEndpoint:r?.apiEndpoint,token:r?.token});if(!i)return;this.applyProjectConfig(i)}catch(i){this.loggingService.catch("Error in applyPortableProjectConfig: ",i)}})}applyProjectConfig(r){this.setIsPrivateCommentsEnabled(!!r?.isPrivateCommentsEnabled);let i=r?.activityConfig??{immutable:!1,isEnabled:!1};this.cachedActivityConfig=i,this.activityService?.setActivityFeatureConfig(i)}handlePortableBackendResponse(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: handlePortableBackendResponse","color: green;"),this.portableBackend$.next({backend:r?.backend,wsEndpoint:r?.wsEndpoint,apiEndpoint:r?.apiEndpoint});let i=g2({backend:r?.backend,token:r?.token??null,wsEndpoint:r?.wsEndpoint,apiEndpoint:r?.apiEndpoint});return this.portableChunkReady=i,this.schedulePortableTokenRefresh(r?.token??null),i}catch(i){return this.loggingService.catch("Error in handlePortableBackendResponse: ",i),null}}schedulePortableTokenRefresh(r){try{if(this.clearPortableTokenRefresh(),this.portableToken=r,!r)return;this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0;let i=l2(xp(r),Date.now());if(i!==null?this.armPortableRefreshTimer(i,"expiry"):this.loggingService.log("Velt [portable backend]: no proactive token refresh scheduled (token expiry unreadable or already past)."),typeof document<"u"&&typeof document.addEventListener=="function"){this.portableVisibilityHandler=o=>{try{let s=jN(this.portableToken,Date.now());if(qn(`page.${o?.type??"lifecycle"}`,`visibility=${typeof document<"u"?document.visibilityState:"?"} credentialExpired=${s}`),o?.type==="pageshow"&&o.persisted===!1)return;s?this.refreshPortableToken("focus"):this.checkPortableSessionAgainstStorage(`page.${o?.type??"lifecycle"}`),E2()}catch{}};for(let o of e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS)document.addEventListener(o,this.portableVisibilityHandler);typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("pageshow",this.portableVisibilityHandler)}this.armPortableStorageListener()}catch(i){this.loggingService.catch("Error scheduling portable token refresh: ",i)}}readStoredPortableSessionRaw(){try{return localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{return}}readPortableSavedSession(r){return y(this,null,function*(){try{let i;try{i=localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{return{verdict:"persist"}}if(!i){let a=this.readPortableSignOutAt();return{verdict:a!==null&&a>=this.portableSessionStartedAt?"stop":"persist"}}if(i===this.portableSavedSessionRaw)return{verdict:"persist"};let o=null;try{o=yield hp(i,this.apiKey??"")}catch{o=null}return o?.v!==1||o?.apiKey!==this.apiKey||!o?.user?.userId?{verdict:"renew-only"}:o.user.userId!==r?{verdict:"stop"}:{verdict:"persist",sharedRefreshToken:(o?.portableBackendUrl??null)===(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)?ol(o?.res):void 0}}catch(i){return this.loggingService.catch("Error in AuthService readPortableSavedSession: ",i),{verdict:"persist"}}})}recordPortableSignOut(){try{if(!this.apiKey)return;let r={};try{let i=JSON.parse(localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{r={}}r[this.apiKey]=Date.now(),localStorage.setItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT,JSON.stringify(r))}catch{}}armPortableRefreshTimer(r,i){this.cancelPortableRefreshTimer(),this.portableRefreshTimer=setTimeout(()=>this.refreshPortableToken(i),r)}cancelPortableRefreshTimer(){this.portableRefreshTimer&&(clearTimeout(this.portableRefreshTimer),this.portableRefreshTimer=null)}readPortableSignOutAt(){try{let r=JSON.parse(localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)??"null"),i=r&&this.apiKey?r[this.apiKey]:void 0;return typeof i=="number"&&Number.isFinite(i)?i:null}catch{return null}}clearPortableTokenRefresh(){try{if(this.cancelPortableRefreshTimer(),this.portableVisibilityHandler&&typeof document<"u")for(let r of e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS)document.removeEventListener(r,this.portableVisibilityHandler);this.portableVisibilityHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("pageshow",this.portableVisibilityHandler),this.portableVisibilityHandler=null,this.portableStorageHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("storage",this.portableStorageHandler),this.portableStorageHandler=null}catch{}}refreshPortableToken(r){return y(this,null,function*(){let i=this.portableSessionEpoch;if(this.portableRefreshInFlightEpoch!==i){this.portableRefreshInFlightEpoch=i;try{let o=this.portableSessionIdentity,s=o?.user;if(!o||o.epoch!==i||!s?.userId||!this.portableBackend$.value)return;if(this.portableRenewalStopped?.epoch===i){qn("credential.refresh-skipped",`${this.portableRenewalStopped.reason}; waiting for identify()`);return}let a=yield this.readPortableSavedSession(s.userId);if(i!==this.portableSessionEpoch)return;if(a.verdict==="stop"){this.endPortableSessionFromAnotherPage(s,`refresh:${r}`);return}let c=a.sharedRefreshToken,l=this.endpointsService.getPortableIdentifyUrl()??void 0;c&&l&&this.portableSessionIdentity&&c!==this.portableSessionIdentity.refreshToken&&(qn("credential.shared-adopted"),this.portableSessionIdentity=me(B({},this.portableSessionIdentity),{refreshToken:c,refreshTokenIssuer:l}));let d=this.portableSessionIdentity??o,h=d.refreshToken&&d.refreshTokenIssuer===l?d.refreshToken:void 0;if(!h){this.reportPortableRefreshMisconfigured(e.PORTABLE_NO_CREDENTIAL_ENVELOPE),this.endPortableSessionForDeadCredential(s,e.PORTABLE_NO_CREDENTIAL_ENVELOPE,r);return}this.loggingService.log(`Velt [portable backend]: refreshing the gateway credential (${r}).`),qn("credential.refresh-requested",`reason=${r} via=refresh`);let f=yield this.requestPortableRefresh(h);if(i!==this.portableSessionEpoch){qn("credential.refresh-discarded",`reason=${r}`),this.loggingService.log("Velt [portable backend]: discarding a credential refresh that a sign-out or a new identify overtook.");return}if(!this.shouldHandlePortableBackend(f)||!f?.token){if(f?.code===VN){this.endPortableSessionForDeadCredential(s,f,r);return}if(BN.has(f?.code)){qn("credential.refresh-misconfigured",`code=${f?.code}`),this.portableRenewalStopped={epoch:i,reason:`renewal refused: ${f?.code}`},this.cancelPortableRefreshTimer(),this.reportPortableRefreshMisconfigured(f);return}this.portableRefreshFailures++,this.portableRefreshFailures>=e.PORTABLE_REFRESH_WARN_AFTER_FAILURES&&this.reportPortableRefreshFailing(f,i);let S=Date.now();jN(this.portableToken,S)&&this.portableRefreshFailuresPastExpiry++,this.armPortableRefreshTimer(u2(xp(this.portableToken),S,this.portableRefreshFailuresPastExpiry),r);return}let g=this.readStoredPortableSessionRaw(),E=yield this.readPortableSavedSession(s.userId);if(i!==this.portableSessionEpoch){qn("credential.refresh-discarded",`reason=${r}`);return}if(E.verdict==="stop"){this.endPortableSessionFromAnotherPage(s,`refresh-answered:${r}`);return}qn("credential.refreshed"),this.handlePortableBackendResponse(f);let I=ol(f)??h;this.portableSessionIdentity?.epoch===i&&(this.portableSessionIdentity=me(B({},this.portableSessionIdentity),{refreshToken:I,refreshTokenIssuer:l})),E.verdict==="persist"&&this.persistPortableSession(s,me(B({},f),{refreshToken:I}),{expectStoredRaw:g})}catch(o){this.loggingService.catch("Error refreshing portable token: ",o)}finally{this.portableRefreshInFlightEpoch===i&&(this.portableRefreshInFlightEpoch=null)}}})}reportPortableRefreshFailing(r,i){try{if(this.portableRefreshWarnedEpoch===i)return;this.portableRefreshWarnedEpoch=i,console.warn(`Velt [portable backend]: could not renew the gateway credential (${this.portableRefreshFailures} attempts in a row${r?.code?`, last: ${r.code}`:""}). The SDK keeps retrying \u2014 every 30 s while the current token is valid; once it has expired, after 30 s, doubling up to every 16 minutes, and each time the page becomes active again \u2014 and the realtime session is unavailable from the moment the token expires until a renewal succeeds. Check that the gateway's /identify/refresh endpoint is reachable and the API key is enabled.`)}catch{}}endPortableSessionForDeadCredential(r,i,o){qn("credential.refresh-credential-invalid",`reason=${o}`),this.portableSavedSessionRaw&&this.clearPersistedPortableSessionIfUnchanged(this.portableSavedSessionRaw),this.endPortableSessionLocally(r),this.emitIdentifyTokenExpiredError(i,r,"internal-portableRefresh")}endPortableSessionFromAnotherPage(r,i){qn("session.ended-elsewhere",i),this.loggingService.log("Velt [portable backend]: another page signed out or signed in another user; this page's session ends too."),this.endPortableSessionLocally(r)}checkPortableSessionAgainstStorage(r){return y(this,null,function*(){try{let i=this.portableSessionEpoch,o=this.portableSessionIdentity;if(!o||o.epoch!==i||!o.user?.userId)return;let{verdict:s}=yield this.readPortableSavedSession(o.user.userId);s==="stop"&&i===this.portableSessionEpoch&&this.endPortableSessionFromAnotherPage(o.user,r)}catch(i){this.loggingService.catch("Error checking the portable session against storage: ",i)}})}armPortableStorageListener(){try{if(this.portableStorageHandler||typeof window>"u"||typeof window.addEventListener!="function")return;this.portableStorageHandler=r=>{try{let i=r?.key;if(i!==null&&i!==k.LOCAL_STORAGE.VELT_PORTABLE_SESSION&&i!==k.LOCAL_STORAGE.VELT_PORTABLE_SIGNED_OUT)return;this.portableSessionIdentity?this.checkPortableSessionAgainstStorage("storage"):this.portableResumeUserId&&this.resumePortableSessionFromAnotherPage()}catch{}},window.addEventListener("storage",this.portableStorageHandler)}catch(r){this.loggingService.catch("Error arming the portable storage listener: ",r)}}resumePortableSessionFromAnotherPage(){let r=this.portableResumeUserId;!r||this.portableSessionIdentity||this.initializeClientToken||!this.autoLoginRequired||this.configService?.getEnablePortableBackend()!==!0||(this.portableAutoLoginInFlight=this.portableAutoLoginInFlight.then(()=>this.autoLoginPortableSession({onlyUserId:r})).catch(()=>{}))}initializePortableSignedInUser(r,i,o=null){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: initializePortableSignedInUser","color: green;"),!i?.token)return this.portableAuthUser$.value&&(this.userPermissionService?.invalidateAllPermissionsState(),this.releaseLiveUserSession("clear")),null;let s=new so;s.type="signedIn",s=B(B(B({},s),r),_re(o)),WN(s,{provided:me(B({},r),{isAdmin:c2(i?.token)}),resolved:o,avatarColor:c=>this.getUserAvatarColor(c),textColor:c=>this.getUserTextColor(c)}),this.setUserToStorage(s),this.persistPortableSession(s,i);let a=Object.assign({},s);return delete a.contacts,this.analyticsService.identifyUser(s.userSnippylyId,a,{forceReset:this.userOptions$.value?.forceReset}),this.user$.next(s),this.portableAuthUser$.next({uid:s.userSnippylyId}),s}catch(s){return this.loggingService.catch("Error in initializePortableSignedInUser: ",s),null}}clearPortableBackendState(){try{this.portableSignOutOwnsEpochBump||this.portableSessionEpoch++,this.releasePortableSession({clearStorage:!0})}catch(r){this.loggingService.catch("Error clearing portable backend state: ",r)}}releaseLiveUserSession(r){this.resetServicesCache(),this.user$.next(null),r==="local"?this.releasePortableSession({clearStorage:!1}):this.clearPortableBackendState()}releasePortableSession(r){this.portablePlanSeeded&&(this.portablePlanSeeded=!1,this.getPlanDetailsCalled=!1),this.pendingPortableRestore=null,this.portableSessionIdentity=null,r.clearStorage&&(this.portableAutoLoginCalled||this.configService?.getEnablePortableBackend()===!0)&&this.clearPersistedPortableSession(),!(!this.portableBackend$.value&&!this.portableAuthUser$.value)&&(this.clearPortableTokenRefresh(),this.portableToken=null,this.portableChunkReady=null,this.portableRefreshFailures=0,this.portableRefreshFailuresPastExpiry=0,this.portableBackend$.next(null),this.portableAuthUser$.next(null),this.user$.next(null),m2())}endPortableSessionLocally(r){try{this.userPermissionService?.invalidateAllPermissionsState(),this.portableSessionEpoch++,this.portableLocalSessionEnds++,this.releaseLiveUserSession("local"),this.autoLoginRequired=!0,this.portableResumeUserId=r?.userId??null,this.armPortableStorageListener()}catch(i){this.loggingService.catch("Error ending the portable session: ",i)}}trackAutoAuthSuccess(r,i){this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r),source:i})}buildAutoLoginOptions(){return this.userOptions$?.value?me(B({},this.userOptions$.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{}}persistPortableSession(r,i,o){let s=this.portableSessionEpoch;return this.portablePersistInFlight=this.portablePersistInFlight.then(()=>this.writePortableSessionEnvelope(r,i,s,o?.expectStoredRaw)).catch(()=>{}),this.portablePersistInFlight}writePortableSessionEnvelope(r,i,o,s){return y(this,null,function*(){try{if(!i?.token||!r?.userId||!this.apiKey)return;let a=this.user$.value;if(a?.userSnippylyId&&r.userSnippylyId&&a.userSnippylyId!==r.userSnippylyId)return;let c=this.getUserWithoutContacts(r);if(!c)return;let l={v:1,apiKey:this.apiKey,portableBackendUrl:this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null,user:c,res:B({backend:i.backend,wsEndpoint:i.wsEndpoint,apiEndpoint:i.apiEndpoint,token:i.token},ol(i)?{refreshToken:ol(i)}:{})},d=yield UT(l,this.apiKey);if(o!==this.portableSessionEpoch){this.loggingService.log("Velt [portable backend]: dropping a session envelope write that a sign-out or a new identify overtook.");return}if(s!==void 0&&localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)!==s){this.loggingService.log("Velt [portable backend]: not re-persisting a refreshed credential \u2014 another page changed the saved session meanwhile.");return}let h=this.readPortableSignOutAt();if(h!==null&&h>this.portableSessionStartedAt){this.loggingService.log("Velt [portable backend]: not persisting the session \u2014 another page signed out after it began.");return}typeof d=="string"&&!d.startsWith("{")&&d!==JSON.stringify(l)&&(localStorage.setItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION,d),this.portableSavedSessionRaw=d)}catch(a){this.loggingService.catch("Error in writePortableSessionEnvelope: ",a)}})}readPersistedPortableSession(){return y(this,null,function*(){try{let r=localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION);if(!r)return null;let i=yield hp(r,this.apiKey??"");return i?i.v!==1||i.apiKey!==this.apiKey||!i.user?.userId||!i.res?.token?(this.clearPersistedPortableSession(),null):(this.portableSavedSessionRaw=r,{envelope:i,raw:r}):null}catch(r){return this.loggingService.catch("Error in readPersistedPortableSession: ",r),null}})}clearPersistedPortableSession(){this.portableSavedSessionRaw=null;try{localStorage.removeItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)}catch{}}clearPersistedPortableSessionIfUnchanged(r){try{r&&localStorage.getItem(k.LOCAL_STORAGE.VELT_PORTABLE_SESSION)===r&&this.clearPersistedPortableSession()}catch{}}isPortableTokenNearExpiry(r){let i=xp(r);return i===null||i-Date.now()<=GN}isPortableRestoreConfigured(){try{let r=this.endpointsService?.getPortableIdentifyUrl?.();return this.configService?.getEnablePortableBackend()===!0&&!!r&&!$c(r)}catch{return!1}}isRestorablePortableSession(r,i,o){try{if(!this.isPortableRestoreConfigured()||o?.forceReset||r.portableBackendUrl!==(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)||!nl(r.res?.apiEndpoint)||r.user?.userSnippylyId!==i?.userSnippylyId)return!1;let s=this.user$.value;return s?.userSnippylyId&&s.userSnippylyId!==r.user.userSnippylyId||this.isPortableTokenNearExpiry(r.res.token)?!1:this.shouldHandlePortableBackend(r.res)}catch(s){return this.loggingService.catch("Error in isRestorablePortableSession: ",s),!1}}takePendingPortableRestore(r,i){let o=this.pendingPortableRestore;if(this.pendingPortableRestore=null,!o)return null;let s=o.resume===!0;return o.epoch!==this.portableSessionEpoch?{envelope:null,overtaken:!0,raw:o.raw,resume:s}:{envelope:this.isRestorablePortableSession(o.envelope,r,i)?o.envelope:null,overtaken:!1,raw:o.raw,resume:s}}autoLoginPortableSession(r){return y(this,null,function*(){let i=this.portableSessionEpoch,o=()=>i!==this.portableSessionEpoch||!this.autoLoginRequired,s=!!r?.onlyUserId;try{let a=yield this.readPersistedPortableSession(),c=a?.envelope;if(!a||!c||o()||s&&c.user?.userId!==r?.onlyUserId)return;if(!this.isPortableRestoreConfigured()){s||this.clearPersistedPortableSession();return}if(c.portableBackendUrl!==(this.configService?.getSelfHostedConfig?.()?.portableBackendUrl??null)){s||(this.loggingService.log("Velt [portable backend]: the persisted session belongs to a different gateway; dropped."),this.clearPersistedPortableSession());return}let l=c;if(this.isPortableTokenNearExpiry(c.res.token)){let h=ol(c.res);if(!h){this.loggingService.log("Velt [portable backend]: the persisted session has no renewal credential; waiting for identify()."),this.clearPersistedPortableSessionIfUnchanged(a.raw);return}qn("credential.restore-renew","via=refresh");let f=yield this.requestPortableRefresh(h);if(o())return;if(!this.shouldHandlePortableBackend(f)||!f?.token){if(f?.code==="network_error"){this.loggingService.log("Velt [portable backend]: could not reach the gateway to renew the persisted session; keeping it for the next attempt.");return}if(BN.has(f?.code)&&this.reportPortableRefreshMisconfigured(f),f?.code!==VN){this.loggingService.log(`Velt [portable backend]: the persisted session's renewal was refused for now (${f?.code??"no code"}); keeping it for the next attempt.`);return}this.loggingService.log("Velt [portable backend]: the persisted session could not be renewed on reload; waiting for identify()."),this.clearPersistedPortableSessionIfUnchanged(a.raw);return}let g=ol(f)??h;l=me(B({},c),{res:{backend:f.backend,wsEndpoint:f.wsEndpoint,apiEndpoint:f.apiEndpoint,token:f.token,refreshToken:g}})}if(o())return;this.pendingPortableRestore=B({envelope:l,epoch:i,raw:a.raw},s?{resume:!0}:{});let d=this.buildAutoLoginOptions();s&&delete d.forceReset,yield this.initializeClient(B({},l.user),d,new Date().getTime(),!0,"internal-autoLogin")}catch(a){this.loggingService.catch("Error in autoLoginPortableSession: ",a)}finally{this.pendingPortableRestore=null}})}getPortableBackend(){return this.portableBackend$.value}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(r){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{r&&typeof r=="object"&&localStorage.setItem(k.LOCAL_STORAGE.VELT_ADVANCED_QUERIES,JSON.stringify(r)),this.advancedQueries$.next(r)}catch(i){this.loggingService.catch("Error in setAdvancedQueries: ",i)}}getAdvancedQueries$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries$","color: green;"),this.advancedQueries$.asObservable()}getAdvancedQueries(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAdvancedQueries","color: green;"),this.advancedQueries$.value}getAdvancedQueriesEnabled(r){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&(r||!!this.getAdvancedQueries()?.advancedQueriesEnabled)}catch(i){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",i),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser||this.portableAuthUser$.value?this.user$.value:null}getProvidedOrCurrentUserId(){try{return this.providedUser?.userId??this.user$.value?.userId??void 0}catch(r){this.loggingService.catch("Error in getProvidedOrCurrentUserId: ",r);return}}scheduleLoggedInUserResolveRetry(r,i){return y(this,null,function*(){try{if(!r||this.loggedInUserResolveRetryInFlightUserId===r)return;this.loggedInUserResolveRetryInFlightUserId=r;let o=this.loggedInUserResolveRetryDelaysMs;for(let s=0;s<o.length;s++){if(yield new Promise(l=>setTimeout(l,o[s])),(this.providedUser?.userId??this.user$.value?.userId)!==r)return;let a=yield this.usersService?.resolveUsers({userIds:[r],organizationId:i,skipUserCheck:!0,forceResolve:!0,moduleName:bT.IDENTIFY});if((this.providedUser?.userId??this.user$.value?.userId)!==r)return;let c=a?.[r];if(c&&this.applyLateResolvedLoggedInUser(r,c))return}this.loggingService.catch(`User resolver did not return the logged-in user after ${o.length} retry attempts \u2014 comments created by this author will have no resolved profile until the resolver returns them`,{userId:r,organizationId:i,attempts:o.length})}catch(o){this.loggingService.catch("Error in scheduleLoggedInUserResolveRetry: ",o)}finally{this.loggedInUserResolveRetryInFlightUserId===r&&(this.loggedInUserResolveRetryInFlightUserId=null)}})}applyLateResolvedLoggedInUser(r,i){try{let o=this.user$.value;if(!o||o.userId!==r)return!1;if(!this.afAuth?.currentUser&&!this.portableAuthUser$.value)return!0;let s=mre(o,i);return this.setUserToStorage(s),this.user$.next(s),!0}catch(o){return this.loggingService.catch("Error in applyLateResolvedLoggedInUser: ",o),!1}}combinedAuthBearer$(){let r=!1;return oc([Ed(this.afAuth).pipe(nn(iw)),this.portableAuthUser$]).pipe(En(([i,o])=>(o!==null&&(r=!0),!!(i!==iw||o!==null||r))),De(([i,o])=>(i===iw?null:i)??o))}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),this.combinedAuthBearer$().pipe(Zn(r=>r?this.user$.asObservable():ot(null)),ai(pp))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getAuthState$(){return this.combinedAuthBearer$()}getIdTokenResultForUser(r,i){return Pp(r,i)}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(r){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let i=this.user$.value;if(r.userId&&r.userId!==i?.userId||r?.groupId&&r?.groupId!==i?.groupId||r?.organizationId&&r?.organizationId!==i?.organizationId)this.providedUser=r,this.initializeClient(r,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=B(B({},this.providedUser),r),i){let o=B(B({},i),r);this.updateUserInternally(o)}}catch(i){this.loggingService.catch("Error in updateUser: ",i)}}signInWithCustomToken(r,i,o="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return FG(this.afAuth,i).then(s=>(this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:o,forceReset:this.userOptions$.value?.forceReset,user:this.getUserForTelemetry(r)}),s)).catch(s=>(this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:r.userId,snippylyUserId:r.userSnippylyId,authType:o,forceReset:this.userOptions$.value?.forceReset,message:s.message,user:this.getUserForTelemetry(r)}),s))}catch(s){return this.loggingService.catch("Error in signInWithCustomToken: ",s),Promise.reject(s)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.activityService?.resetActivityFeatureConfig()}catch(r){this.loggingService.catch("Error in clearCache: ",r)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.serviceBook.get(IT)?.clearCache(),this.viewsService?.clearCache()}catch(r){this.loggingService.catch("Error in resetServicesCache: ",r)}}initializeSignedInUser(r,i,o){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let s=new so;s.userSnippylyId=r.uid,s.type="signedIn",o&&(s=B(B({},s),o)),this.setUserToStorage(s),this.mergeUserWithProvidedUserData(s,i)}catch(s){this.loggingService.catch("Error in initializeSignedInUser: ",s)}}resolveSignedInUserWithProvider(r,i){return y(this,null,function*(){{let o=ad(),s=bT.IDENTIFY;this.coreActionsService.triggerAction(oo.USER_RESOLVER,{event:vt.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:fR.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:s,source:"internal",payload:{userIds:[r.userId],organizationId:i}});let a=yield this.usersService?.resolveUsers({userIds:[r.userId],organizationId:i,skipUserCheck:!0,uniqueId:o,moduleName:s});return a&&a[r.userId]?JSON.parse(JSON.stringify(a[r.userId]||{})):(this.scheduleLoggedInUserResolveRetry(r.userId,i),null)}})}mergeUserWithProvidedUserData(r,i){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{r.userId=this.providedUser?.userId||r.userId;let o=null;if(this.usersService?.externalUserDataProviderAvailable()){let s=this.providedUser?.clientOrganizationId||r.clientOrganizationId;o=yield this.resolveSignedInUserWithProvider(r,s),r=B(B({},r),o||{})}WN(r,{provided:this.providedUser,resolved:o,avatarColor:s=>this.getUserAvatarColor(s),textColor:s=>this.getUserTextColor(s)}),this.updateUserInternally(r)}catch(o){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",o)}})}updateUserInternally(r){return y(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let i=Object.assign({},r);delete i.contacts,this.analyticsService.identifyUser(r.userSnippylyId,i,{forceReset:this.userOptions$.value?.forceReset});let o=this.portableBackend$.value,s=this.portableSessionEpoch;!this.getPlanDetailsCalled&&!o&&this.getPlanDetailsFromDb();let a;if(o)a=HN({apiEndpoint:o.apiEndpoint,token:this.portableToken});else{let h=Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));a=cB({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:h,userId:r?.userId??""})}let c=Promise.resolve();o?this.probeIdentifyPermissionWhenPortableReady(r,s,this.portableChunkReady):c=this.buildIdentifyPermissionProbe(r);let[l,d]=yield Promise.allSettled([a,c]);if(o){if(s!==this.portableSessionEpoch){this.loggingService.log("Velt [portable backend]: discarding an updateUser() that a sign-out or a new identify overtook.");return}l.status==="fulfilled"&&l.value&&this.applyProjectConfig(l.value)}else l.status==="fulfilled"?this.applyProjectConfig(l.value?.data):this.loggingService.warn("Failed to fetch project config:",l.reason);this.afAuth.currentUser?(this.user$.next(r),this.updateUserToFirebase(r)):this.portableAuthUser$.value&&this.user$.next(r)}catch(i){this.loggingService.catch("Error in updateUserInternally: ",i)}})}buildIdentifyPermissionProbe(r){if(this.userPermissionService?.isPermissionProviderAvailable()&&r.clientOrganizationId){let i=[{userId:r.userId,resource:{id:r.clientOrganizationId,type:iV.ORGANIZATION,source:OT.IDENTIFY,organizationId:r.clientOrganizationId}}],o=ad();return this.coreActionsService.triggerAction(oo.PERMISSION_PROVIDER,{event:vt.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:OT.IDENTIFY,uniqueId:o,timestamp:new Date().getTime(),source:"internal",payload:{requests:i}}),this.userPermissionService?.onResourceAccessRequired({requests:i,uniqueId:o,userId:r.userId,methodName:OT.IDENTIFY,fromCache:!1})??Promise.resolve()}return Promise.resolve()}probeIdentifyPermissionWhenPortableReady(r,i,o){return y(this,null,function*(){try{if(yield o,i!==this.portableSessionEpoch||this.user$.value?.userId!==r.userId||!q2()||this.commonDbService?.isPortableBackendActive?.()!==!0)return;yield this.buildIdentifyPermissionProbe(r)}catch(s){this.loggingService.catch("Error in probeIdentifyPermissionWhenPortableReady: ",s)}})}updateUserToFirebase(r){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let i=JSON.parse(JSON.stringify(r)),o=me(B({},i),{lastUpdated:new Date})}catch(i){this.loggingService.catch("Error in updateUserToFirebase: ",i)}}getPlanDetailsFromDb(){return y(this,null,function*(){try{this.getPlanDetailsCalled=!0;let i=yield Td(this.functions,ud({url:this.endpointsService.getCloudFunctionUrl("getPlanDetails"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:Wc(),sdkType:this.configService.getSdkType()});return i?.data?.isPlanExpired&&(this.analyticsService.trackEvent(vt.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(i?.data||{planInfo:null,isPlanExpired:!1}),i}catch(r){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",r),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe(En(r=>!!r),De(r=>!!r?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(r,i){try{this.preSignOutFunctions.set(r,i)}catch(o){this.loggingService.catch("Error in addPreSignOutFuction: ",o)}}setUserOrganization(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===r?.organizationId?(i.metadata=r,this.userOrganization$.next(i)):this.userOrganization$.next(null)}catch(i){this.loggingService.catch("Error in setUserOrganization: ",i)}}setOrganizationUserGroups(r){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let i=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===i?.metadata?.organizationId&&(i.groups=r,this.userOrganization$.next(i))}catch(i){this.loggingService.catch("Error in setUserOrganizationGroups: ",i)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(Zn(r=>r?this.userOrganization$.asObservable().pipe(De(i=>i?.metadata?.organizationId===r.organizationId?i:null)):ot(null)))}signOutUser(r="internal"){return y(this,null,function*(){try{this.userPermissionService?.invalidateAllPermissionsState(),this.portableSessionEpoch++,this.portableSignOutOwnsEpochBump=!0,this.pendingPortableRestore=null,this.portableResumeUserId=null,this.portableSessionIdentity=null,(this.portableAutoLoginCalled||this.configService?.getEnablePortableBackend()===!0)&&(this.clearPersistedPortableSession(),this.recordPortableSignOut(),this.clearPortableTokenRefresh()),r==="external"&&(this.onRetrySubscription?.unsubscribe(),this.authProviderListenerGeneration++),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(vt.Events.Core.SDK_USER_SIGN_OUT,{apiKey:this.apiKey,clientUserId:this.user$?.value?.userId,snippylyUserId:this.user$?.value?.userSnippylyId,message:r==="external"?"User Sign out":"System Sign out",user:this.user$?.value?this.getUserForTelemetry(this.user$?.value):null,forceReset:this.userOptions$.value?.forceReset,source:r});let i=yield Ed(this.afAuth).pipe(_n(1)).toPromise().catch(o=>null);if(i){this.releaseLiveUserSession("clear");for(let[o,s]of this.preSignOutFunctions)try{yield s(i)}catch(a){this.loggingService.catch(`Error in signOutUser ${o} function: `,a)}return this.user$.next(null),yield tB(1e3),UG(this.afAuth).catch(o=>{this.loggingService.catch("Error in signOutUser:",o)})}else return(this.portableAuthUser$.value||this.portableBackend$.value)&&this.releaseLiveUserSession("clear"),Promise.resolve()}catch(i){this.loggingService.catch("Error in signOutUser: ",i)}finally{this.portableSignOutOwnsEpochBump=!1}})}isFeatureAllowed(r){return WV(this.config,this.user$.value,r)}getUserWithoutContacts(r){try{if(r){let i=JSON.parse(JSON.stringify(r));return delete i.contacts,i}else return null}catch(i){return this.loggingService.catch("Error in getUserWithoutContacts: ",i),null}}getUserForTelemetry(r){try{let i=this.getUserWithoutContacts(r);return i?this.usersService?.userResolverConfigured?.()?MR(i):i:null}catch(i){return this.loggingService.catch("Error in getUserForTelemetry: ",i),null}}getUserForClient(r){try{return wR(r)}catch(i){return this.loggingService.catch("Error in getUserForClient: ",i),null}}getUserAvatarColor(r){try{return r?this.avatarService.generateUserColor(jc(r)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(r){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(r){try{r.forEach(i=>{try{i?.color||(i.color=this.getUserAvatarColor(i?.userId)),i?.textColor||(i.textColor=this.getUserTextColor(i?.userId)),!i?.initial&&(i?.name||i?.email)&&(i.initial=i.name?.charAt(0).toUpperCase()||i.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};e.PORTABLE_REFRESH_WARN_AFTER_FAILURES=3,e.PORTABLE_DOCUMENT_LIFECYCLE_EVENTS=["visibilitychange","resume"],e.PORTABLE_NO_CREDENTIAL_ENVELOPE={error:"No renewal credential.",code:"no_renewal_credential",message:"the session has no renewal credential for the configured gateway",source:"identify"},e.\u0275fac=function(i){return new(i||e)(z(Zc),z(fo),z(T2),z(y2),z(W2),z(Zo),z(Zs),z(Rt),z(CT))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Y2="@firebase/database",X2="1.0.20";var ub="";function Tre(t){ub=t}var hw=class{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Pt(n))}get(e){let n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:hd(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}};var fw=class{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return zr(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}};var Nj=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){let e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new hw(e)}}catch{}return new fw},al=Nj("localStorage"),pw=Nj("sessionStorage");var Dd=new qr("@firebase/database"),wj=(function(){let t=1;return function(){return t++}})(),bj=function(t){let e=bB(t),n=new HT;n.update(e);let r=n.digest();return fd.encodeByteArray(r)},cg=function(...t){let e="";for(let n=0;n<t.length;n++){let r=t[n];Array.isArray(r)||r&&typeof r=="object"&&typeof r.length=="number"?e+=cg.apply(null,r):typeof r=="object"?e+=Pt(r):e+=r,e+=" "}return e},cl=null,Q2=!0,yre=function(t,e){Y(!e||t===!0||t===!1,"Can't turn on custom loggers persistently."),t===!0?(Dd.logLevel=we.VERBOSE,cl=Dd.log.bind(Dd),e&&pw.set("logging_enabled",!0)):typeof t=="function"?cl=t:(cl=null,pw.remove("logging_enabled"))},ln=function(...t){if(Q2===!0&&(Q2=!1,cl===null&&pw.get("logging_enabled")===!0&&yre(!0)),cl){let e=cg.apply(null,t);cl(e)}},lg=function(t){return function(...e){ln(t,...e)}},gw=function(...t){let e="FIREBASE INTERNAL ERROR: "+cg(...t);Dd.error(e)},rs=function(...t){let e=`FIREBASE FATAL ERROR: ${cg(...t)}`;throw Dd.error(e),new Error(e)},Fn=function(...t){let e="FIREBASE WARNING: "+cg(...t);Dd.warn(e)},Ire=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&Fn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Xy=function(t){return typeof t=="number"&&(t!==t||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)},vre=function(t){if(co()||document.readyState==="complete")t();else{let e=!1,n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}e||(e=!0,t())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},ul="[MIN_NAME]",sa="[MAX_NAME]",ml=function(t,e){if(t===e)return 0;if(t===ul||e===sa)return-1;if(e===ul||t===sa)return 1;{let n=J2(t),r=J2(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}},Sre=function(t,e){return t===e?0:t<e?-1:1},Gp=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+Pt(e))},db=function(t){if(typeof t!="object"||t===null)return Pt(t);let e=[];for(let r in t)e.push(r);e.sort();let n="{";for(let r=0;r<e.length;r++)r!==0&&(n+=","),n+=Pt(e[r]),n+=":",n+=db(t[e[r]]);return n+="}",n},Oj=function(t,e){let n=t.length;if(n<=e)return[t];let r=[];for(let i=0;i<n;i+=e)i+e>n?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r};function un(t,e){for(let n in t)t.hasOwnProperty(n)&&e(n,t[n])}var Mj=function(t){Y(!Xy(t),"Invalid JSON number");let e=11,n=52,r=(1<<e-1)-1,i,o,s,a,c;t===0?(o=0,s=0,i=1/t===-1/0?1:0):(i=t<0,t=Math.abs(t),t>=Math.pow(2,1-r)?(a=Math.min(Math.floor(Math.log(t)/Math.LN2),r),o=a+r,s=Math.round(t*Math.pow(2,n-a)-Math.pow(2,n))):(o=0,s=Math.round(t/Math.pow(2,1-r-n))));let l=[];for(c=n;c;c-=1)l.push(s%2?1:0),s=Math.floor(s/2);for(c=e;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);l.push(i?1:0),l.reverse();let d=l.join(""),h="";for(c=0;c<64;c+=8){let f=parseInt(d.substr(c,8),2).toString(16);f.length===1&&(f="0"+f),h=h+f}return h.toLowerCase()},Are=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Cre=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function Dre(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");let r=new Error(t+" at "+e._path.toString()+": "+n);return r.code=t.toUpperCase(),r}var Rre=new RegExp("^-?(0*)\\d{1,10}$"),Nre=-2147483648,wre=2147483647,J2=function(t){if(Rre.test(t)){let e=Number(t);if(e>=Nre&&e<=wre)return e}return null},xd=function(t){try{t()}catch(e){setTimeout(()=>{let n=e.stack||"";throw Fn("Exception was thrown by user callback.",n),e},Math.floor(0))}},bre=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Wp=function(t,e){let n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};var mw=class{constructor(e,n){this.appCheckProvider=n,this.appName=e.name,rr(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=n?.getImmediate({optional:!0}),this.appCheck||n?.get().then(r=>this.appCheck=r)}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((n,r)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(r=>r.addTokenListener(e))}notifyForInvalidToken(){Fn(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}};var Ew=class{constructor(e,n,r){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(ln("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,r)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.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/.',Fn(e)}},zp=(()=>{class t{constructor(n){this.accessToken=n}getToken(n){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(n){n(this.accessToken)}removeTokenChangeListener(n){}notifyForInvalidToken(){}}t.OWNER="owner";return t})(),Cy="5",Lj="v",Pj="s",xj="r",kj="f",Fj=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Uj="ls",Vj="p",_w="ac",Bj="websocket",Gj="long_polling";var Dy=class{constructor(e,n,r,i,o=!1,s="",a=!1,c=!1,l=null){this.secure=n,this.namespace=r,this.webSocketOnly=i,this.nodeAdmin=o,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=al.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()&&al.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}};function Ore(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function jj(t,e,n){Y(typeof e=="string","typeof type must == string"),Y(typeof n=="object","typeof params must == object");let r;if(e===Bj)r=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===Gj)r=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);Ore(t)&&(n.ns=t.namespace);let i=[];return un(n,(o,s)=>{i.push(o+"="+s)}),r+i.join("&")}var Tw=class{constructor(){this.counters_={}}incrementCounter(e,n=1){zr(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return EB(this.counters_)}};var ow={},sw={};function hb(t){let e=t.toString();return ow[e]||(ow[e]=new Tw),ow[e]}function Mre(t,e){let n=t.toString();return sw[n]||(sw[n]=e()),sw[n]}var yw=class{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,n){for(this.pendingResponses[e]=n;this.pendingResponses[this.currentResponseNum];){let r=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<r.length;++i)r[i]&&xd(()=>{this.onMessage_(r[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}};var Z2="start",Lre="close",Pre="pLPCommand",xre="pRTLPCB",Hj="id",$j="pw",Wj="ser",kre="cb",Fre="seg",Ure="ts",Vre="d",Bre="dframe",zj=1870,qj=30,Gre=zj-qj,jre=25e3,Hre=3e4,Ry=class t{constructor(e,n,r,i,o,s,a){this.connId=e,this.repoInfo=n,this.applicationId=r,this.appCheckToken=i,this.authToken=o,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=lg(e),this.stats_=hb(n),this.urlFn=c=>(this.appCheckToken&&(c[_w]=this.appCheckToken),jj(n,Gj,c))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new yw(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Hre)),vre(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Iw((...o)=>{let[s,a,c,l,d]=o;if(this.incrementIncomingBytes_(o),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,s===Z2)this.id=a,this.password=c;else if(s===Lre)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+s)},(...o)=>{let[s,a]=o;this.incrementIncomingBytes_(o),this.myPacketOrderer.handleResponse(s,a)},()=>{this.onClosed_()},this.urlFn);let r={};r[Z2]="t",r[Wj]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(r[kre]=this.scriptTagHolder.uniqueCallbackIdentifier),r[Lj]=Cy,this.transportSessionId&&(r[Pj]=this.transportSessionId),this.lastSessionId&&(r[Uj]=this.lastSessionId),this.applicationId&&(r[Vj]=this.applicationId),this.appCheckToken&&(r[_w]=this.appCheckToken),typeof location<"u"&&location.hostname&&Fj.test(location.hostname)&&(r[xj]=kj);let i=this.urlFn(r);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){t.forceAllow_=!0}static forceDisallow(){t.forceDisallow_=!0}static isAvailable(){return co()?!1:t.forceAllow_?!0:!t.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!Are()&&!Cre()}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){let n=Pt(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);let r=UR(n),i=Oj(r,Gre);for(let o=0;o<i.length;o++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[o]),this.curSegmentNum++}addDisconnectPingFrame(e,n){if(co())return;this.myDisconnFrame=document.createElement("iframe");let r={};r[Bre]="t",r[Hj]=e,r[$j]=n,this.myDisconnFrame.src=this.urlFn(r),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let n=Pt(e).length;this.bytesReceived+=n,this.stats_.incrementCounter("bytes_received",n)}},Iw=class t{constructor(e,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0,co())this.commandCB=e,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=wj(),window[Pre+this.uniqueCallbackIdentifier]=e,window[xre+this.uniqueCallbackIdentifier]=n,this.myIFrame=t.createIFrame_();let o="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(o='<script>document.domain="'+document.domain+'";<\/script>');let s="<html><body>"+o+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(s),this.myIFrame.doc.close()}catch(a){ln("frame writing exception"),a.stack&&ln(a.stack),ln(a)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||ln("No IE domain setting required")}catch{let r=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+r+"';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)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;let e={};e[Hj]=this.myID,e[$j]=this.myPW,e[Wj]=this.currentSerial;let n=this.urlFn(e),r="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+qj+r.length<=zj;){let s=this.pendingSegs.shift();r=r+"&"+Fre+i+"="+s.seg+"&"+Ure+i+"="+s.ts+"&"+Vre+i+"="+s.d,i++}return n=n+r,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,r){this.pendingSegs.push({seg:e,ts:n,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);let r=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(r,Math.floor(jre)),o=()=>{clearTimeout(i),r()};this.addTag(e,o)}addTag(e,n){co()?this.doNodeLongPoll(e,n):setTimeout(()=>{try{if(!this.sendNewPolls)return;let r=this.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){let i=r.readyState;(!i||i==="loaded"||i==="complete")&&(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),n())},r.onerror=()=>{ln("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(r)}catch{}},Math.floor(1))}};var $re=16384,Wre=45e3,Ny=null;typeof MozWebSocket<"u"?Ny=MozWebSocket:typeof WebSocket<"u"&&(Ny=WebSocket);var Ad=(()=>{class t{constructor(n,r,i,o,s,a,c){this.connId=n,this.applicationId=i,this.appCheckToken=o,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=lg(this.connId),this.stats_=hb(r),this.connURL=t.connectionURL_(r,a,c,o,i),this.nodeAdmin=r.nodeAdmin}static connectionURL_(n,r,i,o,s){let a={};return a[Lj]=Cy,!co()&&typeof location<"u"&&location.hostname&&Fj.test(location.hostname)&&(a[xj]=kj),r&&(a[Pj]=r),i&&(a[Uj]=i),o&&(a[_w]=o),s&&(a[Vj]=s),jj(n,Bj,a)}open(n,r){this.onDisconnect=r,this.onMessage=n,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,al.set("previous_websocket_failure",!0);try{let i;if(co()){let o=this.nodeAdmin?"AdminNode":"Node";i={headers:{"User-Agent":`Firebase/${Cy}/${ub}/${process.platform}/${o}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(i.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(i.headers["X-Firebase-AppCheck"]=this.appCheckToken);let s=process.env,a=this.connURL.indexOf("wss://")===0?s.HTTPS_PROXY||s.https_proxy:s.HTTP_PROXY||s.http_proxy;a&&(i.proxy={origin:a})}this.mySock=new Ny(this.connURL,[],i)}catch(i){this.log_("Error instantiating WebSocket.");let o=i.message||i.data;o&&this.log_(o),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.");let o=i.message||i.data;o&&this.log_(o),this.onClosed_()}}start(){}static forceDisallow(){t.forceDisallow_=!0}static isAvailable(){let n=!1;if(typeof navigator<"u"&&navigator.userAgent){let r=/Android ([0-9]{0,}\.[0-9]{0,})/,i=navigator.userAgent.match(r);i&&i.length>1&&parseFloat(i[1])<4.4&&(n=!0)}return!n&&Ny!==null&&!t.forceDisallow_}static previouslyFailed(){return al.isInMemoryStorage||al.get("previous_websocket_failure")===!0}markConnectionHealthy(){al.remove("previous_websocket_failure")}appendFrame_(n){if(this.frames.push(n),this.frames.length===this.totalFrames){let r=this.frames.join("");this.frames=null;let i=hd(r);this.onMessage(i)}}handleNewFrameCount_(n){this.totalFrames=n,this.frames=[]}extractFrameCount_(n){if(Y(this.frames===null,"We already have a frame buffer"),n.length<=6){let r=Number(n);if(!isNaN(r))return this.handleNewFrameCount_(r),null}return this.handleNewFrameCount_(1),n}handleIncomingFrame(n){if(this.mySock===null)return;let r=n.data;if(this.bytesReceived+=r.length,this.stats_.incrementCounter("bytes_received",r.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(r);else{let i=this.extractFrameCount_(r);i!==null&&this.appendFrame_(i)}}send(n){this.resetKeepAlive();let r=Pt(n);this.bytesSent+=r.length,this.stats_.incrementCounter("bytes_sent",r.length);let i=Oj(r,$re);i.length>1&&this.sendString_(String(i.length));for(let o=0;o<i.length;o++)this.sendString_(i[o])}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(Wre))}sendString_(n){try{this.mySock.send(n)}catch(r){this.log_("Exception thrown from WebSocket.send():",r.message||r.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}t.responsesRequiredToBeHealthy=2,t.healthyTimeout=3e4;return t})(),Kj=(()=>{class t{static get ALL_TRANSPORTS(){return[Ry,Ad]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(n){this.initTransports_(n)}initTransports_(n){let r=Ad&&Ad.isAvailable(),i=r&&!Ad.previouslyFailed();if(n.webSocketOnly&&(r||Fn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),i=!0),i)this.transports_=[Ad];else{let o=this.transports_=[];for(let s of t.ALL_TRANSPORTS)s&&s.isAvailable()&&o.push(s);t.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}}t.globalTransportInitialized_=!1;return t})(),zre=6e4,qre=5e3,Kre=10*1024,Yre=100*1024,aw="t",ej="d",Xre="s",tj="r",Qre="e",nj="o",rj="a",ij="n",oj="p",Jre="h",vw=class{constructor(e,n,r,i,o,s,a,c,l,d){this.id=e,this.repoInfo_=n,this.applicationId_=r,this.appCheckToken_=i,this.authToken_=o,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=d,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=lg("c:"+this.id+":"),this.transportManager_=new Kj(n),this.log_("Connection created"),this.start_()}start_(){let 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;let n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,r)},Math.floor(0));let i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Wp(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Yre?(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>Kre?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(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){let n={t:"d",d:e};this.sendData_(n)}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(aw in e){let n=e[aw];n===rj?this.upgradeIfSecondaryHealthy_():n===tj?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===nj&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let n=Gp("t",e),r=Gp("d",e);if(n==="c")this.onSecondaryControl_(r);else if(n==="d")this.pendingDataMessages.push(r);else throw new Error("Unknown protocol layer: "+n)}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:oj,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:rj,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:ij,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let n=Gp("t",e),r=Gp("d",e);n==="c"?this.onControl_(r):n==="d"&&this.onDataMessage_(r)}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){let n=Gp(aw,e);if(ej in e){let r=e[ej];if(n===Jre){let i=Object.assign({},r);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===ij){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else n===Xre?this.onConnectionShutdown_(r):n===tj?this.onReset_(r):n===Qre?gw("Server Error: "+r):n===nj?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):gw("Unknown control packet command: "+n)}}onHandshake_(e){let n=e.ts,r=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,n),Cy!==r&&Fn("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){let 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;let n=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,r),Wp(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(zre))}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,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Wp(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(qre))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:oj,d:{}}}))}onSecondaryConnectionLost_(){let 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()&&(al.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)}};var wy=class{put(e,n,r,i){}merge(e,n,r,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,r){}onDisconnectMerge(e,n,r){}onDisconnectCancel(e,n){}reportStats(e){}};var by=class{constructor(e){this.allowedEvents_=e,this.listeners_={},Y(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){let r=[...this.listeners_[e]];for(let i=0;i<r.length;i++)r[i].callback.apply(r[i].context,n)}}on(e,n,r){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:n,context:r});let i=this.getInitialEvent(e);i&&n.apply(r,i)}off(e,n,r){this.validateEventType_(e);let i=this.listeners_[e]||[];for(let o=0;o<i.length;o++)if(i[o].callback===n&&(!r||r===i[o].context)){i.splice(o,1);return}}validateEventType_(e){Y(this.allowedEvents_.find(n=>n===e),"Unknown event: "+e)}};var Oy=class t extends by{static getInstance(){return new t}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!_p()&&(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 Y(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}};var sj=32,aj=768,He=class{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let r=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[r]=this.pieces_[i],r++);this.pieces_.length=r,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n<this.pieces_.length;n++)this.pieces_[n]!==""&&(e+="/"+this.pieces_[n]);return e||"/"}};function je(){return new He("")}function be(t){return t.pieceNum_>=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function aa(t){return t.pieces_.length-t.pieceNum_}function ct(t){let e=t.pieceNum_;return e<t.pieces_.length&&e++,new He(t.pieces_,e)}function fb(t){return t.pieceNum_<t.pieces_.length?t.pieces_[t.pieces_.length-1]:null}function Zre(t){let e="";for(let n=t.pieceNum_;n<t.pieces_.length;n++)t.pieces_[n]!==""&&(e+="/"+encodeURIComponent(String(t.pieces_[n])));return e||"/"}function Xp(t,e=0){return t.pieces_.slice(t.pieceNum_+e)}function Yj(t){if(t.pieceNum_>=t.pieces_.length)return null;let e=[];for(let n=t.pieceNum_;n<t.pieces_.length-1;n++)e.push(t.pieces_[n]);return new He(e,0)}function At(t,e){let n=[];for(let r=t.pieceNum_;r<t.pieces_.length;r++)n.push(t.pieces_[r]);if(e instanceof He)for(let r=e.pieceNum_;r<e.pieces_.length;r++)n.push(e.pieces_[r]);else{let r=e.split("/");for(let i=0;i<r.length;i++)r[i].length>0&&n.push(r[i])}return new He(n,0)}function Oe(t){return t.pieceNum_>=t.pieces_.length}function Kn(t,e){let n=be(t),r=be(e);if(n===null)return e;if(n===r)return Kn(ct(t),ct(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function eie(t,e){let n=Xp(t,0),r=Xp(e,0);for(let i=0;i<n.length&&i<r.length;i++){let o=ml(n[i],r[i]);if(o!==0)return o}return n.length===r.length?0:n.length<r.length?-1:1}function pb(t,e){if(aa(t)!==aa(e))return!1;for(let n=t.pieceNum_,r=e.pieceNum_;n<=t.pieces_.length;n++,r++)if(t.pieces_[n]!==e.pieces_[r])return!1;return!0}function Yr(t,e){let n=t.pieceNum_,r=e.pieceNum_;if(aa(t)>aa(e))return!1;for(;n<t.pieces_.length;){if(t.pieces_[n]!==e.pieces_[r])return!1;++n,++r}return!0}var Sw=class{constructor(e,n){this.errorPrefix_=n,this.parts_=Xp(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=vp(this.parts_[r]);Xj(this)}};function tie(t,e){t.parts_.length>0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=vp(e),Xj(t)}function nie(t){let e=t.parts_.pop();t.byteLength_-=vp(e),t.parts_.length>0&&(t.byteLength_-=1)}function Xj(t){if(t.byteLength_>aj)throw new Error(t.errorPrefix_+"has a key path longer than "+aj+" bytes ("+t.byteLength_+").");if(t.parts_.length>sj)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+sj+") or object contains a cycle "+sl(t))}function sl(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}var Aw=class t extends by{static getInstance(){return new t}constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{let r=!document[e];r!==this.visible_&&(this.visible_=r,this.trigger("visible",r))},!1)}getInitialEvent(e){return Y(e==="visible","Unknown event type: "+e),[this.visible_]}};var jp=1e3,rie=300*1e3,cj=30*1e3,iie=1.3,oie=3e4,sie="server_kill",lj=3,gb=(()=>{class t extends wy{constructor(n,r,i,o,s,a,c,l){if(super(),this.repoInfo_=n,this.applicationId_=r,this.onDataUpdate_=i,this.onConnectStatus_=o,this.onServerInfoUpdate_=s,this.authTokenProvider_=a,this.appCheckTokenProvider_=c,this.authOverride_=l,this.id=t.nextPersistentConnectionId_++,this.log_=lg("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_=jp,this.maxReconnectDelay_=rie,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,l&&!co())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Aw.getInstance().on("visible",this.onVisible_,this),n.host.indexOf("fblocal")===-1&&Oy.getInstance().on("online",this.onOnline_,this)}sendRequest(n,r,i){let o=++this.requestNumber_,s={r:o,a:n,b:r};this.log_(Pt(s)),Y(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),i&&(this.requestCBHash_[o]=i)}get(n){this.initConnection_();let r=new an,o={action:"g",request:{p:n._path.toString(),q:n._queryObject},onComplete:a=>{let c=a.d;a.s==="ok"?r.resolve(c):r.reject(c)}};this.outstandingGets_.push(o),this.outstandingGetCount_++;let s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),r.promise}listen(n,r,i,o){this.initConnection_();let s=n._queryIdentifier,a=n._path.toString();this.log_("Listen called for "+a+" "+s),this.listens.has(a)||this.listens.set(a,new Map),Y(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Y(!this.listens.get(a).has(s),"listen() called twice for same path/queryId.");let c={onComplete:o,hashFn:r,query:n,tag:i};this.listens.get(a).set(s,c),this.connected_&&this.sendListen_(c)}sendGet_(n){let r=this.outstandingGets_[n];this.sendRequest("g",r.request,i=>{delete this.outstandingGets_[n],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),r.onComplete&&r.onComplete(i)})}sendListen_(n){let r=n.query,i=r._path.toString(),o=r._queryIdentifier;this.log_("Listen on "+i+" for "+o);let s={p:i},a="q";n.tag&&(s.q=r._queryObject,s.t=n.tag),s.h=n.hashFn(),this.sendRequest(a,s,c=>{let l=c.d,d=c.s;t.warnOnListenWarnings_(l,r),(this.listens.get(i)&&this.listens.get(i).get(o))===n&&(this.log_("listen response",c),d!=="ok"&&this.removeListen_(i,o),n.onComplete&&n.onComplete(d,l))})}static warnOnListenWarnings_(n,r){if(n&&typeof n=="object"&&zr(n,"w")){let i=$s(n,"w");if(Array.isArray(i)&&~i.indexOf("no_index")){let o='".indexOn": "'+r._queryParams.getIndex().toString()+'"',s=r._path.toString();Fn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${o} at ${s} to your security rules for better performance.`)}}}refreshAuthToken(n){this.authToken_=n,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(n)}reduceReconnectDelayIfAdminCredential_(n){(n&&n.length===40||NB(n))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=cj)}refreshAppCheckToken(n){this.appCheckToken_=n,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let n=this.authToken_,r=RB(n)?"auth":"gauth",i={cred:n};this.authOverride_===null?i.noauth=!0:typeof this.authOverride_=="object"&&(i.authvar=this.authOverride_),this.sendRequest(r,i,o=>{let s=o.s,a=o.d||"error";this.authToken_===n&&(s==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(s,a))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},n=>{let r=n.s,i=n.d||"error";r==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(r,i)})}unlisten(n,r){let i=n._path.toString(),o=n._queryIdentifier;this.log_("Unlisten called for "+i+" "+o),Y(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,o)&&this.connected_&&this.sendUnlisten_(i,o,n._queryObject,r)}sendUnlisten_(n,r,i,o){this.log_("Unlisten on "+n+" for "+r);let s={p:n},a="n";o&&(s.q=i,s.t=o),this.sendRequest(a,s)}onDisconnectPut(n,r,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",n,r,i):this.onDisconnectRequestQueue_.push({pathString:n,action:"o",data:r,onComplete:i})}onDisconnectMerge(n,r,i){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",n,r,i):this.onDisconnectRequestQueue_.push({pathString:n,action:"om",data:r,onComplete:i})}onDisconnectCancel(n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",n,null,r):this.onDisconnectRequestQueue_.push({pathString:n,action:"oc",data:null,onComplete:r})}sendOnDisconnect_(n,r,i,o){let s={p:r,d:i};this.log_("onDisconnect "+n,s),this.sendRequest(n,s,a=>{o&&setTimeout(()=>{o(a.s,a.d)},Math.floor(0))})}put(n,r,i,o){this.putInternal("p",n,r,i,o)}merge(n,r,i,o){this.putInternal("m",n,r,i,o)}putInternal(n,r,i,o,s){this.initConnection_();let a={p:r,d:i};s!==void 0&&(a.h=s),this.outstandingPuts_.push({action:n,request:a,onComplete:o}),this.outstandingPutCount_++;let c=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(c):this.log_("Buffering put: "+r)}sendPut_(n){let r=this.outstandingPuts_[n].action,i=this.outstandingPuts_[n].request,o=this.outstandingPuts_[n].onComplete;this.outstandingPuts_[n].queued=this.connected_,this.sendRequest(r,i,s=>{this.log_(r+" response",s),delete this.outstandingPuts_[n],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),o&&o(s.s,s.d)})}reportStats(n){if(this.connected_){let r={c:n};this.log_("reportStats",r),this.sendRequest("s",r,i=>{if(i.s!=="ok"){let s=i.d;this.log_("reportStats","Error sending stats: "+s)}})}}onDataMessage_(n){if("r"in n){this.log_("from server: "+Pt(n));let r=n.r,i=this.requestCBHash_[r];i&&(delete this.requestCBHash_[r],i(n.b))}else{if("error"in n)throw"A server-side error has occurred: "+n.error;"a"in n&&this.onDataPush_(n.a,n.b)}}onDataPush_(n,r){this.log_("handleServerMessage",n,r),n==="d"?this.onDataUpdate_(r.p,r.d,!1,r.t):n==="m"?this.onDataUpdate_(r.p,r.d,!0,r.t):n==="c"?this.onListenRevoked_(r.p,r.q):n==="ac"?this.onAuthRevoked_(r.s,r.d):n==="apc"?this.onAppCheckRevoked_(r.s,r.d):n==="sd"?this.onSecurityDebugPacket_(r):gw("Unrecognized action received from server: "+Pt(n)+`
|
|
151
151
|
Are you using the latest client?`)}onReady_(n,r){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(n),this.lastSessionId=r,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(n){Y(!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(n))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(n){n&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=jp,this.realtime_||this.scheduleConnect_(0)),this.visible_=n}onOnline_(n){n?(this.log_("Browser went online."),this.reconnectDelay_=jp,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_>oie&&(this.reconnectDelay_=jp),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let n=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_),r=Math.max(0,this.reconnectDelay_-n);r=Math.random()*r,this.log_("Trying to reconnect in "+r+"ms"),this.scheduleConnect_(r),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*iie)}this.onConnectStatus_(!1)}establishConnection_(){return y(this,null,function*(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let n=this.onDataMessage_.bind(this),r=this.onReady_.bind(this),i=this.onRealtimeDisconnect_.bind(this),o=this.id+":"+t.nextConnectionId_++,s=this.lastSessionId,a=!1,c=null,l=function(){c?c.close():(a=!0,i())},d=function(f){Y(c,"sendRequest call when we're not connected not allowed."),c.sendRequest(f)};this.realtime_={close:l,sendRequest:d};let h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[f,g]=yield Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);a?ln("getToken() completed but was canceled"):(ln("getToken() completed. Creating connection."),this.authToken_=f&&f.accessToken,this.appCheckToken_=g&&g.token,c=new vw(o,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,r,i,E=>{Fn(E+" ("+this.repoInfo_.toString()+")"),this.interrupt(sie)},s))}catch(f){this.log_("Failed to get token: "+f),a||(this.repoInfo_.nodeAdmin&&Fn(f),l())}}})}interrupt(n){ln("Interrupting connection for reason: "+n),this.interruptReasons_[n]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(n){ln("Resuming connection for reason: "+n),delete this.interruptReasons_[n],Tp(this.interruptReasons_)&&(this.reconnectDelay_=jp,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(n){let r=n-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:r})}cancelSentTransactions_(){for(let n=0;n<this.outstandingPuts_.length;n++){let r=this.outstandingPuts_[n];r&&"h"in r.request&&r.queued&&(r.onComplete&&r.onComplete("disconnect"),delete this.outstandingPuts_[n],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(n,r){let i;r?i=r.map(s=>db(s)).join("$"):i="default";let o=this.removeListen_(n,i);o&&o.onComplete&&o.onComplete("permission_denied")}removeListen_(n,r){let i=new He(n).toString(),o;if(this.listens.has(i)){let s=this.listens.get(i);o=s.get(r),s.delete(r),s.size===0&&this.listens.delete(i)}else o=void 0;return o}onAuthRevoked_(n,r){ln("Auth token revoked: "+n+"/"+r),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(n==="invalid_token"||n==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=lj&&(this.reconnectDelay_=cj,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(n,r){ln("App check token revoked: "+n+"/"+r),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(n==="invalid_token"||n==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=lj&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(n){this.securityDebugCallback_?this.securityDebugCallback_(n):"msg"in n&&console.log("FIREBASE: "+n.msg.replace(`
|
|
152
152
|
`,`
|
|
153
|
-
FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(let n of this.listens.values())for(let r of n.values())this.sendListen_(r);for(let n=0;n<this.outstandingPuts_.length;n++)this.outstandingPuts_[n]&&this.sendPut_(n);for(;this.onDisconnectRequestQueue_.length;){let n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let n=0;n<this.outstandingGets_.length;n++)this.outstandingGets_[n]&&this.sendGet_(n)}sendConnectStats_(){let n={},r="js";co()&&(this.repoInfo_.nodeAdmin?r="admin_node":r="node"),n["sdk."+r+"."+ub.replace(/\./g,"-")]=1,_p()?n["framework.cordova"]=1:qT()&&(n["framework.reactnative"]=1),this.reportStats(n)}shouldReconnect_(){let n=Oy.getInstance().currentlyOnline();return Tp(this.interruptReasons_)&&n}}t.nextPersistentConnectionId_=0,t.nextConnectionId_=0;return t})(),Le=class t{constructor(e,n){this.name=e,this.node=n}static Wrap(e,n){return new t(e,n)}};var Rd=class{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,n){let r=new Le(ul,e),i=new Le(ul,n);return this.compare(r,i)!==0}minPost(){return Le.MIN}};var Ay,My=class extends Rd{static get __EMPTY_NODE(){return Ay}static set __EMPTY_NODE(e){Ay=e}compare(e,n){return ml(e.name,n.name)}isDefinedOn(e){throw zc("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,n){return!1}minPost(){return Le.MIN}maxPost(){return new Le(sa,Ay)}makePost(e,n){return Y(typeof e=="string","KeyIndex indexValue must always be a string."),new Le(e,Ay)}toString(){return".key"}},ll=new My;var Cd=class{constructor(e,n,r,i,o=null){this.isReverse_=i,this.resultGenerator_=o,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(e=e,s=n?r(e.key,n):1,i&&(s*=-1),s<0)this.isReverse_?e=e.left:e=e.right;else if(s===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(),n;if(this.resultGenerator_?n=this.resultGenerator_(e.key,e.value):n={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 n}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}},Ii=(()=>{class t{constructor(n,r,i,o,s){this.key=n,this.value=r,this.color=i??t.RED,this.left=o??Xr.EMPTY_NODE,this.right=s??Xr.EMPTY_NODE}copy(n,r,i,o,s){return new t(n??this.key,r??this.value,i??this.color,o??this.left,s??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(n){return this.left.inorderTraversal(n)||!!n(this.key,this.value)||this.right.inorderTraversal(n)}reverseTraversal(n){return this.right.reverseTraversal(n)||n(this.key,this.value)||this.left.reverseTraversal(n)}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(n,r,i){let o=this,s=i(n,o.key);return s<0?o=o.copy(null,null,null,o.left.insert(n,r,i),null):s===0?o=o.copy(null,r,null,null,null):o=o.copy(null,null,null,null,o.right.insert(n,r,i)),o.fixUp_()}removeMin_(){if(this.left.isEmpty())return Xr.EMPTY_NODE;let n=this;return!n.left.isRed_()&&!n.left.left.isRed_()&&(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.removeMin_(),null),n.fixUp_()}remove(n,r){let i,o;if(i=this,r(n,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(n,r),null);else{if(i.left.isRed_()&&(i=i.rotateRight_()),!i.right.isEmpty()&&!i.right.isRed_()&&!i.right.left.isRed_()&&(i=i.moveRedRight_()),r(n,i.key)===0){if(i.right.isEmpty())return Xr.EMPTY_NODE;o=i.right.min_(),i=i.copy(o.key,o.value,null,null,i.right.removeMin_())}i=i.copy(null,null,null,null,i.right.remove(n,r))}return i.fixUp_()}isRed_(){return this.color}fixUp_(){let n=this;return n.right.isRed_()&&!n.left.isRed_()&&(n=n.rotateLeft_()),n.left.isRed_()&&n.left.left.isRed_()&&(n=n.rotateRight_()),n.left.isRed_()&&n.right.isRed_()&&(n=n.colorFlip_()),n}moveRedLeft_(){let n=this.colorFlip_();return n.right.left.isRed_()&&(n=n.copy(null,null,null,null,n.right.rotateRight_()),n=n.rotateLeft_(),n=n.colorFlip_()),n}moveRedRight_(){let n=this.colorFlip_();return n.left.left.isRed_()&&(n=n.rotateRight_(),n=n.colorFlip_()),n}rotateLeft_(){let n=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,n,null)}rotateRight_(){let n=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,n)}colorFlip_(){let n=this.left.copy(null,null,!this.left.color,null,null),r=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,n,r)}checkMaxDepth_(){let n=this.check_();return Math.pow(2,n)<=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");let n=this.left.check_();if(n!==this.right.check_())throw new Error("Black depths differ");return n+(this.isRed_()?0:1)}}return t.RED=!0,t.BLACK=!1,t})(),Cw=class{copy(e,n,r,i,o){return this}insert(e,n,r){return new Ii(e,n,null)}remove(e,n){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}},Xr=class t{constructor(e,n=t.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new t(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,Ii.BLACK,null,null))}remove(e){return new t(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ii.BLACK,null,null))}get(e){let n,r=this.root_;for(;!r.isEmpty();){if(n=this.comparator_(e,r.key),n===0)return r.value;n<0?r=r.left:n>0&&(r=r.right)}return null}getPredecessorKey(e){let n,r=this.root_,i=null;for(;!r.isEmpty();)if(n=this.comparator_(e,r.key),n===0){if(r.left.isEmpty())return i?i.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}else n<0?r=r.left:n>0&&(i=r,r=r.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 Cd(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new Cd(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new Cd(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new Cd(this.root_,null,this.comparator_,!0,e)}};Xr.EMPTY_NODE=new Cw;function aie(t,e){return ml(t.name,e.name)}function mb(t,e){return ml(t,e)}var Dw;function cie(t){Dw=t}var Qj=function(t){return typeof t=="number"?"number:"+Mj(t):"string:"+t},Jj=function(t){if(t.isLeafNode()){let e=t.val();Y(typeof e=="string"||typeof e=="number"||typeof e=="object"&&zr(e,".sv"),"Priority must be a string or number.")}else Y(t===Dw||t.isEmpty(),"priority of unexpected type.");Y(t===Dw||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};var uj,Nd=(()=>{class t{static set __childrenNodeConstructor(n){uj=n}static get __childrenNodeConstructor(){return uj}constructor(n,r=t.__childrenNodeConstructor.EMPTY_NODE){this.value_=n,this.priorityNode_=r,this.lazyHash_=null,Y(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),Jj(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(n){return new t(this.value_,n)}getImmediateChild(n){return n===".priority"?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE}getChild(n){return Oe(n)?this:be(n)===".priority"?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(n,r){return null}updateImmediateChild(n,r){return n===".priority"?this.updatePriority(r):r.isEmpty()&&n!==".priority"?this:t.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(n,r).updatePriority(this.priorityNode_)}updateChild(n,r){let i=be(n);return i===null?r:r.isEmpty()&&i!==".priority"?this:(Y(i!==".priority"||aa(n)===1,".priority must be the last token in a path"),this.updateImmediateChild(i,t.__childrenNodeConstructor.EMPTY_NODE.updateChild(ct(n),r)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(n,r){return!1}val(n){return n&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let n="";this.priorityNode_.isEmpty()||(n+="priority:"+Qj(this.priorityNode_.val())+":");let r=typeof this.value_;n+=r+":",r==="number"?n+=Mj(this.value_):n+=this.value_,this.lazyHash_=bj(n)}return this.lazyHash_}getValue(){return this.value_}compareTo(n){return n===t.__childrenNodeConstructor.EMPTY_NODE?1:n instanceof t.__childrenNodeConstructor?-1:(Y(n.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(n))}compareToLeafNode_(n){let r=typeof n.value_,i=typeof this.value_,o=t.VALUE_TYPE_ORDER.indexOf(r),s=t.VALUE_TYPE_ORDER.indexOf(i);return Y(o>=0,"Unknown leaf type: "+r),Y(s>=0,"Unknown leaf type: "+i),o===s?i==="object"?0:this.value_<n.value_?-1:this.value_===n.value_?0:1:s-o}withIndex(){return this}isIndexed(){return!0}equals(n){if(n===this)return!0;if(n.isLeafNode()){let r=n;return this.value_===r.value_&&this.priorityNode_.equals(r.priorityNode_)}else return!1}}t.VALUE_TYPE_ORDER=["object","boolean","number","string"];return t})(),Zj,eH;function lie(t){Zj=t}function uie(t){eH=t}var Rw=class extends Rd{compare(e,n){let r=e.node.getPriority(),i=n.node.getPriority(),o=r.compareTo(i);return o===0?ml(e.name,n.name):o}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,n){return!e.getPriority().equals(n.getPriority())}minPost(){return Le.MIN}maxPost(){return new Le(sa,new Nd("[PRIORITY-POST]",eH))}makePost(e,n){let r=Zj(e);return new Le(n,new Nd("[PRIORITY-POST]",r))}toString(){return".priority"}},ht=new Rw;var die=Math.log(2),Nw=class{constructor(e){let n=o=>parseInt(Math.log(o)/die,10),r=o=>parseInt(Array(o+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;let i=r(this.count);this.bits_=e+1&i}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}},Ly=function(t,e,n,r){t.sort(e);let i=function(c,l){let d=l-c,h,f;if(d===0)return null;if(d===1)return h=t[c],f=n?n(h):h,new Ii(f,h.node,Ii.BLACK,null,null);{let g=parseInt(d/2,10)+c,E=i(c,g),I=i(g+1,l);return h=t[g],f=n?n(h):h,new Ii(f,h.node,Ii.BLACK,E,I)}},o=function(c){let l=null,d=null,h=t.length,f=function(E,I){let S=h-E,L=h;h-=E;let j=i(S+1,L),K=t[S],te=n?n(K):K;g(new Ii(te,K.node,I,null,j))},g=function(E){l?(l.left=E,l=E):(d=E,l=E)};for(let E=0;E<c.count;++E){let I=c.nextBitIsOne(),S=Math.pow(2,c.count-(E+1));I?f(S,Ii.BLACK):(f(S,Ii.BLACK),f(S,Ii.RED))}return d},s=new Nw(t.length),a=o(s);return new Xr(r||e,a)};var cw,Sd={},wd=class t{static get Default(){return Y(Sd&&ht,"ChildrenNode.ts has not been loaded"),cw=cw||new t({".priority":Sd},{".priority":ht}),cw}constructor(e,n){this.indexes_=e,this.indexSet_=n}get(e){let n=$s(this.indexes_,e);if(!n)throw new Error("No index defined for "+e);return n instanceof Xr?n:null}hasIndex(e){return zr(this.indexSet_,e.toString())}addIndex(e,n){Y(e!==ll,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let r=[],i=!1,o=n.getIterator(Le.Wrap),s=o.getNext();for(;s;)i=i||e.isDefinedOn(s.node),r.push(s),s=o.getNext();let a;i?a=Ly(r,e.getCompare()):a=Sd;let c=e.toString(),l=Object.assign({},this.indexSet_);l[c]=e;let d=Object.assign({},this.indexes_);return d[c]=a,new t(d,l)}addToIndexes(e,n){let r=yp(this.indexes_,(i,o)=>{let s=$s(this.indexSet_,o);if(Y(s,"Missing index implementation for "+o),i===Sd)if(s.isDefinedOn(e.node)){let a=[],c=n.getIterator(Le.Wrap),l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),Ly(a,s.getCompare())}else return Sd;else{let a=n.get(e.name),c=i;return a&&(c=c.remove(new Le(e.name,a))),c.insert(e,e.node)}});return new t(r,this.indexSet_)}removeFromIndexes(e,n){let r=yp(this.indexes_,i=>{if(i===Sd)return i;{let o=n.get(e.name);return o?i.remove(new Le(e.name,o)):i}});return new t(r,this.indexSet_)}};var Hp,ve=(()=>{class t{static get EMPTY_NODE(){return Hp||(Hp=new t(new Xr(mb),null,wd.Default))}constructor(n,r,i){this.children_=n,this.priorityNode_=r,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&Jj(this.priorityNode_),this.children_.isEmpty()&&Y(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Hp}updatePriority(n){return this.children_.isEmpty()?this:new t(this.children_,n,this.indexMap_)}getImmediateChild(n){if(n===".priority")return this.getPriority();{let r=this.children_.get(n);return r===null?Hp:r}}getChild(n){let r=be(n);return r===null?this:this.getImmediateChild(r).getChild(ct(n))}hasChild(n){return this.children_.get(n)!==null}updateImmediateChild(n,r){if(Y(r,"We should always be passing snapshot nodes"),n===".priority")return this.updatePriority(r);{let i=new Le(n,r),o,s;r.isEmpty()?(o=this.children_.remove(n),s=this.indexMap_.removeFromIndexes(i,this.children_)):(o=this.children_.insert(n,r),s=this.indexMap_.addToIndexes(i,this.children_));let a=o.isEmpty()?Hp:this.priorityNode_;return new t(o,a,s)}}updateChild(n,r){let i=be(n);if(i===null)return r;{Y(be(n)!==".priority"||aa(n)===1,".priority must be the last token in a path");let o=this.getImmediateChild(i).updateChild(ct(n),r);return this.updateImmediateChild(i,o)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;let r={},i=0,o=0,s=!0;if(this.forEachChild(ht,(a,c)=>{r[a]=c.val(n),i++,s&&t.INTEGER_REGEXP_.test(a)?o=Math.max(o,Number(a)):s=!1}),!n&&s&&o<2*i){let a=[];for(let c in r)a[c]=r[c];return a}else return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(this.lazyHash_===null){let n="";this.getPriority().isEmpty()||(n+="priority:"+Qj(this.getPriority().val())+":"),this.forEachChild(ht,(r,i)=>{let o=i.hash();o!==""&&(n+=":"+r+":"+o)}),this.lazyHash_=n===""?"":bj(n)}return this.lazyHash_}getPredecessorChildName(n,r,i){let o=this.resolveIndex_(i);if(o){let s=o.getPredecessorKey(new Le(n,r));return s?s.name:null}else return this.children_.getPredecessorKey(n)}getFirstChildName(n){let r=this.resolveIndex_(n);if(r){let i=r.minKey();return i&&i.name}else return this.children_.minKey()}getFirstChild(n){let r=this.getFirstChildName(n);return r?new Le(r,this.children_.get(r)):null}getLastChildName(n){let r=this.resolveIndex_(n);if(r){let i=r.maxKey();return i&&i.name}else return this.children_.maxKey()}getLastChild(n){let r=this.getLastChildName(n);return r?new Le(r,this.children_.get(r)):null}forEachChild(n,r){let i=this.resolveIndex_(n);return i?i.inorderTraversal(o=>r(o.name,o.node)):this.children_.inorderTraversal(r)}getIterator(n){return this.getIteratorFrom(n.minPost(),n)}getIteratorFrom(n,r){let i=this.resolveIndex_(r);if(i)return i.getIteratorFrom(n,o=>o);{let o=this.children_.getIteratorFrom(n.name,Le.Wrap),s=o.peek();for(;s!=null&&r.compare(s,n)<0;)o.getNext(),s=o.peek();return o}}getReverseIterator(n){return this.getReverseIteratorFrom(n.maxPost(),n)}getReverseIteratorFrom(n,r){let i=this.resolveIndex_(r);if(i)return i.getReverseIteratorFrom(n,o=>o);{let o=this.children_.getReverseIteratorFrom(n.name,Le.Wrap),s=o.peek();for(;s!=null&&r.compare(s,n)>0;)o.getNext(),s=o.peek();return o}}compareTo(n){return this.isEmpty()?n.isEmpty()?0:-1:n.isLeafNode()||n.isEmpty()?1:n===ug?-1:0}withIndex(n){if(n===ll||this.indexMap_.hasIndex(n))return this;{let r=this.indexMap_.addIndex(n,this.children_);return new t(this.children_,this.priorityNode_,r)}}isIndexed(n){return n===ll||this.indexMap_.hasIndex(n)}equals(n){if(n===this)return!0;if(n.isLeafNode())return!1;{let r=n;if(this.getPriority().equals(r.getPriority()))if(this.children_.count()===r.children_.count()){let i=this.getIterator(ht),o=r.getIterator(ht),s=i.getNext(),a=o.getNext();for(;s&&a;){if(s.name!==a.name||!s.node.equals(a.node))return!1;s=i.getNext(),a=o.getNext()}return s===null&&a===null}else return!1;else return!1}}resolveIndex_(n){return n===ll?null:this.indexMap_.get(n.toString())}}return t.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,t})(),ww=class extends ve{constructor(){super(new Xr(mb),ve.EMPTY_NODE,wd.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ve.EMPTY_NODE}isEmpty(){return!1}},ug=new ww;Object.defineProperties(Le,{MIN:{value:new Le(ul,ve.EMPTY_NODE)},MAX:{value:new Le(sa,ug)}});My.__EMPTY_NODE=ve.EMPTY_NODE;Nd.__childrenNodeConstructor=ve;cie(ug);uie(ug);var hie=!0;function St(t,e=null){if(t===null)return ve.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),Y(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){let n=t;return new Nd(n,St(e))}if(!(t instanceof Array)&&hie){let n=[],r=!1;if(un(t,(s,a)=>{if(s.substring(0,1)!=="."){let c=St(a);c.isEmpty()||(r=r||!c.getPriority().isEmpty(),n.push(new Le(s,c)))}}),n.length===0)return ve.EMPTY_NODE;let o=Ly(n,aie,s=>s.name,mb);if(r){let s=Ly(n,ht.getCompare());return new ve(o,St(e),new wd({".priority":s},{".priority":ht}))}else return new ve(o,St(e),wd.Default)}else{let n=ve.EMPTY_NODE;return un(t,(r,i)=>{if(zr(t,r)&&r.substring(0,1)!=="."){let o=St(i);(o.isLeafNode()||!o.isEmpty())&&(n=n.updateImmediateChild(r,o))}}),n.updatePriority(St(e))}}lie(St);var Qp=class extends Rd{constructor(e){super(),this.indexPath_=e,Y(!Oe(e)&&be(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,n){let r=this.extractChild(e.node),i=this.extractChild(n.node),o=r.compareTo(i);return o===0?ml(e.name,n.name):o}makePost(e,n){let r=St(e),i=ve.EMPTY_NODE.updateChild(this.indexPath_,r);return new Le(n,i)}maxPost(){let e=ve.EMPTY_NODE.updateChild(this.indexPath_,ug);return new Le(sa,e)}toString(){return Xp(this.indexPath_,0).join("/")}};var bw=class extends Rd{compare(e,n){let r=e.node.compareTo(n.node);return r===0?ml(e.name,n.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return Le.MIN}maxPost(){return Le.MAX}makePost(e,n){let r=St(e);return new Le(n,r)}toString(){return".value"}},tH=new bw;function nH(t){return{type:"value",snapshotNode:t}}function bd(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function Jp(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function Zp(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function fie(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}var eg=class{constructor(e){this.index_=e}updateChild(e,n,r,i,o,s){Y(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let a=e.getImmediateChild(n);return a.getChild(i).equals(r.getChild(i))&&a.isEmpty()===r.isEmpty()||(s!=null&&(r.isEmpty()?e.hasChild(n)?s.trackChildChange(Jp(n,a)):Y(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(bd(n,r)):s.trackChildChange(Zp(n,r,a))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(n,r).withIndex(this.index_)}updateFullNode(e,n,r){return r!=null&&(e.isLeafNode()||e.forEachChild(ht,(i,o)=>{n.hasChild(i)||r.trackChildChange(Jp(i,o))}),n.isLeafNode()||n.forEachChild(ht,(i,o)=>{if(e.hasChild(i)){let s=e.getImmediateChild(i);s.equals(o)||r.trackChildChange(Zp(i,o,s))}else r.trackChildChange(bd(i,o))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?ve.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}};var Py=class t{constructor(e){this.indexedFilter_=new eg(e.getIndex()),this.index_=e.getIndex(),this.startPost_=t.getStartPost_(e),this.endPost_=t.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&r}updateChild(e,n,r,i,o,s){return this.matches(new Le(n,r))||(r=ve.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,r,i,o,s)}updateFullNode(e,n,r){n.isLeafNode()&&(n=ve.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(ve.EMPTY_NODE);let o=this;return n.forEachChild(ht,(s,a)=>{o.matches(new Le(s,a))||(i=i.updateImmediateChild(s,ve.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){let n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){let n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}};var Ow=class{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{let r=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?r<=0:r<0},this.withinEndPost=n=>{let r=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?r<=0:r<0},this.rangedFilter_=new Py(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,r,i,o,s){return this.rangedFilter_.matches(new Le(n,r))||(r=ve.EMPTY_NODE),e.getImmediateChild(n).equals(r)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,n,r,i,o,s):this.fullLimitUpdateChild_(e,n,r,o,s)}updateFullNode(e,n,r){let i;if(n.isLeafNode()||n.isEmpty())i=ve.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<n.numChildren()&&n.isIndexed(this.index_)){i=ve.EMPTY_NODE.withIndex(this.index_);let o;this.reverse_?o=n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):o=n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let s=0;for(;o.hasNext()&&s<this.limit_;){let a=o.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))i=i.updateImmediateChild(a.name,a.node),s++;else break;else continue}}else{i=n.withIndex(this.index_),i=i.updatePriority(ve.EMPTY_NODE);let o;this.reverse_?o=i.getReverseIterator(this.index_):o=i.getIterator(this.index_);let s=0;for(;o.hasNext();){let a=o.getNext();s<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?s++:i=i.updateImmediateChild(a.name,ve.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,n,r,i,o){let s;if(this.reverse_){let h=this.index_.getCompare();s=(f,g)=>h(g,f)}else s=this.index_.getCompare();let a=e;Y(a.numChildren()===this.limit_,"");let c=new Le(n,r),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),d=this.rangedFilter_.matches(c);if(a.hasChild(n)){let h=a.getImmediateChild(n),f=i.getChildAfterChild(this.index_,l,this.reverse_);for(;f!=null&&(f.name===n||a.hasChild(f.name));)f=i.getChildAfterChild(this.index_,f,this.reverse_);let g=f==null?1:s(f,c);if(d&&!r.isEmpty()&&g>=0)return o?.trackChildChange(Zp(n,r,h)),a.updateImmediateChild(n,r);{o?.trackChildChange(Jp(n,h));let I=a.updateImmediateChild(n,ve.EMPTY_NODE);return f!=null&&this.rangedFilter_.matches(f)?(o?.trackChildChange(bd(f.name,f.node)),I.updateImmediateChild(f.name,f.node)):I}}else return r.isEmpty()?e:d&&s(l,c)>=0?(o!=null&&(o.trackChildChange(Jp(l.name,l.node)),o.trackChildChange(bd(n,r))),a.updateImmediateChild(n,r).updateImmediateChild(l.name,ve.EMPTY_NODE)):e}};var Mw=class t{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_=ht}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return Y(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Y(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:ul}hasEnd(){return this.endSet_}getIndexEndValue(){return Y(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Y(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:sa}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return Y(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_===ht}copy(){let e=new t;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 pie(t){return t.loadsAllData()?new eg(t.getIndex()):t.hasLimit()?new Ow(t):new Py(t)}function gie(t,e){let n=t.copy();return n.limitSet_=!0,n.limit_=e,n.viewFrom_="r",n}function mie(t,e,n){let r=t.copy();return r.startSet_=!0,e===void 0&&(e=null),r.indexStartValue_=e,n!=null?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function Eie(t,e,n){let r=t.copy();return r.endSet_=!0,e===void 0&&(e=null),r.indexEndValue_=e,n!==void 0?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function _ie(t,e){let n=t.copy();return n.index_=e,n}function dj(t){let e={};if(t.isDefault())return e;let n;if(t.index_===ht?n="$priority":t.index_===tH?n="$value":t.index_===ll?n="$key":(Y(t.index_ instanceof Qp,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Pt(n),t.startSet_){let r=t.startAfterSet_?"startAfter":"startAt";e[r]=Pt(t.indexStartValue_),t.startNameSet_&&(e[r]+=","+Pt(t.indexStartName_))}if(t.endSet_){let r=t.endBeforeSet_?"endBefore":"endAt";e[r]=Pt(t.indexEndValue_),t.endNameSet_&&(e[r]+=","+Pt(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function hj(t){let e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==ht&&(e.i=t.index_.toString()),e}var Lw=class t extends wy{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(Y(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,n,r,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=r,this.appCheckTokenProvider_=i,this.log_=lg("p:rest:"),this.listens_={}}listen(e,n,r,i){let o=e._path.toString();this.log_("Listen called for "+o+" "+e._queryIdentifier);let s=t.getListenId_(e,r),a={};this.listens_[s]=a;let c=dj(e._queryParams);this.restRequest_(o+".json",c,(l,d)=>{let h=d;if(l===404&&(h=null,l=null),l===null&&this.onDataUpdate_(o,h,!1,r),$s(this.listens_,s)===a){let f;l?l===401?f="permission_denied":f="rest_error:"+l:f="ok",i(f,null)}})}unlisten(e,n){let r=t.getListenId_(e,n);delete this.listens_[r]}get(e){let n=dj(e._queryParams),r=e._path.toString(),i=new an;return this.restRequest_(r+".json",n,(o,s)=>{let a=s;o===404&&(a=null,o=null),o===null?(this.onDataUpdate_(r,a,!1,null),i.resolve(a)):i.reject(new Error(a))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},r){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,o])=>{i&&i.accessToken&&(n.auth=i.accessToken),o&&o.token&&(n.ac=o.token);let s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+Ip(n);this.log_("Sending REST request for "+s);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(r&&a.readyState===4){this.log_("REST Response for "+s+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=hd(a.responseText)}catch{Fn("Failed to parse JSON response for "+s+": "+a.responseText)}r(null,c)}else a.status!==401&&a.status!==404&&Fn("Got unsuccessful REST response for "+s+" Status: "+a.status),r(a.status);r=null}},a.open("GET",s,!0),a.send()})}};var Pw=class{constructor(){this.rootNode_=ve.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}};function xy(){return{value:null,children:new Map}}function kd(t,e,n){if(Oe(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{let r=be(e);t.children.has(r)||t.children.set(r,xy());let i=t.children.get(r);e=ct(e),kd(i,e,n)}}function xw(t,e){if(Oe(e))return t.value=null,t.children.clear(),!0;if(t.value!==null){if(t.value.isLeafNode())return!1;{let n=t.value;return t.value=null,n.forEachChild(ht,(r,i)=>{kd(t,new He(r),i)}),xw(t,e)}}else if(t.children.size>0){let n=be(e);return e=ct(e),t.children.has(n)&&xw(t.children.get(n),e)&&t.children.delete(n),t.children.size===0}else return!0}function kw(t,e,n){t.value!==null?n(e,t.value):Tie(t,(r,i)=>{let o=new He(e.toString()+"/"+r);kw(i,o,n)})}function Tie(t,e){t.children.forEach((n,r)=>{e(r,n)})}var Fw=class{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),n=Object.assign({},e);return this.last_&&un(this.last_,(r,i)=>{n[r]=n[r]-i}),this.last_=e,n}};var fj=10*1e3,yie=30*1e3,Iie=300*1e3,Uw=class{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new Fw(e);let r=fj+(yie-fj)*Math.random();Wp(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){let e=this.statsListener_.get(),n={},r=!1;un(e,(i,o)=>{o>0&&zr(this.statsToReport_,i)&&(n[i]=o,r=!0)}),r&&this.server_.reportStats(n),Wp(this.reportStats_.bind(this),Math.floor(Math.random()*2*Iie))}};var po=(function(t){return t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE",t})(po||{});function Eb(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function _b(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Tb(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}var Vw=class t{constructor(e,n,r){this.path=e,this.affectedTree=n,this.revert=r,this.type=po.ACK_USER_WRITE,this.source=Eb()}operationForChild(e){if(Oe(this.path)){if(this.affectedTree.value!=null)return Y(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let n=this.affectedTree.subtree(new He(e));return new t(je(),n,this.revert)}}else return Y(be(this.path)===e,"operationForChild called for unrelated child."),new t(ct(this.path),this.affectedTree,this.revert)}};var ky=class t{constructor(e,n){this.source=e,this.path=n,this.type=po.LISTEN_COMPLETE}operationForChild(e){return Oe(this.path)?new t(this.source,je()):new t(this.source,ct(this.path))}};var Od=class t{constructor(e,n,r){this.source=e,this.path=n,this.snap=r,this.type=po.OVERWRITE}operationForChild(e){return Oe(this.path)?new t(this.source,je(),this.snap.getImmediateChild(e)):new t(this.source,ct(this.path),this.snap)}};var tg=class t{constructor(e,n,r){this.source=e,this.path=n,this.children=r,this.type=po.MERGE}operationForChild(e){if(Oe(this.path)){let n=this.children.subtree(new He(e));return n.isEmpty()?null:n.value?new Od(this.source,je(),n.value):new t(this.source,je(),n)}else return Y(be(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new t(this.source,ct(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}};var go=class{constructor(e,n,r){this.node_=e,this.fullyInitialized_=n,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Oe(e))return this.isFullyInitialized()&&!this.filtered_;let n=be(e);return this.isCompleteForChild(n)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}};var Bw=class{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}};function vie(t,e,n,r){let i=[],o=[];return e.forEach(s=>{s.type==="child_changed"&&t.index_.indexedValueChanged(s.oldSnap,s.snapshotNode)&&o.push(fie(s.childName,s.snapshotNode))}),$p(t,i,"child_removed",e,r,n),$p(t,i,"child_added",e,r,n),$p(t,i,"child_moved",o,r,n),$p(t,i,"child_changed",e,r,n),$p(t,i,"value",e,r,n),i}function $p(t,e,n,r,i,o){let s=r.filter(a=>a.type===n);s.sort((a,c)=>Aie(t,a,c)),s.forEach(a=>{let c=Sie(t,a,o);i.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,t.query_))})})}function Sie(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function Aie(t,e,n){if(e.childName==null||n.childName==null)throw zc("Should only compare child_ events.");let r=new Le(e.childName,e.snapshotNode),i=new Le(n.childName,n.snapshotNode);return t.index_.compare(r,i)}function Qy(t,e){return{eventCache:t,serverCache:e}}function qp(t,e,n,r){return Qy(new go(e,n,r),t.serverCache)}function rH(t,e,n,r){return Qy(t.eventCache,new go(e,n,r))}function Fy(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function dl(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}var lw,Cie=()=>(lw||(lw=new Xr(Sre)),lw),Yn=class t{static fromObject(e){let n=new t(null);return un(e,(r,i)=>{n=n.set(new He(r),i)}),n}constructor(e,n=Cie()){this.value=e,this.children=n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:je(),value:this.value};if(Oe(e))return null;{let r=be(e),i=this.children.get(r);if(i!==null){let o=i.findRootMostMatchingPathAndValue(ct(e),n);return o!=null?{path:At(new He(r),o.path),value:o.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(Oe(e))return this;{let n=be(e),r=this.children.get(n);return r!==null?r.subtree(ct(e)):new t(null)}}set(e,n){if(Oe(e))return new t(n,this.children);{let r=be(e),o=(this.children.get(r)||new t(null)).set(ct(e),n),s=this.children.insert(r,o);return new t(this.value,s)}}remove(e){if(Oe(e))return this.children.isEmpty()?new t(null):new t(null,this.children);{let n=be(e),r=this.children.get(n);if(r){let i=r.remove(ct(e)),o;return i.isEmpty()?o=this.children.remove(n):o=this.children.insert(n,i),this.value===null&&o.isEmpty()?new t(null):new t(this.value,o)}else return this}}get(e){if(Oe(e))return this.value;{let n=be(e),r=this.children.get(n);return r?r.get(ct(e)):null}}setTree(e,n){if(Oe(e))return n;{let r=be(e),o=(this.children.get(r)||new t(null)).setTree(ct(e),n),s;return o.isEmpty()?s=this.children.remove(r):s=this.children.insert(r,o),new t(this.value,s)}}fold(e){return this.fold_(je(),e)}fold_(e,n){let r={};return this.children.inorderTraversal((i,o)=>{r[i]=o.fold_(At(e,i),n)}),n(e,this.value,r)}findOnPath(e,n){return this.findOnPath_(e,je(),n)}findOnPath_(e,n,r){let i=this.value?r(n,this.value):!1;if(i)return i;if(Oe(e))return null;{let o=be(e),s=this.children.get(o);return s?s.findOnPath_(ct(e),At(n,o),r):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,je(),n)}foreachOnPath_(e,n,r){if(Oe(e))return this;{this.value&&r(n,this.value);let i=be(e),o=this.children.get(i);return o?o.foreachOnPath_(ct(e),At(n,i),r):new t(null)}}foreach(e){this.foreach_(je(),e)}foreach_(e,n){this.children.inorderTraversal((r,i)=>{i.foreach_(At(e,r),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,r)=>{r.value&&e(n,r.value)})}};var vi=class t{constructor(e){this.writeTree_=e}static empty(){return new t(new Yn(null))}};function Kp(t,e,n){if(Oe(e))return new vi(new Yn(n));{let r=t.writeTree_.findRootMostValueAndPath(e);if(r!=null){let i=r.path,o=r.value,s=Kn(i,e);return o=o.updateChild(s,n),new vi(t.writeTree_.set(i,o))}else{let i=new Yn(n),o=t.writeTree_.setTree(e,i);return new vi(o)}}}function Gw(t,e,n){let r=t;return un(n,(i,o)=>{r=Kp(r,At(e,i),o)}),r}function pj(t,e){if(Oe(e))return vi.empty();{let n=t.writeTree_.setTree(e,new Yn(null));return new vi(n)}}function jw(t,e){return El(t,e)!=null}function El(t,e){let n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(Kn(n.path,e)):null}function gj(t){let e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(ht,(r,i)=>{e.push(new Le(r,i))}):t.writeTree_.children.inorderTraversal((r,i)=>{i.value!=null&&e.push(new Le(r,i.value))}),e}function ia(t,e){if(Oe(e))return t;{let n=El(t,e);return n!=null?new vi(new Yn(n)):new vi(t.writeTree_.subtree(e))}}function Hw(t){return t.writeTree_.isEmpty()}function Md(t,e){return iH(je(),t.writeTree_,e)}function iH(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let r=null;return e.children.inorderTraversal((i,o)=>{i===".priority"?(Y(o.value!==null,"Priority writes must always be leaf nodes"),r=o.value):n=iH(At(t,i),o,n)}),!n.getChild(t).isEmpty()&&r!==null&&(n=n.updateChild(At(t,".priority"),r)),n}}function Jy(t,e){return cH(e,t)}function Die(t,e,n,r,i){Y(r>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:r,visible:i}),i&&(t.visibleWrites=Kp(t.visibleWrites,e,n)),t.lastWriteId=r}function Rie(t,e,n,r){Y(r>t.lastWriteId,"Stacking an older merge on top of newer ones"),t.allWrites.push({path:e,children:n,writeId:r,visible:!0}),t.visibleWrites=Gw(t.visibleWrites,e,n),t.lastWriteId=r}function Nie(t,e){for(let n=0;n<t.allWrites.length;n++){let r=t.allWrites[n];if(r.writeId===e)return r}return null}function wie(t,e){let n=t.allWrites.findIndex(a=>a.writeId===e);Y(n>=0,"removeWrite called with nonexistent writeId.");let r=t.allWrites[n];t.allWrites.splice(n,1);let i=r.visible,o=!1,s=t.allWrites.length-1;for(;i&&s>=0;){let a=t.allWrites[s];a.visible&&(s>=n&&bie(a,r.path)?i=!1:Yr(r.path,a.path)&&(o=!0)),s--}if(i){if(o)return Oie(t),!0;if(r.snap)t.visibleWrites=pj(t.visibleWrites,r.path);else{let a=r.children;un(a,c=>{t.visibleWrites=pj(t.visibleWrites,At(r.path,c))})}return!0}else return!1}function bie(t,e){if(t.snap)return Yr(t.path,e);for(let n in t.children)if(t.children.hasOwnProperty(n)&&Yr(At(t.path,n),e))return!0;return!1}function Oie(t){t.visibleWrites=oH(t.allWrites,Mie,je()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function Mie(t){return t.visible}function oH(t,e,n){let r=vi.empty();for(let i=0;i<t.length;++i){let o=t[i];if(e(o)){let s=o.path,a;if(o.snap)Yr(n,s)?(a=Kn(n,s),r=Kp(r,a,o.snap)):Yr(s,n)&&(a=Kn(s,n),r=Kp(r,je(),o.snap.getChild(a)));else if(o.children){if(Yr(n,s))a=Kn(n,s),r=Gw(r,a,o.children);else if(Yr(s,n))if(a=Kn(s,n),Oe(a))r=Gw(r,je(),o.children);else{let c=$s(o.children,be(a));if(c){let l=c.getChild(ct(a));r=Kp(r,je(),l)}}}else throw zc("WriteRecord should have .snap or .children")}}return r}function sH(t,e,n,r,i){if(!r&&!i){let o=El(t.visibleWrites,e);if(o!=null)return o;{let s=ia(t.visibleWrites,e);if(Hw(s))return n;if(n==null&&!jw(s,je()))return null;{let a=n||ve.EMPTY_NODE;return Md(s,a)}}}else{let o=ia(t.visibleWrites,e);if(!i&&Hw(o))return n;if(!i&&n==null&&!jw(o,je()))return null;{let s=function(l){return(l.visible||i)&&(!r||!~r.indexOf(l.writeId))&&(Yr(l.path,e)||Yr(e,l.path))},a=oH(t.allWrites,s,e),c=n||ve.EMPTY_NODE;return Md(a,c)}}}function Lie(t,e,n){let r=ve.EMPTY_NODE,i=El(t.visibleWrites,e);if(i)return i.isLeafNode()||i.forEachChild(ht,(o,s)=>{r=r.updateImmediateChild(o,s)}),r;if(n){let o=ia(t.visibleWrites,e);return n.forEachChild(ht,(s,a)=>{let c=Md(ia(o,new He(s)),a);r=r.updateImmediateChild(s,c)}),gj(o).forEach(s=>{r=r.updateImmediateChild(s.name,s.node)}),r}else{let o=ia(t.visibleWrites,e);return gj(o).forEach(s=>{r=r.updateImmediateChild(s.name,s.node)}),r}}function Pie(t,e,n,r,i){Y(r||i,"Either existingEventSnap or existingServerSnap must exist");let o=At(e,n);if(jw(t.visibleWrites,o))return null;{let s=ia(t.visibleWrites,o);return Hw(s)?i.getChild(n):Md(s,i.getChild(n))}}function xie(t,e,n,r){let i=At(e,n),o=El(t.visibleWrites,i);if(o!=null)return o;if(r.isCompleteForChild(n)){let s=ia(t.visibleWrites,i);return Md(s,r.getNode().getImmediateChild(n))}else return null}function kie(t,e){return El(t.visibleWrites,e)}function Fie(t,e,n,r,i,o,s){let a,c=ia(t.visibleWrites,e),l=El(c,je());if(l!=null)a=l;else if(n!=null)a=Md(c,n);else return[];if(a=a.withIndex(s),!a.isEmpty()&&!a.isLeafNode()){let d=[],h=s.getCompare(),f=o?a.getReverseIteratorFrom(r,s):a.getIteratorFrom(r,s),g=f.getNext();for(;g&&d.length<i;)h(g,r)!==0&&d.push(g),g=f.getNext();return d}else return[]}function Uie(){return{visibleWrites:vi.empty(),allWrites:[],lastWriteId:-1}}function Uy(t,e,n,r){return sH(t.writeTree,t.treePath,e,n,r)}function yb(t,e){return Lie(t.writeTree,t.treePath,e)}function mj(t,e,n,r){return Pie(t.writeTree,t.treePath,e,n,r)}function Vy(t,e){return kie(t.writeTree,At(t.treePath,e))}function Vie(t,e,n,r,i,o){return Fie(t.writeTree,t.treePath,e,n,r,i,o)}function Ib(t,e,n){return xie(t.writeTree,t.treePath,e,n)}function aH(t,e){return cH(At(t.treePath,e),t.writeTree)}function cH(t,e){return{treePath:t,writeTree:e}}var $w=class{constructor(){this.changeMap=new Map}trackChildChange(e){let n=e.type,r=e.childName;Y(n==="child_added"||n==="child_changed"||n==="child_removed","Only child changes supported for tracking"),Y(r!==".priority","Only non-priority child changes can be tracked.");let i=this.changeMap.get(r);if(i){let o=i.type;if(n==="child_added"&&o==="child_removed")this.changeMap.set(r,Zp(r,e.snapshotNode,i.snapshotNode));else if(n==="child_removed"&&o==="child_added")this.changeMap.delete(r);else if(n==="child_removed"&&o==="child_changed")this.changeMap.set(r,Jp(r,i.oldSnap));else if(n==="child_changed"&&o==="child_added")this.changeMap.set(r,bd(r,e.snapshotNode));else if(n==="child_changed"&&o==="child_changed")this.changeMap.set(r,Zp(r,e.snapshotNode,i.oldSnap));else throw zc("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}};var Ww=class{getCompleteChild(e){return null}getChildAfterChild(e,n,r){return null}},lH=new Ww,ng=class{constructor(e,n,r=null){this.writes_=e,this.viewCache_=n,this.optCompleteServerCache_=r}getCompleteChild(e){let n=this.viewCache_.eventCache;if(n.isCompleteForChild(e))return n.getNode().getImmediateChild(e);{let r=this.optCompleteServerCache_!=null?new go(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Ib(this.writes_,e,r)}}getChildAfterChild(e,n,r){let i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:dl(this.viewCache_),o=Vie(this.writes_,i,n,1,r,e);return o.length===0?null:o[0]}};function Bie(t){return{filter:t}}function Gie(t,e){Y(e.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),Y(e.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed")}function jie(t,e,n,r,i){let o=new $w,s,a;if(n.type===po.OVERWRITE){let l=n;l.source.fromUser?s=zw(t,e,l.path,l.snap,r,i,o):(Y(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!Oe(l.path),s=By(t,e,l.path,l.snap,r,i,a,o))}else if(n.type===po.MERGE){let l=n;l.source.fromUser?s=$ie(t,e,l.path,l.children,r,i,o):(Y(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),s=qw(t,e,l.path,l.children,r,i,a,o))}else if(n.type===po.ACK_USER_WRITE){let l=n;l.revert?s=qie(t,e,l.path,r,i,o):s=Wie(t,e,l.path,l.affectedTree,r,i,o)}else if(n.type===po.LISTEN_COMPLETE)s=zie(t,e,n.path,r,o);else throw zc("Unknown operation type: "+n.type);let c=o.getChanges();return Hie(e,s,c),{viewCache:s,changes:c}}function Hie(t,e,n){let r=e.eventCache;if(r.isFullyInitialized()){let i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=Fy(t);(n.length>0||!t.eventCache.isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(nH(Fy(e)))}}function uH(t,e,n,r,i,o){let s=e.eventCache;if(Vy(r,n)!=null)return e;{let a,c;if(Oe(n))if(Y(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){let l=dl(e),d=l instanceof ve?l:ve.EMPTY_NODE,h=yb(r,d);a=t.filter.updateFullNode(e.eventCache.getNode(),h,o)}else{let l=Uy(r,dl(e));a=t.filter.updateFullNode(e.eventCache.getNode(),l,o)}else{let l=be(n);if(l===".priority"){Y(aa(n)===1,"Can't have a priority with additional path components");let d=s.getNode();c=e.serverCache.getNode();let h=mj(r,n,d,c);h!=null?a=t.filter.updatePriority(d,h):a=s.getNode()}else{let d=ct(n),h;if(s.isCompleteForChild(l)){c=e.serverCache.getNode();let f=mj(r,n,s.getNode(),c);f!=null?h=s.getNode().getImmediateChild(l).updateChild(d,f):h=s.getNode().getImmediateChild(l)}else h=Ib(r,l,e.serverCache);h!=null?a=t.filter.updateChild(s.getNode(),l,h,d,i,o):a=s.getNode()}}return qp(e,a,s.isFullyInitialized()||Oe(n),t.filter.filtersNodes())}}function By(t,e,n,r,i,o,s,a){let c=e.serverCache,l,d=s?t.filter:t.filter.getIndexedFilter();if(Oe(n))l=d.updateFullNode(c.getNode(),r,null);else if(d.filtersNodes()&&!c.isFiltered()){let g=c.getNode().updateChild(n,r);l=d.updateFullNode(c.getNode(),g,null)}else{let g=be(n);if(!c.isCompleteForPath(n)&&aa(n)>1)return e;let E=ct(n),S=c.getNode().getImmediateChild(g).updateChild(E,r);g===".priority"?l=d.updatePriority(c.getNode(),S):l=d.updateChild(c.getNode(),g,S,E,lH,null)}let h=rH(e,l,c.isFullyInitialized()||Oe(n),d.filtersNodes()),f=new ng(i,h,o);return uH(t,h,n,i,f,a)}function zw(t,e,n,r,i,o,s){let a=e.eventCache,c,l,d=new ng(i,e,o);if(Oe(n))l=t.filter.updateFullNode(e.eventCache.getNode(),r,s),c=qp(e,l,!0,t.filter.filtersNodes());else{let h=be(n);if(h===".priority")l=t.filter.updatePriority(e.eventCache.getNode(),r),c=qp(e,l,a.isFullyInitialized(),a.isFiltered());else{let f=ct(n),g=a.getNode().getImmediateChild(h),E;if(Oe(f))E=r;else{let I=d.getCompleteChild(h);I!=null?fb(f)===".priority"&&I.getChild(Yj(f)).isEmpty()?E=I:E=I.updateChild(f,r):E=ve.EMPTY_NODE}if(g.equals(E))c=e;else{let I=t.filter.updateChild(a.getNode(),h,E,f,d,s);c=qp(e,I,a.isFullyInitialized(),t.filter.filtersNodes())}}}return c}function Ej(t,e){return t.eventCache.isCompleteForChild(e)}function $ie(t,e,n,r,i,o,s){let a=e;return r.foreach((c,l)=>{let d=At(n,c);Ej(e,be(d))&&(a=zw(t,a,d,l,i,o,s))}),r.foreach((c,l)=>{let d=At(n,c);Ej(e,be(d))||(a=zw(t,a,d,l,i,o,s))}),a}function _j(t,e,n){return n.foreach((r,i)=>{e=e.updateChild(r,i)}),e}function qw(t,e,n,r,i,o,s,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;Oe(n)?l=r:l=new Yn(null).setTree(n,r);let d=e.serverCache.getNode();return l.children.inorderTraversal((h,f)=>{if(d.hasChild(h)){let g=e.serverCache.getNode().getImmediateChild(h),E=_j(t,g,f);c=By(t,c,new He(h),E,i,o,s,a)}}),l.children.inorderTraversal((h,f)=>{let g=!e.serverCache.isCompleteForChild(h)&&f.value===null;if(!d.hasChild(h)&&!g){let E=e.serverCache.getNode().getImmediateChild(h),I=_j(t,E,f);c=By(t,c,new He(h),I,i,o,s,a)}}),c}function Wie(t,e,n,r,i,o,s){if(Vy(i,n)!=null)return e;let a=e.serverCache.isFiltered(),c=e.serverCache;if(r.value!=null){if(Oe(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return By(t,e,n,c.getNode().getChild(n),i,o,a,s);if(Oe(n)){let l=new Yn(null);return c.getNode().forEachChild(ll,(d,h)=>{l=l.set(new He(d),h)}),qw(t,e,n,l,i,o,a,s)}else return e}else{let l=new Yn(null);return r.foreach((d,h)=>{let f=At(n,d);c.isCompleteForPath(f)&&(l=l.set(d,c.getNode().getChild(f)))}),qw(t,e,n,l,i,o,a,s)}}function zie(t,e,n,r,i){let o=e.serverCache,s=rH(e,o.getNode(),o.isFullyInitialized()||Oe(n),o.isFiltered());return uH(t,s,n,r,lH,i)}function qie(t,e,n,r,i,o){let s;if(Vy(r,n)!=null)return e;{let a=new ng(r,e,i),c=e.eventCache.getNode(),l;if(Oe(n)||be(n)===".priority"){let d;if(e.serverCache.isFullyInitialized())d=Uy(r,dl(e));else{let h=e.serverCache.getNode();Y(h instanceof ve,"serverChildren would be complete if leaf node"),d=yb(r,h)}d=d,l=t.filter.updateFullNode(c,d,o)}else{let d=be(n),h=Ib(r,d,e.serverCache);h==null&&e.serverCache.isCompleteForChild(d)&&(h=c.getImmediateChild(d)),h!=null?l=t.filter.updateChild(c,d,h,ct(n),a,o):e.eventCache.getNode().hasChild(d)?l=t.filter.updateChild(c,d,ve.EMPTY_NODE,ct(n),a,o):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(s=Uy(r,dl(e)),s.isLeafNode()&&(l=t.filter.updateFullNode(l,s,o)))}return s=e.serverCache.isFullyInitialized()||Vy(r,je())!=null,qp(e,l,s,t.filter.filtersNodes())}}var Kw=class{constructor(e,n){this.query_=e,this.eventRegistrations_=[];let r=this.query_._queryParams,i=new eg(r.getIndex()),o=pie(r);this.processor_=Bie(o);let s=n.serverCache,a=n.eventCache,c=i.updateFullNode(ve.EMPTY_NODE,s.getNode(),null),l=o.updateFullNode(ve.EMPTY_NODE,a.getNode(),null),d=new go(c,s.isFullyInitialized(),i.filtersNodes()),h=new go(l,a.isFullyInitialized(),o.filtersNodes());this.viewCache_=Qy(h,d),this.eventGenerator_=new Bw(this.query_)}get query(){return this.query_}};function Kie(t){return t.viewCache_.serverCache.getNode()}function Yie(t){return Fy(t.viewCache_)}function Xie(t,e){let n=dl(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!Oe(e)&&!n.getImmediateChild(be(e)).isEmpty())?n.getChild(e):null}function Tj(t){return t.eventRegistrations_.length===0}function Qie(t,e){t.eventRegistrations_.push(e)}function yj(t,e,n){let r=[];if(n){Y(e==null,"A cancel should cancel all event registrations.");let i=t.query._path;t.eventRegistrations_.forEach(o=>{let s=o.createCancelEvent(n,i);s&&r.push(s)})}if(e){let i=[];for(let o=0;o<t.eventRegistrations_.length;++o){let s=t.eventRegistrations_[o];if(!s.matches(e))i.push(s);else if(e.hasAnyCallback()){i=i.concat(t.eventRegistrations_.slice(o+1));break}}t.eventRegistrations_=i}else t.eventRegistrations_=[];return r}function Ij(t,e,n,r){e.type===po.MERGE&&e.source.queryId!==null&&(Y(dl(t.viewCache_),"We should always have a full cache before handling merges"),Y(Fy(t.viewCache_),"Missing event cache, even though we have a server cache"));let i=t.viewCache_,o=jie(t.processor_,i,e,n,r);return Gie(t.processor_,o.viewCache),Y(o.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),t.viewCache_=o.viewCache,dH(t,o.changes,o.viewCache.eventCache.getNode(),null)}function Jie(t,e){let n=t.viewCache_.eventCache,r=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(ht,(o,s)=>{r.push(bd(o,s))}),n.isFullyInitialized()&&r.push(nH(n.getNode())),dH(t,r,n.getNode(),e)}function dH(t,e,n,r){let i=r?[r]:t.eventRegistrations_;return vie(t.eventGenerator_,e,n,i)}var Gy,jy=class{constructor(){this.views=new Map}};function Zie(t){Y(!Gy,"__referenceConstructor has already been defined"),Gy=t}function eoe(){return Y(Gy,"Reference.ts has not been loaded"),Gy}function toe(t){return t.views.size===0}function vb(t,e,n,r){let i=e.source.queryId;if(i!==null){let o=t.views.get(i);return Y(o!=null,"SyncTree gave us an op for an invalid query."),Ij(o,e,n,r)}else{let o=[];for(let s of t.views.values())o=o.concat(Ij(s,e,n,r));return o}}function hH(t,e,n,r,i){let o=e._queryIdentifier,s=t.views.get(o);if(!s){let a=Uy(n,i?r:null),c=!1;a?c=!0:r instanceof ve?(a=yb(n,r),c=!1):(a=ve.EMPTY_NODE,c=!1);let l=Qy(new go(a,c,!1),new go(r,i,!1));return new Kw(e,l)}return s}function noe(t,e,n,r,i,o){let s=hH(t,e,r,i,o);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,s),Qie(s,n),Jie(s,n)}function roe(t,e,n,r){let i=e._queryIdentifier,o=[],s=[],a=ca(t);if(i==="default")for(let[c,l]of t.views.entries())s=s.concat(yj(l,n,r)),Tj(l)&&(t.views.delete(c),l.query._queryParams.loadsAllData()||o.push(l.query));else{let c=t.views.get(i);c&&(s=s.concat(yj(c,n,r)),Tj(c)&&(t.views.delete(i),c.query._queryParams.loadsAllData()||o.push(c.query)))}return a&&!ca(t)&&o.push(new(eoe())(e._repo,e._path)),{removed:o,events:s}}function fH(t){let e=[];for(let n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function oa(t,e){let n=null;for(let r of t.views.values())n=n||Xie(r,e);return n}function pH(t,e){if(e._queryParams.loadsAllData())return Zy(t);{let r=e._queryIdentifier;return t.views.get(r)}}function gH(t,e){return pH(t,e)!=null}function ca(t){return Zy(t)!=null}function Zy(t){for(let e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}var Hy;function ioe(t){Y(!Hy,"__referenceConstructor has already been defined"),Hy=t}function ooe(){return Y(Hy,"Reference.ts has not been loaded"),Hy}var soe=1,$y=class{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Yn(null),this.pendingWriteTree_=Uie(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}};function Sb(t,e,n,r,i){return Die(t.pendingWriteTree_,e,n,r,i),i?Fd(t,new Od(Eb(),e,n)):[]}function aoe(t,e,n,r){Rie(t.pendingWriteTree_,e,n,r);let i=Yn.fromObject(n);return Fd(t,new tg(Eb(),e,i))}function na(t,e,n=!1){let r=Nie(t.pendingWriteTree_,e);if(wie(t.pendingWriteTree_,e)){let o=new Yn(null);return r.snap!=null?o=o.set(je(),!0):un(r.children,s=>{o=o.set(new He(s),!0)}),Fd(t,new Vw(r.path,o,n))}else return[]}function dg(t,e,n){return Fd(t,new Od(_b(),e,n))}function coe(t,e,n){let r=Yn.fromObject(n);return Fd(t,new tg(_b(),e,r))}function loe(t,e){return Fd(t,new ky(_b(),e))}function uoe(t,e,n){let r=Ab(t,n);if(r){let i=Cb(r),o=i.path,s=i.queryId,a=Kn(o,e),c=new ky(Tb(s),a);return Db(t,o,c)}else return[]}function Wy(t,e,n,r,i=!1){let o=e._path,s=t.syncPointTree_.get(o),a=[];if(s&&(e._queryIdentifier==="default"||gH(s,e))){let c=roe(s,e,n,r);toe(s)&&(t.syncPointTree_=t.syncPointTree_.remove(o));let l=c.removed;if(a=c.events,!i){let d=l.findIndex(f=>f._queryParams.loadsAllData())!==-1,h=t.syncPointTree_.findOnPath(o,(f,g)=>ca(g));if(d&&!h){let f=t.syncPointTree_.subtree(o);if(!f.isEmpty()){let g=foe(f);for(let E=0;E<g.length;++E){let I=g[E],S=I.query,L=TH(t,I);t.listenProvider_.startListening(Yp(S),rg(t,S),L.hashFn,L.onComplete)}}}!h&&l.length>0&&!r&&(d?t.listenProvider_.stopListening(Yp(e),null):l.forEach(f=>{let g=t.queryToTagMap.get(tI(f));t.listenProvider_.stopListening(Yp(f),g)}))}poe(t,l)}return a}function mH(t,e,n,r){let i=Ab(t,r);if(i!=null){let o=Cb(i),s=o.path,a=o.queryId,c=Kn(s,e),l=new Od(Tb(a),c,n);return Db(t,s,l)}else return[]}function doe(t,e,n,r){let i=Ab(t,r);if(i){let o=Cb(i),s=o.path,a=o.queryId,c=Kn(s,e),l=Yn.fromObject(n),d=new tg(Tb(a),c,l);return Db(t,s,d)}else return[]}function Yw(t,e,n,r=!1){let i=e._path,o=null,s=!1;t.syncPointTree_.foreachOnPath(i,(f,g)=>{let E=Kn(f,i);o=o||oa(g,E),s=s||ca(g)});let a=t.syncPointTree_.get(i);a?(s=s||ca(a),o=o||oa(a,je())):(a=new jy,t.syncPointTree_=t.syncPointTree_.set(i,a));let c;o!=null?c=!0:(c=!1,o=ve.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((g,E)=>{let I=oa(E,je());I&&(o=o.updateImmediateChild(g,I))}));let l=gH(a,e);if(!l&&!e._queryParams.loadsAllData()){let f=tI(e);Y(!t.queryToTagMap.has(f),"View does not exist, but we have a tag");let g=goe();t.queryToTagMap.set(f,g),t.tagToQueryMap.set(g,f)}let d=Jy(t.pendingWriteTree_,i),h=noe(a,e,n,d,o,c);if(!l&&!s&&!r){let f=pH(a,e);h=h.concat(moe(t,e,f))}return h}function eI(t,e,n){let i=t.pendingWriteTree_,o=t.syncPointTree_.findOnPath(e,(s,a)=>{let c=Kn(s,e),l=oa(a,c);if(l)return l});return sH(i,e,o,n,!0)}function hoe(t,e){let n=e._path,r=null;t.syncPointTree_.foreachOnPath(n,(l,d)=>{let h=Kn(l,n);r=r||oa(d,h)});let i=t.syncPointTree_.get(n);i?r=r||oa(i,je()):(i=new jy,t.syncPointTree_=t.syncPointTree_.set(n,i));let o=r!=null,s=o?new go(r,!0,!1):null,a=Jy(t.pendingWriteTree_,e._path),c=hH(i,e,a,o?s.getNode():ve.EMPTY_NODE,o);return Yie(c)}function Fd(t,e){return EH(e,t.syncPointTree_,null,Jy(t.pendingWriteTree_,je()))}function EH(t,e,n,r){if(Oe(t.path))return _H(t,e,n,r);{let i=e.get(je());n==null&&i!=null&&(n=oa(i,je()));let o=[],s=be(t.path),a=t.operationForChild(s),c=e.children.get(s);if(c&&a){let l=n?n.getImmediateChild(s):null,d=aH(r,s);o=o.concat(EH(a,c,l,d))}return i&&(o=o.concat(vb(i,t,r,n))),o}}function _H(t,e,n,r){let i=e.get(je());n==null&&i!=null&&(n=oa(i,je()));let o=[];return e.children.inorderTraversal((s,a)=>{let c=n?n.getImmediateChild(s):null,l=aH(r,s),d=t.operationForChild(s);d&&(o=o.concat(_H(d,a,c,l)))}),i&&(o=o.concat(vb(i,t,r,n))),o}function TH(t,e){let n=e.query,r=rg(t,n);return{hashFn:()=>(Kie(e)||ve.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return r?uoe(t,n._path,r):loe(t,n._path);{let o=Dre(i,n);return Wy(t,n,null,o)}}}}function rg(t,e){let n=tI(e);return t.queryToTagMap.get(n)}function tI(t){return t._path.toString()+"$"+t._queryIdentifier}function Ab(t,e){return t.tagToQueryMap.get(e)}function Cb(t){let e=t.indexOf("$");return Y(e!==-1&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new He(t.substr(0,e))}}function Db(t,e,n){let r=t.syncPointTree_.get(e);Y(r,"Missing sync point for query tag that we're tracking");let i=Jy(t.pendingWriteTree_,e);return vb(r,n,i,null)}function foe(t){return t.fold((e,n,r)=>{if(n&&ca(n))return[Zy(n)];{let i=[];return n&&(i=fH(n)),un(r,(o,s)=>{i=i.concat(s)}),i}})}function Yp(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(ooe())(t._repo,t._path):t}function poe(t,e){for(let n=0;n<e.length;++n){let r=e[n];if(!r._queryParams.loadsAllData()){let i=tI(r),o=t.queryToTagMap.get(i);t.queryToTagMap.delete(i),t.tagToQueryMap.delete(o)}}}function goe(){return soe++}function moe(t,e,n){let r=e._path,i=rg(t,e),o=TH(t,n),s=t.listenProvider_.startListening(Yp(e),i,o.hashFn,o.onComplete),a=t.syncPointTree_.subtree(r);if(i)Y(!ca(a.value),"If we're adding a query, it shouldn't be shadowed");else{let c=a.fold((l,d,h)=>{if(!Oe(l)&&d&&ca(d))return[Zy(d).query];{let f=[];return d&&(f=f.concat(fH(d).map(g=>g.query))),un(h,(g,E)=>{f=f.concat(E)}),f}});for(let l=0;l<c.length;++l){let d=c[l];t.listenProvider_.stopListening(Yp(d),rg(t,d))}}return s}var Xw=class t{constructor(e){this.node_=e}getImmediateChild(e){let n=this.node_.getImmediateChild(e);return new t(n)}node(){return this.node_}},Qw=class t{constructor(e,n){this.syncTree_=e,this.path_=n}getImmediateChild(e){let n=At(this.path_,e);return new t(this.syncTree_,n)}node(){return eI(this.syncTree_,this.path_)}},Eoe=function(t){return t=t||{},t.timestamp=t.timestamp||new Date().getTime(),t},vj=function(t,e,n){if(!t||typeof t!="object")return t;if(Y(".sv"in t,"Unexpected leaf node or priority contents"),typeof t[".sv"]=="string")return _oe(t[".sv"],e,n);if(typeof t[".sv"]=="object")return Toe(t[".sv"],e);Y(!1,"Unexpected server value: "+JSON.stringify(t,null,2))},_oe=function(t,e,n){if(t==="timestamp")return n.timestamp;Y(!1,"Unexpected server value: "+t)},Toe=function(t,e,n){t.hasOwnProperty("increment")||Y(!1,"Unexpected server value: "+JSON.stringify(t,null,2));let r=t.increment;typeof r!="number"&&Y(!1,"Unexpected increment value: "+r);let i=e.node();if(Y(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;let s=i.getValue();return typeof s!="number"?r:s+r},yH=function(t,e,n,r){return Nb(e,new Qw(n,t),r)},Rb=function(t,e,n){return Nb(t,new Xw(e),n)};function Nb(t,e,n){let r=t.getPriority().val(),i=vj(r,e.getImmediateChild(".priority"),n),o;if(t.isLeafNode()){let s=t,a=vj(s.getValue(),e,n);return a!==s.getValue()||i!==s.getPriority().val()?new Nd(a,St(i)):t}else{let s=t;return o=s,i!==s.getPriority().val()&&(o=o.updatePriority(new Nd(i))),s.forEachChild(ht,(a,c)=>{let l=Nb(c,e.getImmediateChild(a),n);l!==c&&(o=o.updateImmediateChild(a,l))}),o}}var ig=class{constructor(e="",n=null,r={children:{},childCount:0}){this.name=e,this.parent=n,this.node=r}};function nI(t,e){let n=e instanceof He?e:new He(e),r=t,i=be(n);for(;i!==null;){let o=$s(r.node.children,i)||{children:{},childCount:0};r=new ig(i,r,o),n=ct(n),i=be(n)}return r}function _l(t){return t.node.value}function wb(t,e){t.node.value=e,Jw(t)}function IH(t){return t.node.childCount>0}function yoe(t){return _l(t)===void 0&&!IH(t)}function rI(t,e){un(t.node.children,(n,r)=>{e(new ig(n,t,r))})}function vH(t,e,n,r){n&&!r&&e(t),rI(t,i=>{vH(i,e,!0,r)}),n&&r&&e(t)}function Ioe(t,e,n){let r=n?t:t.parent;for(;r!==null;){if(e(r))return!0;r=r.parent}return!1}function hg(t){return new He(t.parent===null?t.name:hg(t.parent)+"/"+t.name)}function Jw(t){t.parent!==null&&voe(t.parent,t.name,t)}function voe(t,e,n){let r=yoe(n),i=zr(t.node.children,e);r&&i?(delete t.node.children[e],t.node.childCount--,Jw(t)):!r&&!i&&(t.node.children[e]=n.node,t.node.childCount++,Jw(t))}var Soe=/[\[\].#$\/\u0000-\u001F\u007F]/,Aoe=/[\[\].#$\u0000-\u001F\u007F]/,uw=10*1024*1024,iI=function(t){return typeof t=="string"&&t.length!==0&&!Soe.test(t)},SH=function(t){return typeof t=="string"&&t.length!==0&&!Aoe.test(t)},Coe=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),SH(t)},og=function(t){return t===null||typeof t=="string"||typeof t=="number"&&!Xy(t)||t&&typeof t=="object"&&zr(t,".sv")},hl=function(t,e,n,r){r&&e===void 0||fg(Ws(t,"value"),e,n)},fg=function(t,e,n){let r=n instanceof He?new Sw(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+sl(r));if(typeof e=="function")throw new Error(t+"contains a function "+sl(r)+" with contents = "+e.toString());if(Xy(e))throw new Error(t+"contains "+e.toString()+" "+sl(r));if(typeof e=="string"&&e.length>uw/3&&vp(e)>uw)throw new Error(t+"contains a string greater than "+uw+" utf8 bytes "+sl(r)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,o=!1;if(un(e,(s,a)=>{if(s===".value")i=!0;else if(s!==".priority"&&s!==".sv"&&(o=!0,!iI(s)))throw new Error(t+" contains an invalid key ("+s+") "+sl(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);tie(r,s),fg(t,a,r),nie(r)}),i&&o)throw new Error(t+' contains ".value" child '+sl(r)+" in addition to actual children.")}},Doe=function(t,e){let n,r;for(n=0;n<e.length;n++){r=e[n];let o=Xp(r);for(let s=0;s<o.length;s++)if(!(o[s]===".priority"&&s===o.length-1)){if(!iI(o[s]))throw new Error(t+"contains an invalid key ("+o[s]+") in path "+r.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}}e.sort(eie);let i=null;for(n=0;n<e.length;n++){if(r=e[n],i!==null&&Yr(i,r))throw new Error(t+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}},AH=function(t,e,n,r){if(r&&e===void 0)return;let i=Ws(t,"values");if(!(e&&typeof e=="object")||Array.isArray(e))throw new Error(i+" must be an object containing the children to replace.");let o=[];un(e,(s,a)=>{let c=new He(s);if(fg(i,a,At(n,c)),fb(c)===".priority"&&!og(a))throw new Error(i+"contains an invalid value for '"+c.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(c)}),Doe(i,o)},Roe=function(t,e,n){if(!(n&&e===void 0)){if(Xy(e))throw new Error(Ws(t,"priority")+"is "+e.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!og(e))throw new Error(Ws(t,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},CH=function(t,e,n,r){if(!(r&&n===void 0)&&!iI(n))throw new Error(Ws(t,e)+'was an invalid key = "'+n+`". Firebase keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]").`)},bb=function(t,e,n,r){if(!(r&&n===void 0)&&!SH(n))throw new Error(Ws(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Noe=function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),bb(t,e,n,r)},ra=function(t,e){if(be(e)===".info")throw new Error(t+" failed = Can't modify data under /.info/")},woe=function(t,e){let n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!iI(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Coe(n))throw new Error(Ws(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};var Zw=class{constructor(){this.eventLists_=[],this.recursionDepth_=0}};function oI(t,e){let n=null;for(let r=0;r<e.length;r++){let i=e[r],o=i.getPath();n!==null&&!pb(o,n.path)&&(t.eventLists_.push(n),n=null),n===null&&(n={events:[],path:o}),n.events.push(i)}n&&t.eventLists_.push(n)}function DH(t,e,n){oI(t,n),RH(t,r=>pb(r,e))}function Cr(t,e,n){oI(t,n),RH(t,r=>Yr(r,e)||Yr(e,r))}function RH(t,e){t.recursionDepth_++;let n=!0;for(let r=0;r<t.eventLists_.length;r++){let i=t.eventLists_[r];if(i){let o=i.path;e(o)?(boe(t.eventLists_[r]),t.eventLists_[r]=null):n=!1}}n&&(t.eventLists_=[]),t.recursionDepth_--}function boe(t){for(let e=0;e<t.events.length;e++){let n=t.events[e];if(n!==null){t.events[e]=null;let r=n.getEventRunner();cl&&ln("event: "+n.toString()),xd(r)}}}var Ooe="repo_interrupt",Moe=25,eb=class{constructor(e,n,r,i){this.repoInfo_=e,this.forceRestClient_=n,this.authTokenProvider_=r,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Zw,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=xy(),this.transactionQueueTree_=new ig,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}};function Loe(t,e,n){if(t.stats_=hb(t.repoInfo_),t.forceRestClient_||bre())t.server_=new Lw(t.repoInfo_,(r,i,o,s)=>{Sj(t,r,i,o,s)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>Aj(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Pt(n)}catch(r){throw new Error("Invalid authOverride provided: "+r)}}t.persistentConnection_=new gb(t.repoInfo_,e,(r,i,o,s)=>{Sj(t,r,i,o,s)},r=>{Aj(t,r)},r=>{Poe(t,r)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(r=>{t.server_.refreshAuthToken(r)}),t.appCheckProvider_.addTokenChangeListener(r=>{t.server_.refreshAppCheckToken(r.token)}),t.statsReporter_=Mre(t.repoInfo_,()=>new Uw(t.stats_,t.server_)),t.infoData_=new Pw,t.infoSyncTree_=new $y({startListening:(r,i,o,s)=>{let a=[],c=t.infoData_.getNode(r._path);return c.isEmpty()||(a=dg(t.infoSyncTree_,r._path,c),setTimeout(()=>{s("ok")},0)),a},stopListening:()=>{}}),Ob(t,"connected",!1),t.serverSyncTree_=new $y({startListening:(r,i,o,s)=>(t.server_.listen(r,o,i,(a,c)=>{let l=s(a,c);Cr(t.eventQueue_,r._path,l)}),[]),stopListening:(r,i)=>{t.server_.unlisten(r,i)}})}function NH(t){let n=t.infoData_.getNode(new He(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function pg(t){return Eoe({timestamp:NH(t)})}function Sj(t,e,n,r,i){t.dataUpdateCount++;let o=new He(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let s=[];if(i)if(r){let c=yp(n,l=>St(l));s=doe(t.serverSyncTree_,o,c,i)}else{let c=St(n);s=mH(t.serverSyncTree_,o,c,i)}else if(r){let c=yp(n,l=>St(l));s=coe(t.serverSyncTree_,o,c)}else{let c=St(n);s=dg(t.serverSyncTree_,o,c)}let a=o;s.length>0&&(a=Ld(t,o)),Cr(t.eventQueue_,a,s)}function Aj(t,e){Ob(t,"connected",e),e===!1&&Uoe(t)}function Poe(t,e){un(e,(n,r)=>{Ob(t,n,r)})}function Ob(t,e,n){let r=new He("/.info/"+e),i=St(n);t.infoData_.updateSnapshot(r,i);let o=dg(t.infoSyncTree_,r,i);Cr(t.eventQueue_,r,o)}function sI(t){return t.nextWriteId_++}function xoe(t,e,n){let r=hoe(t.serverSyncTree_,e);return r!=null?Promise.resolve(r):t.server_.get(e).then(i=>{let o=St(i).withIndex(e._queryParams.getIndex());Yw(t.serverSyncTree_,e,n,!0);let s;if(e._queryParams.loadsAllData())s=dg(t.serverSyncTree_,e._path,o);else{let a=rg(t.serverSyncTree_,e);s=mH(t.serverSyncTree_,e._path,o,a)}return Cr(t.eventQueue_,e._path,s),Wy(t.serverSyncTree_,e,n,null,!0),o},i=>(Ud(t,"get for query "+Pt(e)+" failed: "+i),Promise.reject(new Error(i))))}function koe(t,e,n,r,i){Ud(t,"set",{path:e.toString(),value:n,priority:r});let o=pg(t),s=St(n,r),a=eI(t.serverSyncTree_,e),c=Rb(s,a,o),l=sI(t),d=Sb(t.serverSyncTree_,e,c,l,!0);oI(t.eventQueue_,d),t.server_.put(e.toString(),s.val(!0),(f,g)=>{let E=f==="ok";E||Fn("set at "+e+" failed: "+f);let I=na(t.serverSyncTree_,l,!E);Cr(t.eventQueue_,e,I),la(t,i,f,g)});let h=Lb(t,e);Ld(t,h),Cr(t.eventQueue_,h,[])}function Foe(t,e,n,r){Ud(t,"update",{path:e.toString(),value:n});let i=!0,o=pg(t),s={};if(un(n,(a,c)=>{i=!1,s[a]=yH(At(e,a),St(c),t.serverSyncTree_,o)}),i)ln("update() called with empty data. Don't do anything."),la(t,r,"ok",void 0);else{let a=sI(t),c=aoe(t.serverSyncTree_,e,s,a);oI(t.eventQueue_,c),t.server_.merge(e.toString(),n,(l,d)=>{let h=l==="ok";h||Fn("update at "+e+" failed: "+l);let f=na(t.serverSyncTree_,a,!h),g=f.length>0?Ld(t,e):e;Cr(t.eventQueue_,g,f),la(t,r,l,d)}),un(n,l=>{let d=Lb(t,At(e,l));Ld(t,d)}),Cr(t.eventQueue_,e,[])}}function Uoe(t){Ud(t,"onDisconnectEvents");let e=pg(t),n=xy();kw(t.onDisconnect_,je(),(i,o)=>{let s=yH(i,o,t.serverSyncTree_,e);kd(n,i,s)});let r=[];kw(n,je(),(i,o)=>{r=r.concat(dg(t.serverSyncTree_,i,o));let s=Lb(t,i);Ld(t,s)}),t.onDisconnect_=xy(),Cr(t.eventQueue_,je(),r)}function Voe(t,e,n){t.server_.onDisconnectCancel(e.toString(),(r,i)=>{r==="ok"&&xw(t.onDisconnect_,e),la(t,n,r,i)})}function Cj(t,e,n,r){let i=St(n);t.server_.onDisconnectPut(e.toString(),i.val(!0),(o,s)=>{o==="ok"&&kd(t.onDisconnect_,e,i),la(t,r,o,s)})}function Boe(t,e,n,r,i){let o=St(n,r);t.server_.onDisconnectPut(e.toString(),o.val(!0),(s,a)=>{s==="ok"&&kd(t.onDisconnect_,e,o),la(t,i,s,a)})}function Goe(t,e,n,r){if(Tp(n)){ln("onDisconnect().update() called with empty data. Don't do anything."),la(t,r,"ok",void 0);return}t.server_.onDisconnectMerge(e.toString(),n,(i,o)=>{i==="ok"&&un(n,(s,a)=>{let c=St(a);kd(t.onDisconnect_,At(e,s),c)}),la(t,r,i,o)})}function joe(t,e,n){let r;be(e._path)===".info"?r=Yw(t.infoSyncTree_,e,n):r=Yw(t.serverSyncTree_,e,n),DH(t.eventQueue_,e._path,r)}function tb(t,e,n){let r;be(e._path)===".info"?r=Wy(t.infoSyncTree_,e,n):r=Wy(t.serverSyncTree_,e,n),DH(t.eventQueue_,e._path,r)}function Hoe(t){t.persistentConnection_&&t.persistentConnection_.interrupt(Ooe)}function Ud(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),ln(n,...e)}function la(t,e,n,r){e&&xd(()=>{if(n==="ok")e(null);else{let i=(n||"error").toUpperCase(),o=i;r&&(o+=": "+r);let s=new Error(o);s.code=i,e(s)}})}function $oe(t,e,n,r,i,o){Ud(t,"transaction on "+e);let s={path:e,update:n,onComplete:r,status:null,order:wj(),applyLocally:o,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=Mb(t,e,void 0);s.currentInputSnapshot=a;let c=s.update(a.val());if(c===void 0)s.unwatcher(),s.currentOutputSnapshotRaw=null,s.currentOutputSnapshotResolved=null,s.onComplete&&s.onComplete(null,!1,s.currentInputSnapshot);else{fg("transaction failed: Data returned ",c,s.path),s.status=0;let l=nI(t.transactionQueueTree_,e),d=_l(l)||[];d.push(s),wb(l,d);let h;typeof c=="object"&&c!==null&&zr(c,".priority")?(h=$s(c,".priority"),Y(og(h),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):h=(eI(t.serverSyncTree_,e)||ve.EMPTY_NODE).getPriority().val();let f=pg(t),g=St(c,h),E=Rb(g,a,f);s.currentOutputSnapshotRaw=g,s.currentOutputSnapshotResolved=E,s.currentWriteId=sI(t);let I=Sb(t.serverSyncTree_,e,E,s.currentWriteId,s.applyLocally);Cr(t.eventQueue_,e,I),aI(t,t.transactionQueueTree_)}}function Mb(t,e,n){return eI(t.serverSyncTree_,e,n)||ve.EMPTY_NODE}function aI(t,e=t.transactionQueueTree_){if(e||cI(t,e),_l(e)){let n=bH(t,e);Y(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&Woe(t,hg(e),n)}else IH(e)&&rI(e,n=>{aI(t,n)})}function Woe(t,e,n){let r=n.map(l=>l.currentWriteId),i=Mb(t,e,r),o=i,s=i.hash();for(let l=0;l<n.length;l++){let d=n[l];Y(d.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),d.status=1,d.retryCount++;let h=Kn(e,d.path);o=o.updateChild(h,d.currentOutputSnapshotRaw)}let a=o.val(!0),c=e;t.server_.put(c.toString(),a,l=>{Ud(t,"transaction put response",{path:c.toString(),status:l});let d=[];if(l==="ok"){let h=[];for(let f=0;f<n.length;f++)n[f].status=2,d=d.concat(na(t.serverSyncTree_,n[f].currentWriteId)),n[f].onComplete&&h.push(()=>n[f].onComplete(null,!0,n[f].currentOutputSnapshotResolved)),n[f].unwatcher();cI(t,nI(t.transactionQueueTree_,e)),aI(t,t.transactionQueueTree_),Cr(t.eventQueue_,e,d);for(let f=0;f<h.length;f++)xd(h[f])}else{if(l==="datastale")for(let h=0;h<n.length;h++)n[h].status===3?n[h].status=4:n[h].status=0;else{Fn("transaction at "+c.toString()+" failed: "+l);for(let h=0;h<n.length;h++)n[h].status=4,n[h].abortReason=l}Ld(t,e)}},s)}function Ld(t,e){let n=wH(t,e),r=hg(n),i=bH(t,n);return zoe(t,i,r),r}function zoe(t,e,n){if(e.length===0)return;let r=[],i=[],s=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){let c=e[a],l=Kn(n,c.path),d=!1,h;if(Y(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)d=!0,h=c.abortReason,i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=Moe)d=!0,h="maxretry",i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0));else{let f=Mb(t,c.path,s);c.currentInputSnapshot=f;let g=e[a].update(f.val());if(g!==void 0){fg("transaction failed: Data returned ",g,c.path);let E=St(g);typeof g=="object"&&g!=null&&zr(g,".priority")||(E=E.updatePriority(f.getPriority()));let S=c.currentWriteId,L=pg(t),j=Rb(E,f,L);c.currentOutputSnapshotRaw=E,c.currentOutputSnapshotResolved=j,c.currentWriteId=sI(t),s.splice(s.indexOf(S),1),i=i.concat(Sb(t.serverSyncTree_,c.path,j,c.currentWriteId,c.applyLocally)),i=i.concat(na(t.serverSyncTree_,S,!0))}else d=!0,h="nodata",i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0))}Cr(t.eventQueue_,n,i),i=[],d&&(e[a].status=2,(function(f){setTimeout(f,Math.floor(0))})(e[a].unwatcher),e[a].onComplete&&(h==="nodata"?r.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):r.push(()=>e[a].onComplete(new Error(h),!1,null))))}cI(t,t.transactionQueueTree_);for(let a=0;a<r.length;a++)xd(r[a]);aI(t,t.transactionQueueTree_)}function wH(t,e){let n,r=t.transactionQueueTree_;for(n=be(e);n!==null&&_l(r)===void 0;)r=nI(r,n),e=ct(e),n=be(e);return r}function bH(t,e){let n=[];return OH(t,e,n),n.sort((r,i)=>r.order-i.order),n}function OH(t,e,n){let r=_l(e);if(r)for(let i=0;i<r.length;i++)n.push(r[i]);rI(e,i=>{OH(t,i,n)})}function cI(t,e){let n=_l(e);if(n){let r=0;for(let i=0;i<n.length;i++)n[i].status!==2&&(n[r]=n[i],r++);n.length=r,wb(e,n.length>0?n:void 0)}rI(e,r=>{cI(t,r)})}function Lb(t,e){let n=hg(wH(t,e)),r=nI(t.transactionQueueTree_,e);return Ioe(r,i=>{dw(t,i)}),dw(t,r),vH(r,i=>{dw(t,i)}),n}function dw(t,e){let n=_l(e);if(n){let r=[],i=[],o=-1;for(let s=0;s<n.length;s++)n[s].status===3||(n[s].status===1?(Y(o===s-1,"All SENT items should be at beginning of queue."),o=s,n[s].status=3,n[s].abortReason="set"):(Y(n[s].status===0,"Unexpected transaction status in abort"),n[s].unwatcher(),i=i.concat(na(t.serverSyncTree_,n[s].currentWriteId,!0)),n[s].onComplete&&r.push(n[s].onComplete.bind(null,new Error("set"),!1,null))));o===-1?wb(e,void 0):n.length=o+1,Cr(t.eventQueue_,hg(e),i);for(let s=0;s<r.length;s++)xd(r[s])}}function qoe(t){let e="",n=t.split("/");for(let r=0;r<n.length;r++)if(n[r].length>0){let i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function Koe(t){let e={};t.charAt(0)==="?"&&(t=t.substring(1));for(let n of t.split("&")){if(n.length===0)continue;let r=n.split("=");r.length===2?e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):Fn(`Invalid query segment '${n}' in query '${t}'`)}return e}var Dj=function(t,e){let n=Yoe(t),r=n.namespace;n.domain==="firebase.com"&&rs(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!r||r==="undefined")&&n.domain!=="localhost"&&rs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Ire();let i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new Dy(n.host,n.secure,r,i,e,"",r!==n.subdomain),path:new He(n.pathString)}},Yoe=function(t){let e="",n="",r="",i="",o="",s=!0,a="https",c=443;if(typeof t=="string"){let l=t.indexOf("//");l>=0&&(a=t.substring(0,l-1),t=t.substring(l+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),e=t.substring(0,Math.min(d,h)),d<h&&(i=qoe(t.substring(d,h)));let f=Koe(t.substring(Math.min(t.length,h)));l=e.indexOf(":"),l>=0?(s=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;let g=e.slice(0,l);if(g.toLowerCase()==="localhost")n="localhost";else if(g.split(".").length<=2)n=g;else{let E=e.indexOf(".");r=e.substring(0,E).toLowerCase(),n=e.substring(E+1),o=r}"ns"in f&&(o=f.ns)}return{host:e,port:c,domain:n,subdomain:r,secure:s,scheme:a,pathString:i,namespace:o}};var Rj="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Xoe=(function(){let t=0,e=[];return function(n){let r=n===t;t=n;let i,o=new Array(8);for(i=7;i>=0;i--)o[i]=Rj.charAt(n%64),n=Math.floor(n/64);Y(n===0,"Cannot push at time == 0");let s=o.join("");if(r){for(i=11;i>=0&&e[i]===63;i--)e[i]=0;e[i]++}else for(i=0;i<12;i++)e[i]=Math.floor(Math.random()*64);for(i=0;i<12;i++)s+=Rj.charAt(e[i]);return Y(s.length===20,"nextPushId: Length should be 20."),s}})();var zy=class{constructor(e,n,r,i){this.eventType=e,this.eventRegistration=n,this.snapshot=r,this.prevName=i}getPath(){let 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+":"+Pt(this.snapshot.exportVal())}},qy=class{constructor(e,n,r){this.eventRegistration=e,this.error=n,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}};var sg=class{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return Y(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}};var nb=class{constructor(e,n){this._repo=e,this._path=n}cancel(){let e=new an;return Voe(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){ra("OnDisconnect.remove",this._path);let e=new an;return Cj(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){ra("OnDisconnect.set",this._path),hl("OnDisconnect.set",e,this._path,!1);let n=new an;return Cj(this._repo,this._path,e,n.wrapCallback(()=>{})),n.promise}setWithPriority(e,n){ra("OnDisconnect.setWithPriority",this._path),hl("OnDisconnect.setWithPriority",e,this._path,!1),Roe("OnDisconnect.setWithPriority",n,!1);let r=new an;return Boe(this._repo,this._path,e,n,r.wrapCallback(()=>{})),r.promise}update(e){ra("OnDisconnect.update",this._path),AH("OnDisconnect.update",e,this._path,!1);let n=new an;return Goe(this._repo,this._path,e,n.wrapCallback(()=>{})),n.promise}};var fl=class t{constructor(e,n,r,i){this._repo=e,this._path=n,this._queryParams=r,this._orderByCalled=i}get key(){return Oe(this._path)?null:fb(this._path)}get ref(){return new Si(this._repo,this._path)}get _queryIdentifier(){let e=hj(this._queryParams),n=db(e);return n==="{}"?"default":n}get _queryObject(){return hj(this._queryParams)}isEqual(e){if(e=Pe(e),!(e instanceof t))return!1;let n=this._repo===e._repo,r=pb(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+Zre(this._path)}};function Qoe(t,e){if(t._orderByCalled===!0)throw new Error(e+": You can't combine multiple orderBy calls.")}function Pb(t){let e=null,n=null;if(t.hasStart()&&(e=t.getIndexStartValue()),t.hasEnd()&&(n=t.getIndexEndValue()),t.getIndex()===ll){let r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(t.hasStart()){if(t.getIndexStartName()!==ul)throw new Error(r);if(typeof e!="string")throw new Error(i)}if(t.hasEnd()){if(t.getIndexEndName()!==sa)throw new Error(r);if(typeof n!="string")throw new Error(i)}}else if(t.getIndex()===ht){if(e!=null&&!og(e)||n!=null&&!og(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(Y(t.getIndex()instanceof Qp||t.getIndex()===tH,"unknown index type."),e!=null&&typeof e=="object"||n!=null&&typeof n=="object")throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function MH(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}var Si=class t extends fl{constructor(e,n){super(e,n,new Mw,!1)}get parent(){let e=Yj(this._path);return e===null?null:new t(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}},Pd=class t{constructor(e,n,r){this._node=e,this.ref=n,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){let n=new He(e),r=pl(this.ref,e);return new t(this._node.getChild(n),r,ht)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(r,i)=>e(new t(i,pl(this.ref,r),ht)))}hasChild(e){let n=new He(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}};function LH(t,e){return t=Pe(t),t._checkNotDeleted("ref"),e!==void 0?pl(t._root,e):t._root}function pl(t,e){return t=Pe(t),be(t._path)===null?Noe("child","path",e,!1):bb("child","path",e,!1),new Si(t._repo,At(t._path,e))}function PH(t){return t=Pe(t),new nb(t._repo,t._path)}function xH(t,e){t=Pe(t),ra("push",t._path),hl("push",e,t._path,!0);let n=NH(t._repo),r=Xoe(n),i=pl(t,r),o=pl(t,r),s;return e!=null?s=lI(o,e).then(()=>o):s=Promise.resolve(o),i.then=s.then.bind(s),i.catch=s.then.bind(s,void 0),i}function kH(t){return ra("remove",t._path),lI(t,null)}function lI(t,e){t=Pe(t),ra("set",t._path),hl("set",e,t._path,!1);let n=new an;return koe(t._repo,t._path,e,null,n.wrapCallback(()=>{})),n.promise}function FH(t,e){AH("update",e,t._path,!1);let n=new an;return Foe(t._repo,t._path,e,n.wrapCallback(()=>{})),n.promise}function uI(t){t=Pe(t);let e=new sg(()=>{}),n=new ag(e);return xoe(t._repo,t,n).then(r=>new Pd(r,new Si(t._repo,t._path),t._queryParams.getIndex()))}var ag=class t{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){let r=n._queryParams.getIndex();return new zy("value",this,new Pd(e.snapshotNode,new Si(n._repo,n._path),r))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qy(this,e,n):null}matches(e){return e instanceof t?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}},Ky=class t{constructor(e,n){this.eventType=e,this.callbackContext=n}respondsTo(e){let n=e==="children_added"?"child_added":e;return n=n==="children_removed"?"child_removed":n,this.eventType===n}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qy(this,e,n):null}createEvent(e,n){Y(e.childName!=null,"Child events should have a childName.");let r=pl(new Si(n._repo,n._path),e.childName),i=n._queryParams.getIndex();return new zy(e.type,this,new Pd(e.snapshotNode,r,i),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof t?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}};function gg(t,e,n,r,i){let o;if(typeof r=="object"&&(o=void 0,i=r),typeof r=="function"&&(o=r),i&&i.onlyOnce){let c=n,l=(d,h)=>{tb(t._repo,t,a),c(d,h)};l.userCallback=n.userCallback,l.context=n.context,n=l}let s=new sg(n,o||void 0),a=e==="value"?new ag(s):new Ky(e,s);return joe(t._repo,t,a),()=>tb(t._repo,t,a)}function mg(t,e,n,r){return gg(t,"value",e,n,r)}function dI(t,e,n,r){return gg(t,"child_added",e,n,r)}function hI(t,e,n,r){return gg(t,"child_changed",e,n,r)}function xb(t,e,n,r){return gg(t,"child_moved",e,n,r)}function fI(t,e,n,r){return gg(t,"child_removed",e,n,r)}function pI(t,e,n){let r=null,i=n?new sg(n):null;e==="value"?r=new ag(i):e&&(r=new Ky(e,i)),tb(t._repo,t,r)}var gl=class{},rb=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="endAt"}_apply(e){hl("endAt",this._value,e._path,!0);let n=Eie(e._queryParams,this._value,this._key);if(MH(n),Pb(n),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new fl(e._repo,e._path,n,e._orderByCalled)}};var Yy=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="startAt"}_apply(e){hl("startAt",this._value,e._path,!0);let n=mie(e._queryParams,this._value,this._key);if(MH(n),Pb(n),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new fl(e._repo,e._path,n,e._orderByCalled)}};function UH(t=null,e){return CH("startAt","key",e,!0),new Yy(t,e)}var ib=class extends gl{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new fl(e._repo,e._path,gie(e._queryParams,this._limit),e._orderByCalled)}};function VH(t){if(typeof t!="number"||Math.floor(t)!==t||t<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new ib(t)}var ob=class extends gl{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Qoe(e,"orderByChild");let n=new He(this._path);if(Oe(n))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");let r=new Qp(n),i=_ie(e._queryParams,r);return Pb(i),new fl(e._repo,e._path,i,!0)}};function BH(t){if(t==="$key")throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if(t==="$priority")throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if(t==="$value")throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return bb("orderByChild","path",t,!1),new ob(t)}var sb=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="equalTo"}_apply(e){if(hl("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new rb(this._value,this._key)._apply(new Yy(this._value,this._key)._apply(e))}};function GH(t,e){return CH("equalTo","key",e,!0),new sb(t,e)}function jH(t,...e){let n=Pe(t);for(let r of e)n=r._apply(n);return n}Zie(Si);ioe(Si);var Joe="FIREBASE_DATABASE_EMULATOR_HOST",ab={},Zoe=!1;function ese(t,e,n,r){let i=e.lastIndexOf(":"),o=e.substring(0,i),s=vr(o);t.repoInfo_=new Dy(e,s,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(t.authTokenProvider_=r)}function tse(t,e,n,r,i){let o=r||t.options.databaseURL;o===void 0&&(t.options.projectId||rs("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),ln("Using default host for project ",t.options.projectId),o=`${t.options.projectId}-default-rtdb.firebaseio.com`);let s=Dj(o,i),a=s.repoInfo,c,l;typeof process<"u"&&process.env&&(l=process.env[Joe]),l?(c=!0,o=`http://${l}?ns=${a.namespace}`,s=Dj(o,i),a=s.repoInfo):c=!s.repoInfo.secure;let d=i&&c?new zp(zp.OWNER):new Ew(t.name,t.options,e);woe("Invalid Firebase Database URL",s),Oe(s.path)||rs("Database URL must point to the root of a Firebase Database (not including a child path).");let h=rse(a,t,d,new mw(t,n));return new cb(h,t)}function nse(t,e){let n=ab[e];(!n||n[t.key]!==t)&&rs(`Database ${e}(${t.repoInfo_}) has already been deleted.`),Hoe(t),delete n[t.key]}function rse(t,e,n,r){let i=ab[e.name];i||(i={},ab[e.name]=i);let o=i[t.toURLString()];return o&&rs("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),o=new eb(t,Zoe,n,r),i[t.toURLString()]=o,o}var cb=class{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Loe(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Si(this._repo,je())),this._rootInternal}_delete(){return this._rootInternal!==null&&(nse(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&rs("Cannot call "+e+" on a deleted database.")}};function ise(){Kj.IS_TRANSPORT_INITIALIZED&&Fn("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function kb(){ise(),Ad.forceDisallow(),Ry.forceAllow()}function Vd(t=ir(),e){let n=uo(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){let r=pd("database");r&&HH(n,...r)}return n}function HH(t,e,n,r={}){t=Pe(t),t._checkNotDeleted("useEmulator");let i=`${e}:${n}`,o=t._repoInternal;if(t._instanceStarted){if(i===t._repoInternal.repoInfo_.host&&mi(r,o.repoInfo_.emulatorOptions))return;rs("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let s;if(o.repoInfo_.nodeAdmin)r.mockUserToken&&rs('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new zp(zp.OWNER);else if(r.mockUserToken){let a=typeof r.mockUserToken=="string"?r.mockUserToken:zT(r.mockUserToken,t.app.options.projectId);s=new zp(a)}vr(e)&&(Hs(e),qc("Database",!0)),ese(o,i,r,s)}function ose(t){Tre(qs),zn(new Xt("database",(e,{instanceIdentifier:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),o=e.getProvider("app-check-internal");return tse(r,i,o,n)},"PUBLIC").setMultipleInstances(!0)),$e(Y2,X2,t),$e(Y2,X2,"esm2017")}var lb=class{constructor(e,n){this.committed=e,this.snapshot=n}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function $H(t,e,n){var r;if(t=Pe(t),ra("Reference.transaction",t._path),t.key===".length"||t.key===".keys")throw"Reference.transaction failed: "+t.key+" is a read-only object.";let i=(r=n?.applyLocally)!==null&&r!==void 0?r:!0,o=new an,s=(c,l,d)=>{let h=null;c?o.reject(c):(h=new Pd(d,new Si(t._repo,t._path),ht),o.resolve(new lb(l,h)))},a=mg(t,()=>{});return $oe(t._repo,t._path,e,s,a,i),o.promise}gb.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};gb.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};ose();var Tl,dn=(function(t){return t.added="child_added",t.removed="child_removed",t.changed="child_changed",t.moved="child_moved",t.value="value",t})(dn||{}),sse=Object.freeze((Tl={},Tl[dn.added]=dI,Tl[dn.removed]=fI,Tl[dn.changed]=hI,Tl[dn.moved]=xb,Tl[dn.value]=mg,Tl));function mI(t,e){return new ue(function(n){var r=sse[e](t,function(i,o){n.next({snapshot:i,prevKey:o,event:e})},n.error.bind(n));return{unsubscribe:function(){pI(t,e,r)}}}).pipe(yS(0))}var gI=function(){return gI=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},gI.apply(this,arguments)};function Fb(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}function WH(t){return(t==null||t.length===0)&&(t=[dn.added,dn.removed,dn.changed,dn.moved]),t}function zH(t,e){return e===void 0&&(e={}),mI(t,dn.value).pipe(De(function(n){return Ub(n,e)}))}function Ub(t,e){var n;e===void 0&&(e={});var r=t.snapshot.val();return!t.snapshot.exists()||typeof r!="object"?r:gI(gI({},r),e.keyField?(n={},n[e.keyField]=t.snapshot.key,n):null)}function qH(t,e){e===void 0&&(e={});var n=WH(e.events),r=n.map(function(i){return mI(t,i)});return vs.apply(void 0,r)}function ase(t){return hr(uI(t)).pipe(De(function(e){var n=dn.value;return{snapshot:e,prevKey:null,event:n}}))}function KH(t,e){e===void 0&&(e={});var n=WH(e.events);return ase(t).pipe(Zn(function(r){var i=[ot(r)];return n.forEach(function(o){i.push(mI(t,o))}),vs.apply(void 0,i).pipe(aE(lse,[]))}),ai())}function YH(t,e){return e===void 0&&(e={}),KH(t).pipe(De(function(n){return n.map(function(r){return Ub(r,e)})}))}function XH(t,e){for(var n=t.length,r=0;r<n;r++)if(t[r].snapshot.key===e)return r;return-1}function cse(t,e){if(e==null)return 0;var n=XH(t,e);return n===-1?t.length:n+1}function lse(t,e){var n=e.snapshot,r=e.prevKey,i=e.event,o=n.key,s=XH(t,o),a=cse(t,r||void 0);switch(i){case dn.value:if(e.snapshot&&e.snapshot.exists()){var c=null;e.snapshot.forEach(function(h){var f={snapshot:h,event:dn.value,prevKey:c};return c=h.key,t=Fb(Fb([],t,!0),[f],!1),!1})}return t;case dn.added:if(s>-1){var l=t[s-1];(l&&l.snapshot.key||null)!==r&&(t=t.filter(function(h){return h.snapshot.key!==n.key}),t.splice(a,0,e))}else{if(r==null)return Fb([e],t,!0);t=t.slice(),t.splice(a,0,e)}return t;case dn.removed:return t.filter(function(h){return h.snapshot.key!==n.key});case dn.changed:return t.map(function(h){return h.snapshot.key===o?e:h});case dn.moved:if(s>-1){var d=t.splice(s,1)[0];return t=t.slice(),t.splice(a,0,d),t}return t;default:return t}}var Eg=class{constructor(e){return e}},QH="database",Vb=class{constructor(){return Qo(QH)}};var Bb=new q("angularfire2.database-instances");function use(t,e){let n=Ks(QH,t,e);return n&&new Eg(n)}function dse(t){return(e,n)=>{let r=e.runOutsideAngular(()=>t(n));return new Eg(r)}}var hse={provide:Vb,deps:[[new Wt,Bb]]},fse={provide:Eg,useFactory:use,deps:[[new Wt,Bb],Ti]};function zFe(t,...e){return $e("angularfire",Ei.full,"rtdb"),er([fse,hse,{provide:Bb,useFactory:dse(t),multi:!0,deps:[Re,Ke,_i,Jo,[new Wt,el],[new Wt,Xs],...e]}])}var JH=de(YH,!0);var ZH=de(zH,!0),e$=de(qH,!0);var qFe=de(GH,!0,2);var _g=de(uI,!0),KFe=de(Vd,!0);var YFe=de(VH,!0,2),t$=de(pI,!0),n$=de(dI,!0),r$=de(hI,!0);var i$=de(fI,!0),o$=de(PH,!0),Gb=de(mg,!0),XFe=de(BH,!0,2);var s$=de(xH,!0,2),a$=de(jH,!0,2),Bd=de(LH,!0,2);var c$=de(kH,!0,2),l$=de($H,!0),u$=de(lI,!0,2);var QFe=de(UH,!0,2),d$=de(FH,!0,2);var h$=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},f$={};var is,jb;(function(){var t;function e(A,v){function C(){}C.prototype=v.prototype,A.D=v.prototype,A.prototype=new C,A.prototype.constructor=A,A.C=function(w,R,O){for(var D=Array(arguments.length-2),Mr=2;Mr<arguments.length;Mr++)D[Mr-2]=arguments[Mr];return v.prototype[R].apply(w,D)}}function n(){this.blockSize=-1}function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}e(r,n),r.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function i(A,v,C){C||(C=0);var w=Array(16);if(typeof v=="string")for(var R=0;16>R;++R)w[R]=v.charCodeAt(C++)|v.charCodeAt(C++)<<8|v.charCodeAt(C++)<<16|v.charCodeAt(C++)<<24;else for(R=0;16>R;++R)w[R]=v[C++]|v[C++]<<8|v[C++]<<16|v[C++]<<24;v=A.g[0],C=A.g[1],R=A.g[2];var O=A.g[3],D=v+(O^C&(R^O))+w[0]+3614090360&4294967295;v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[1]+3905402710&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[2]+606105819&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[3]+3250441966&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[4]+4118548399&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[5]+1200080426&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[6]+2821735955&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[7]+4249261313&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[8]+1770035416&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[9]+2336552879&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[10]+4294925233&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[11]+2304563134&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[12]+1804603682&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[13]+4254626195&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[14]+2792965006&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[15]+1236535329&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(R^O&(C^R))+w[1]+4129170786&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[6]+3225465664&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[11]+643717713&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[0]+3921069994&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[5]+3593408605&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[10]+38016083&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[15]+3634488961&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[4]+3889429448&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[9]+568446438&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[14]+3275163606&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[3]+4107603335&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[8]+1163531501&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[13]+2850285829&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[2]+4243563512&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[7]+1735328473&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[12]+2368359562&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(C^R^O)+w[5]+4294588738&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[8]+2272392833&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[11]+1839030562&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[14]+4259657740&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[1]+2763975236&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[4]+1272893353&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[7]+4139469664&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[10]+3200236656&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[13]+681279174&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[0]+3936430074&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[3]+3572445317&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[6]+76029189&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[9]+3654602809&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[12]+3873151461&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[15]+530742520&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[2]+3299628645&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(R^(C|~O))+w[0]+4096336452&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[7]+1126891415&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[14]+2878612391&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[5]+4237533241&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[12]+1700485571&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[3]+2399980690&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[10]+4293915773&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[1]+2240044497&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[8]+1873313359&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[15]+4264355552&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[6]+2734768916&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[13]+1309151649&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[4]+4149444226&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[11]+3174756917&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[2]+718787259&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[9]+3951481745&4294967295,A.g[0]=A.g[0]+v&4294967295,A.g[1]=A.g[1]+(R+(D<<21&4294967295|D>>>11))&4294967295,A.g[2]=A.g[2]+R&4294967295,A.g[3]=A.g[3]+O&4294967295}r.prototype.u=function(A,v){v===void 0&&(v=A.length);for(var C=v-this.blockSize,w=this.B,R=this.h,O=0;O<v;){if(R==0)for(;O<=C;)i(this,A,O),O+=this.blockSize;if(typeof A=="string"){for(;O<v;)if(w[R++]=A.charCodeAt(O++),R==this.blockSize){i(this,w),R=0;break}}else for(;O<v;)if(w[R++]=A[O++],R==this.blockSize){i(this,w),R=0;break}}this.h=R,this.o+=v},r.prototype.v=function(){var A=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);A[0]=128;for(var v=1;v<A.length-8;++v)A[v]=0;var C=8*this.o;for(v=A.length-8;v<A.length;++v)A[v]=C&255,C/=256;for(this.u(A),A=Array(16),v=C=0;4>v;++v)for(var w=0;32>w;w+=8)A[C++]=this.g[v]>>>w&255;return A};function o(A,v){var C=a;return Object.prototype.hasOwnProperty.call(C,A)?C[A]:C[A]=v(A)}function s(A,v){this.h=v;for(var C=[],w=!0,R=A.length-1;0<=R;R--){var O=A[R]|0;w&&O==v||(C[R]=O,w=!1)}this.g=C}var a={};function c(A){return-128<=A&&128>A?o(A,function(v){return new s([v|0],0>v?-1:0)}):new s([A|0],0>A?-1:0)}function l(A){if(isNaN(A)||!isFinite(A))return h;if(0>A)return S(l(-A));for(var v=[],C=1,w=0;A>=C;w++)v[w]=A/C|0,C*=4294967296;return new s(v,0)}function d(A,v){if(A.length==0)throw Error("number format error: empty string");if(v=v||10,2>v||36<v)throw Error("radix out of range: "+v);if(A.charAt(0)=="-")return S(d(A.substring(1),v));if(0<=A.indexOf("-"))throw Error('number format error: interior "-" character');for(var C=l(Math.pow(v,8)),w=h,R=0;R<A.length;R+=8){var O=Math.min(8,A.length-R),D=parseInt(A.substring(R,R+O),v);8>O?(O=l(Math.pow(v,O)),w=w.j(O).add(l(D))):(w=w.j(C),w=w.add(l(D)))}return w}var h=c(0),f=c(1),g=c(16777216);t=s.prototype,t.m=function(){if(I(this))return-S(this).m();for(var A=0,v=1,C=0;C<this.g.length;C++){var w=this.i(C);A+=(0<=w?w:4294967296+w)*v,v*=4294967296}return A},t.toString=function(A){if(A=A||10,2>A||36<A)throw Error("radix out of range: "+A);if(E(this))return"0";if(I(this))return"-"+S(this).toString(A);for(var v=l(Math.pow(A,6)),C=this,w="";;){var R=te(C,v).g;C=L(C,R.j(v));var O=((0<C.g.length?C.g[0]:C.h)>>>0).toString(A);if(C=R,E(C))return O+w;for(;6>O.length;)O="0"+O;w=O+w}},t.i=function(A){return 0>A?0:A<this.g.length?this.g[A]:this.h};function E(A){if(A.h!=0)return!1;for(var v=0;v<A.g.length;v++)if(A.g[v]!=0)return!1;return!0}function I(A){return A.h==-1}t.l=function(A){return A=L(this,A),I(A)?-1:E(A)?0:1};function S(A){for(var v=A.g.length,C=[],w=0;w<v;w++)C[w]=~A.g[w];return new s(C,~A.h).add(f)}t.abs=function(){return I(this)?S(this):this},t.add=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0,R=0;R<=v;R++){var O=w+(this.i(R)&65535)+(A.i(R)&65535),D=(O>>>16)+(this.i(R)>>>16)+(A.i(R)>>>16);w=D>>>16,O&=65535,D&=65535,C[R]=D<<16|O}return new s(C,C[C.length-1]&-2147483648?-1:0)};function L(A,v){return A.add(S(v))}t.j=function(A){if(E(this)||E(A))return h;if(I(this))return I(A)?S(this).j(S(A)):S(S(this).j(A));if(I(A))return S(this.j(S(A)));if(0>this.l(g)&&0>A.l(g))return l(this.m()*A.m());for(var v=this.g.length+A.g.length,C=[],w=0;w<2*v;w++)C[w]=0;for(w=0;w<this.g.length;w++)for(var R=0;R<A.g.length;R++){var O=this.i(w)>>>16,D=this.i(w)&65535,Mr=A.i(R)>>>16,Jr=A.i(R)&65535;C[2*w+2*R]+=D*Jr,j(C,2*w+2*R),C[2*w+2*R+1]+=O*Jr,j(C,2*w+2*R+1),C[2*w+2*R+1]+=D*Mr,j(C,2*w+2*R+1),C[2*w+2*R+2]+=O*Mr,j(C,2*w+2*R+2)}for(w=0;w<v;w++)C[w]=C[2*w+1]<<16|C[2*w];for(w=v;w<2*v;w++)C[w]=0;return new s(C,0)};function j(A,v){for(;(A[v]&65535)!=A[v];)A[v+1]+=A[v]>>>16,A[v]&=65535,v++}function K(A,v){this.g=A,this.h=v}function te(A,v){if(E(v))throw Error("division by zero");if(E(A))return new K(h,h);if(I(A))return v=te(S(A),v),new K(S(v.g),S(v.h));if(I(v))return v=te(A,S(v)),new K(S(v.g),v.h);if(30<A.g.length){if(I(A)||I(v))throw Error("slowDivide_ only works with positive integers.");for(var C=f,w=v;0>=w.l(A);)C=pe(C),w=pe(w);var R=ie(C,1),O=ie(w,1);for(w=ie(w,2),C=ie(C,2);!E(w);){var D=O.add(w);0>=D.l(A)&&(R=R.add(C),O=D),w=ie(w,1),C=ie(C,1)}return v=L(A,R.j(v)),new K(R,v)}for(R=h;0<=A.l(v);){for(C=Math.max(1,Math.floor(A.m()/v.m())),w=Math.ceil(Math.log(C)/Math.LN2),w=48>=w?1:Math.pow(2,w-48),O=l(C),D=O.j(v);I(D)||0<D.l(A);)C-=w,O=l(C),D=O.j(v);E(O)&&(O=f),R=R.add(O),A=L(A,D)}return new K(R,A)}t.A=function(A){return te(this,A).h},t.and=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)&A.i(w);return new s(C,this.h&A.h)},t.or=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)|A.i(w);return new s(C,this.h|A.h)},t.xor=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)^A.i(w);return new s(C,this.h^A.h)};function pe(A){for(var v=A.g.length+1,C=[],w=0;w<v;w++)C[w]=A.i(w)<<1|A.i(w-1)>>>31;return new s(C,A.h)}function ie(A,v){var C=v>>5;v%=32;for(var w=A.g.length-C,R=[],O=0;O<w;O++)R[O]=0<v?A.i(O+C)>>>v|A.i(O+C+1)<<32-v:A.i(O+C);return new s(R,A.h)}r.prototype.digest=r.prototype.v,r.prototype.reset=r.prototype.s,r.prototype.update=r.prototype.u,jb=f$.Md5=r,s.prototype.add=s.prototype.add,s.prototype.multiply=s.prototype.j,s.prototype.modulo=s.prototype.A,s.prototype.compare=s.prototype.l,s.prototype.toNumber=s.prototype.m,s.prototype.toString=s.prototype.toString,s.prototype.getBits=s.prototype.i,s.fromNumber=l,s.fromString=d,is=f$.Integer=s}).apply(typeof h$<"u"?h$:typeof self<"u"?self:typeof window<"u"?window:{});var EI=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},os={};var Hb,pse,Gd,$b,Tg,_I,Wb,zb,qb;(function(){var t,e=typeof Object.defineProperties=="function"?Object.defineProperty:function(u,p,m){return u==Array.prototype||u==Object.prototype||(u[p]=m.value),u};function n(u){u=[typeof globalThis=="object"&&globalThis,u,typeof window=="object"&&window,typeof self=="object"&&self,typeof EI=="object"&&EI];for(var p=0;p<u.length;++p){var m=u[p];if(m&&m.Math==Math)return m}throw Error("Cannot find global object")}var r=n(this);function i(u,p){if(p)e:{var m=r;u=u.split(".");for(var _=0;_<u.length-1;_++){var M=u[_];if(!(M in m))break e;m=m[M]}u=u[u.length-1],_=m[u],p=p(_),p!=_&&p!=null&&e(m,u,{configurable:!0,writable:!0,value:p})}}function o(u,p){u instanceof String&&(u+="");var m=0,_=!1,M={next:function(){if(!_&&m<u.length){var F=m++;return{value:p(F,u[F]),done:!1}}return _=!0,{done:!0,value:void 0}}};return M[Symbol.iterator]=function(){return M},M}i("Array.prototype.values",function(u){return u||function(){return o(this,function(p,m){return m})}});var s=s||{},a=this||self;function c(u){var p=typeof u;return p=p!="object"?p:u?Array.isArray(u)?"array":p:"null",p=="array"||p=="object"&&typeof u.length=="number"}function l(u){var p=typeof u;return p=="object"&&u!=null||p=="function"}function d(u,p,m){return u.call.apply(u.bind,arguments)}function h(u,p,m){if(!u)throw Error();if(2<arguments.length){var _=Array.prototype.slice.call(arguments,2);return function(){var M=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(M,_),u.apply(p,M)}}return function(){return u.apply(p,arguments)}}function f(u,p,m){return f=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?d:h,f.apply(null,arguments)}function g(u,p){var m=Array.prototype.slice.call(arguments,1);return function(){var _=m.slice();return _.push.apply(_,arguments),u.apply(this,_)}}function E(u,p){function m(){}m.prototype=p.prototype,u.aa=p.prototype,u.prototype=new m,u.prototype.constructor=u,u.Qb=function(_,M,F){for(var Q=Array(arguments.length-2),it=2;it<arguments.length;it++)Q[it-2]=arguments[it];return p.prototype[M].apply(_,Q)}}function I(u){let p=u.length;if(0<p){let m=Array(p);for(let _=0;_<p;_++)m[_]=u[_];return m}return[]}function S(u,p){for(let m=1;m<arguments.length;m++){let _=arguments[m];if(c(_)){let M=u.length||0,F=_.length||0;u.length=M+F;for(let Q=0;Q<F;Q++)u[M+Q]=_[Q]}else u.push(_)}}class L{constructor(p,m){this.i=p,this.j=m,this.h=0,this.g=null}get(){let p;return 0<this.h?(this.h--,p=this.g,this.g=p.next,p.next=null):p=this.i(),p}}function j(u){return/^[\s\xa0]*$/.test(u)}function K(){var u=a.navigator;return u&&(u=u.userAgent)?u:""}function te(u){return te[" "](u),u}te[" "]=function(){};var pe=K().indexOf("Gecko")!=-1&&!(K().toLowerCase().indexOf("webkit")!=-1&&K().indexOf("Edge")==-1)&&!(K().indexOf("Trident")!=-1||K().indexOf("MSIE")!=-1)&&K().indexOf("Edge")==-1;function ie(u,p,m){for(let _ in u)p.call(m,u[_],_,u)}function A(u,p){for(let m in u)p.call(void 0,u[m],m,u)}function v(u){let p={};for(let m in u)p[m]=u[m];return p}let C="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function w(u,p){let m,_;for(let M=1;M<arguments.length;M++){_=arguments[M];for(m in _)u[m]=_[m];for(let F=0;F<C.length;F++)m=C[F],Object.prototype.hasOwnProperty.call(_,m)&&(u[m]=_[m])}}function R(u){var p=1;u=u.split(":");let m=[];for(;0<p&&u.length;)m.push(u.shift()),p--;return u.length&&m.push(u.join(":")),m}function O(u){a.setTimeout(()=>{throw u},0)}function D(){var u=Lh;let p=null;return u.g&&(p=u.g,u.g=u.g.next,u.g||(u.h=null),p.next=null),p}class Mr{constructor(){this.h=this.g=null}add(p,m){let _=Jr.get();_.set(p,m),this.h?this.h.next=_:this.g=_,this.h=_}}var Jr=new L(()=>new _m,u=>u.reset());class _m{constructor(){this.next=this.g=this.h=null}set(p,m){this.h=p,this.g=m,this.next=null}reset(){this.next=this.g=this.h=null}}let Lr,Pa=!1,Lh=new Mr,xa=()=>{let u=a.Promise.resolve(void 0);Lr=()=>{u.then(Ph)}};var Ph=()=>{for(var u;u=D();){try{u.h.call(u.g)}catch(m){O(m)}var p=Jr;p.j(u),100>p.h&&(p.h++,u.next=p.g,p.g=u)}Pa=!1};function Zr(){this.s=this.s,this.C=this.C}Zr.prototype.s=!1,Zr.prototype.ma=function(){this.s||(this.s=!0,this.N())},Zr.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function tn(u,p){this.type=u,this.g=this.target=p,this.defaultPrevented=!1}tn.prototype.h=function(){this.defaultPrevented=!0};var Kv=(function(){if(!a.addEventListener||!Object.defineProperty)return!1;var u=!1,p=Object.defineProperty({},"passive",{get:function(){u=!0}});try{let m=()=>{};a.addEventListener("test",m,p),a.removeEventListener("test",m,p)}catch{}return u})();function ka(u,p){if(tn.call(this,u?u.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,u){var m=this.type=u.type,_=u.changedTouches&&u.changedTouches.length?u.changedTouches[0]:null;if(this.target=u.target||u.srcElement,this.g=p,p=u.relatedTarget){if(pe){e:{try{te(p.nodeName);var M=!0;break e}catch{}M=!1}M||(p=null)}}else m=="mouseover"?p=u.fromElement:m=="mouseout"&&(p=u.toElement);this.relatedTarget=p,_?(this.clientX=_.clientX!==void 0?_.clientX:_.pageX,this.clientY=_.clientY!==void 0?_.clientY:_.pageY,this.screenX=_.screenX||0,this.screenY=_.screenY||0):(this.clientX=u.clientX!==void 0?u.clientX:u.pageX,this.clientY=u.clientY!==void 0?u.clientY:u.pageY,this.screenX=u.screenX||0,this.screenY=u.screenY||0),this.button=u.button,this.key=u.key||"",this.ctrlKey=u.ctrlKey,this.altKey=u.altKey,this.shiftKey=u.shiftKey,this.metaKey=u.metaKey,this.pointerId=u.pointerId||0,this.pointerType=typeof u.pointerType=="string"?u.pointerType:nt[u.pointerType]||"",this.state=u.state,this.i=u,u.defaultPrevented&&ka.aa.h.call(this)}}E(ka,tn);var nt={2:"touch",3:"pen",4:"mouse"};ka.prototype.h=function(){ka.aa.h.call(this);var u=this.i;u.preventDefault?u.preventDefault():u.returnValue=!1};var Fa="closure_listenable_"+(1e6*Math.random()|0),Yv=0;function Xv(u,p,m,_,M){this.listener=u,this.proxy=null,this.src=p,this.type=m,this.capture=!!_,this.ha=M,this.key=++Yv,this.da=this.fa=!1}function zl(u){u.da=!0,u.listener=null,u.proxy=null,u.src=null,u.ha=null}function ql(u){this.src=u,this.g={},this.h=0}ql.prototype.add=function(u,p,m,_,M){var F=u.toString();u=this.g[F],u||(u=this.g[F]=[],this.h++);var Q=Kl(u,p,_,M);return-1<Q?(p=u[Q],m||(p.fa=!1)):(p=new Xv(p,this.src,F,!!_,M),p.fa=m,u.push(p)),p};function xh(u,p){var m=p.type;if(m in u.g){var _=u.g[m],M=Array.prototype.indexOf.call(_,p,void 0),F;(F=0<=M)&&Array.prototype.splice.call(_,M,1),F&&(zl(p),u.g[m].length==0&&(delete u.g[m],u.h--))}}function Kl(u,p,m,_){for(var M=0;M<u.length;++M){var F=u[M];if(!F.da&&F.listener==p&&F.capture==!!m&&F.ha==_)return M}return-1}var kh="closure_lm_"+(1e6*Math.random()|0),Yl={};function rt(u,p,m,_,M){if(_&&_.once)return Ql(u,p,m,_,M);if(Array.isArray(p)){for(var F=0;F<p.length;F++)rt(u,p[F],m,_,M);return null}return m=Zl(m),u&&u[Fa]?u.K(p,m,l(_)?!!_.capture:!!_,M):Xl(u,p,m,!1,_,M)}function Xl(u,p,m,_,M,F){if(!p)throw Error("Invalid event type");var Q=l(M)?!!M.capture:!!M,it=Jl(u);if(it||(u[kh]=it=new ql(u)),m=it.add(p,m,_,Q,F),m.proxy)return m;if(_=lt(),m.proxy=_,_.src=u,_.listener=m,u.addEventListener)Kv||(M=Q),M===void 0&&(M=!1),u.addEventListener(p.toString(),_,M);else if(u.attachEvent)u.attachEvent(Fh(p.toString()),_);else if(u.addListener&&u.removeListener)u.addListener(_);else throw Error("addEventListener and attachEvent are unavailable.");return m}function lt(){function u(m){return p.call(u.src,u.listener,m)}let p=wi;return u}function Ql(u,p,m,_,M){if(Array.isArray(p)){for(var F=0;F<p.length;F++)Ql(u,p[F],m,_,M);return null}return m=Zl(m),u&&u[Fa]?u.L(p,m,l(_)?!!_.capture:!!_,M):Xl(u,p,m,!0,_,M)}function ur(u,p,m,_,M){if(Array.isArray(p))for(var F=0;F<p.length;F++)ur(u,p[F],m,_,M);else _=l(_)?!!_.capture:!!_,m=Zl(m),u&&u[Fa]?(u=u.i,p=String(p).toString(),p in u.g&&(F=u.g[p],m=Kl(F,m,_,M),-1<m&&(zl(F[m]),Array.prototype.splice.call(F,m,1),F.length==0&&(delete u.g[p],u.h--)))):u&&(u=Jl(u))&&(p=u.g[p.toString()],u=-1,p&&(u=Kl(p,m,_,M)),(m=-1<u?p[u]:null)&&So(m))}function So(u){if(typeof u!="number"&&u&&!u.da){var p=u.src;if(p&&p[Fa])xh(p.i,u);else{var m=u.type,_=u.proxy;p.removeEventListener?p.removeEventListener(m,_,u.capture):p.detachEvent?p.detachEvent(Fh(m),_):p.addListener&&p.removeListener&&p.removeListener(_),(m=Jl(p))?(xh(m,u),m.h==0&&(m.src=null,p[kh]=null)):zl(u)}}}function Fh(u){return u in Yl?Yl[u]:Yl[u]="on"+u}function wi(u,p){if(u.da)u=!0;else{p=new ka(p,this);var m=u.listener,_=u.ha||u.src;u.fa&&So(u),u=m.call(_,p)}return u}function Jl(u){return u=u[kh],u instanceof ql?u:null}var Ua="__closure_events_fn_"+(1e9*Math.random()>>>0);function Zl(u){return typeof u=="function"?u:(u[Ua]||(u[Ua]=function(p){return u.handleEvent(p)}),u[Ua])}function bt(){Zr.call(this),this.i=new ql(this),this.M=this,this.F=null}E(bt,Zr),bt.prototype[Fa]=!0,bt.prototype.removeEventListener=function(u,p,m,_){ur(this,u,p,m,_)};function dt(u,p){var m,_=u.F;if(_)for(m=[];_;_=_.F)m.push(_);if(u=u.M,_=p.type||p,typeof p=="string")p=new tn(p,u);else if(p instanceof tn)p.target=p.target||u;else{var M=p;p=new tn(_,u),w(p,M)}if(M=!0,m)for(var F=m.length-1;0<=F;F--){var Q=p.g=m[F];M=Pr(Q,_,!0,p)&&M}if(Q=p.g=u,M=Pr(Q,_,!0,p)&&M,M=Pr(Q,_,!1,p)&&M,m)for(F=0;F<m.length;F++)Q=p.g=m[F],M=Pr(Q,_,!1,p)&&M}bt.prototype.N=function(){if(bt.aa.N.call(this),this.i){var u=this.i,p;for(p in u.g){for(var m=u.g[p],_=0;_<m.length;_++)zl(m[_]);delete u.g[p],u.h--}}this.F=null},bt.prototype.K=function(u,p,m,_){return this.i.add(String(u),p,!1,m,_)},bt.prototype.L=function(u,p,m,_){return this.i.add(String(u),p,!0,m,_)};function Pr(u,p,m,_){if(p=u.i.g[String(p)],!p)return!0;p=p.concat();for(var M=!0,F=0;F<p.length;++F){var Q=p[F];if(Q&&!Q.da&&Q.capture==m){var it=Q.listener,mn=Q.ha||Q.src;Q.fa&&xh(u.i,Q),M=it.call(mn,_)!==!1&&M}}return M&&!_.defaultPrevented}function bi(u,p,m){if(typeof u=="function")m&&(u=f(u,m));else if(u&&typeof u.handleEvent=="function")u=f(u.handleEvent,u);else throw Error("Invalid listener argument");return 2147483647<Number(p)?-1:a.setTimeout(u,p||0)}function eu(u){u.g=bi(()=>{u.g=null,u.i&&(u.i=!1,eu(u))},u.l);let p=u.h;u.h=null,u.m.apply(null,p)}class tu extends Zr{constructor(p,m){super(),this.m=p,this.l=m,this.h=null,this.i=!1,this.g=null}j(p){this.h=arguments,this.g?this.i=!0:eu(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Oi(u){Zr.call(this),this.h=u,this.g={}}E(Oi,Zr);var nu=[];function Ao(u){ie(u.g,function(p,m){this.g.hasOwnProperty(m)&&So(p)},u),u.g={}}Oi.prototype.N=function(){Oi.aa.N.call(this),Ao(this)},Oi.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var hs=a.JSON.stringify,ru=a.JSON.parse,Tm=class{stringify(u){return a.JSON.stringify(u,void 0)}parse(u){return a.JSON.parse(u,void 0)}};function iu(){}iu.prototype.h=null;function Uh(u){return u.h||(u.h=u.i())}function ou(){}var Co={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function ei(){tn.call(this,"d")}E(ei,tn);function Mi(){tn.call(this,"c")}E(Mi,tn);var Gn={},Vh=null;function Va(){return Vh=Vh||new bt}Gn.La="serverreachability";function Bh(u){tn.call(this,Gn.La,u)}E(Bh,tn);function fs(u){let p=Va();dt(p,new Bh(p))}Gn.STAT_EVENT="statevent";function Gh(u,p){tn.call(this,Gn.STAT_EVENT,u),this.stat=p}E(Gh,tn);function Ot(u){let p=Va();dt(p,new Gh(p,u))}Gn.Ma="timingevent";function Ba(u,p){tn.call(this,Gn.Ma,u),this.size=p}E(Ba,tn);function An(u,p){if(typeof u!="function")throw Error("Fn must not be null and must be a function");return a.setTimeout(function(){u()},p)}function xr(){this.g=!0}xr.prototype.xa=function(){this.g=!1};function jh(u,p,m,_,M,F){u.info(function(){if(u.g)if(F)for(var Q="",it=F.split("&"),mn=0;mn<it.length;mn++){var Ve=it[mn].split("=");if(1<Ve.length){var Cn=Ve[0];Ve=Ve[1];var Dn=Cn.split("_");Q=2<=Dn.length&&Dn[1]=="type"?Q+(Cn+"="+Ve+"&"):Q+(Cn+"=redacted&")}}else Q=null;else Q=F;return"XMLHTTP REQ ("+_+") [attempt "+M+"]: "+p+`
|
|
153
|
+
FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(let n of this.listens.values())for(let r of n.values())this.sendListen_(r);for(let n=0;n<this.outstandingPuts_.length;n++)this.outstandingPuts_[n]&&this.sendPut_(n);for(;this.onDisconnectRequestQueue_.length;){let n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let n=0;n<this.outstandingGets_.length;n++)this.outstandingGets_[n]&&this.sendGet_(n)}sendConnectStats_(){let n={},r="js";co()&&(this.repoInfo_.nodeAdmin?r="admin_node":r="node"),n["sdk."+r+"."+ub.replace(/\./g,"-")]=1,_p()?n["framework.cordova"]=1:qT()&&(n["framework.reactnative"]=1),this.reportStats(n)}shouldReconnect_(){let n=Oy.getInstance().currentlyOnline();return Tp(this.interruptReasons_)&&n}}t.nextPersistentConnectionId_=0,t.nextConnectionId_=0;return t})(),Le=class t{constructor(e,n){this.name=e,this.node=n}static Wrap(e,n){return new t(e,n)}};var Rd=class{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,n){let r=new Le(ul,e),i=new Le(ul,n);return this.compare(r,i)!==0}minPost(){return Le.MIN}};var Ay,My=class extends Rd{static get __EMPTY_NODE(){return Ay}static set __EMPTY_NODE(e){Ay=e}compare(e,n){return ml(e.name,n.name)}isDefinedOn(e){throw zc("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,n){return!1}minPost(){return Le.MIN}maxPost(){return new Le(sa,Ay)}makePost(e,n){return Y(typeof e=="string","KeyIndex indexValue must always be a string."),new Le(e,Ay)}toString(){return".key"}},ll=new My;var Cd=class{constructor(e,n,r,i,o=null){this.isReverse_=i,this.resultGenerator_=o,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(e=e,s=n?r(e.key,n):1,i&&(s*=-1),s<0)this.isReverse_?e=e.left:e=e.right;else if(s===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(),n;if(this.resultGenerator_?n=this.resultGenerator_(e.key,e.value):n={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 n}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}},Ii=(()=>{class t{constructor(n,r,i,o,s){this.key=n,this.value=r,this.color=i??t.RED,this.left=o??Xr.EMPTY_NODE,this.right=s??Xr.EMPTY_NODE}copy(n,r,i,o,s){return new t(n??this.key,r??this.value,i??this.color,o??this.left,s??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(n){return this.left.inorderTraversal(n)||!!n(this.key,this.value)||this.right.inorderTraversal(n)}reverseTraversal(n){return this.right.reverseTraversal(n)||n(this.key,this.value)||this.left.reverseTraversal(n)}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(n,r,i){let o=this,s=i(n,o.key);return s<0?o=o.copy(null,null,null,o.left.insert(n,r,i),null):s===0?o=o.copy(null,r,null,null,null):o=o.copy(null,null,null,null,o.right.insert(n,r,i)),o.fixUp_()}removeMin_(){if(this.left.isEmpty())return Xr.EMPTY_NODE;let n=this;return!n.left.isRed_()&&!n.left.left.isRed_()&&(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.removeMin_(),null),n.fixUp_()}remove(n,r){let i,o;if(i=this,r(n,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(n,r),null);else{if(i.left.isRed_()&&(i=i.rotateRight_()),!i.right.isEmpty()&&!i.right.isRed_()&&!i.right.left.isRed_()&&(i=i.moveRedRight_()),r(n,i.key)===0){if(i.right.isEmpty())return Xr.EMPTY_NODE;o=i.right.min_(),i=i.copy(o.key,o.value,null,null,i.right.removeMin_())}i=i.copy(null,null,null,null,i.right.remove(n,r))}return i.fixUp_()}isRed_(){return this.color}fixUp_(){let n=this;return n.right.isRed_()&&!n.left.isRed_()&&(n=n.rotateLeft_()),n.left.isRed_()&&n.left.left.isRed_()&&(n=n.rotateRight_()),n.left.isRed_()&&n.right.isRed_()&&(n=n.colorFlip_()),n}moveRedLeft_(){let n=this.colorFlip_();return n.right.left.isRed_()&&(n=n.copy(null,null,null,null,n.right.rotateRight_()),n=n.rotateLeft_(),n=n.colorFlip_()),n}moveRedRight_(){let n=this.colorFlip_();return n.left.left.isRed_()&&(n=n.rotateRight_(),n=n.colorFlip_()),n}rotateLeft_(){let n=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,n,null)}rotateRight_(){let n=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,n)}colorFlip_(){let n=this.left.copy(null,null,!this.left.color,null,null),r=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,n,r)}checkMaxDepth_(){let n=this.check_();return Math.pow(2,n)<=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");let n=this.left.check_();if(n!==this.right.check_())throw new Error("Black depths differ");return n+(this.isRed_()?0:1)}}return t.RED=!0,t.BLACK=!1,t})(),Cw=class{copy(e,n,r,i,o){return this}insert(e,n,r){return new Ii(e,n,null)}remove(e,n){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}},Xr=class t{constructor(e,n=t.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new t(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,Ii.BLACK,null,null))}remove(e){return new t(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ii.BLACK,null,null))}get(e){let n,r=this.root_;for(;!r.isEmpty();){if(n=this.comparator_(e,r.key),n===0)return r.value;n<0?r=r.left:n>0&&(r=r.right)}return null}getPredecessorKey(e){let n,r=this.root_,i=null;for(;!r.isEmpty();)if(n=this.comparator_(e,r.key),n===0){if(r.left.isEmpty())return i?i.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}else n<0?r=r.left:n>0&&(i=r,r=r.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 Cd(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new Cd(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new Cd(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new Cd(this.root_,null,this.comparator_,!0,e)}};Xr.EMPTY_NODE=new Cw;function aie(t,e){return ml(t.name,e.name)}function mb(t,e){return ml(t,e)}var Dw;function cie(t){Dw=t}var Qj=function(t){return typeof t=="number"?"number:"+Mj(t):"string:"+t},Jj=function(t){if(t.isLeafNode()){let e=t.val();Y(typeof e=="string"||typeof e=="number"||typeof e=="object"&&zr(e,".sv"),"Priority must be a string or number.")}else Y(t===Dw||t.isEmpty(),"priority of unexpected type.");Y(t===Dw||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};var uj,Nd=(()=>{class t{static set __childrenNodeConstructor(n){uj=n}static get __childrenNodeConstructor(){return uj}constructor(n,r=t.__childrenNodeConstructor.EMPTY_NODE){this.value_=n,this.priorityNode_=r,this.lazyHash_=null,Y(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),Jj(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(n){return new t(this.value_,n)}getImmediateChild(n){return n===".priority"?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE}getChild(n){return Oe(n)?this:be(n)===".priority"?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(n,r){return null}updateImmediateChild(n,r){return n===".priority"?this.updatePriority(r):r.isEmpty()&&n!==".priority"?this:t.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(n,r).updatePriority(this.priorityNode_)}updateChild(n,r){let i=be(n);return i===null?r:r.isEmpty()&&i!==".priority"?this:(Y(i!==".priority"||aa(n)===1,".priority must be the last token in a path"),this.updateImmediateChild(i,t.__childrenNodeConstructor.EMPTY_NODE.updateChild(ct(n),r)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(n,r){return!1}val(n){return n&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let n="";this.priorityNode_.isEmpty()||(n+="priority:"+Qj(this.priorityNode_.val())+":");let r=typeof this.value_;n+=r+":",r==="number"?n+=Mj(this.value_):n+=this.value_,this.lazyHash_=bj(n)}return this.lazyHash_}getValue(){return this.value_}compareTo(n){return n===t.__childrenNodeConstructor.EMPTY_NODE?1:n instanceof t.__childrenNodeConstructor?-1:(Y(n.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(n))}compareToLeafNode_(n){let r=typeof n.value_,i=typeof this.value_,o=t.VALUE_TYPE_ORDER.indexOf(r),s=t.VALUE_TYPE_ORDER.indexOf(i);return Y(o>=0,"Unknown leaf type: "+r),Y(s>=0,"Unknown leaf type: "+i),o===s?i==="object"?0:this.value_<n.value_?-1:this.value_===n.value_?0:1:s-o}withIndex(){return this}isIndexed(){return!0}equals(n){if(n===this)return!0;if(n.isLeafNode()){let r=n;return this.value_===r.value_&&this.priorityNode_.equals(r.priorityNode_)}else return!1}}t.VALUE_TYPE_ORDER=["object","boolean","number","string"];return t})(),Zj,eH;function lie(t){Zj=t}function uie(t){eH=t}var Rw=class extends Rd{compare(e,n){let r=e.node.getPriority(),i=n.node.getPriority(),o=r.compareTo(i);return o===0?ml(e.name,n.name):o}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,n){return!e.getPriority().equals(n.getPriority())}minPost(){return Le.MIN}maxPost(){return new Le(sa,new Nd("[PRIORITY-POST]",eH))}makePost(e,n){let r=Zj(e);return new Le(n,new Nd("[PRIORITY-POST]",r))}toString(){return".priority"}},ht=new Rw;var die=Math.log(2),Nw=class{constructor(e){let n=o=>parseInt(Math.log(o)/die,10),r=o=>parseInt(Array(o+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;let i=r(this.count);this.bits_=e+1&i}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}},Ly=function(t,e,n,r){t.sort(e);let i=function(c,l){let d=l-c,h,f;if(d===0)return null;if(d===1)return h=t[c],f=n?n(h):h,new Ii(f,h.node,Ii.BLACK,null,null);{let g=parseInt(d/2,10)+c,E=i(c,g),I=i(g+1,l);return h=t[g],f=n?n(h):h,new Ii(f,h.node,Ii.BLACK,E,I)}},o=function(c){let l=null,d=null,h=t.length,f=function(E,I){let S=h-E,L=h;h-=E;let j=i(S+1,L),K=t[S],te=n?n(K):K;g(new Ii(te,K.node,I,null,j))},g=function(E){l?(l.left=E,l=E):(d=E,l=E)};for(let E=0;E<c.count;++E){let I=c.nextBitIsOne(),S=Math.pow(2,c.count-(E+1));I?f(S,Ii.BLACK):(f(S,Ii.BLACK),f(S,Ii.RED))}return d},s=new Nw(t.length),a=o(s);return new Xr(r||e,a)};var cw,Sd={},wd=class t{static get Default(){return Y(Sd&&ht,"ChildrenNode.ts has not been loaded"),cw=cw||new t({".priority":Sd},{".priority":ht}),cw}constructor(e,n){this.indexes_=e,this.indexSet_=n}get(e){let n=$s(this.indexes_,e);if(!n)throw new Error("No index defined for "+e);return n instanceof Xr?n:null}hasIndex(e){return zr(this.indexSet_,e.toString())}addIndex(e,n){Y(e!==ll,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let r=[],i=!1,o=n.getIterator(Le.Wrap),s=o.getNext();for(;s;)i=i||e.isDefinedOn(s.node),r.push(s),s=o.getNext();let a;i?a=Ly(r,e.getCompare()):a=Sd;let c=e.toString(),l=Object.assign({},this.indexSet_);l[c]=e;let d=Object.assign({},this.indexes_);return d[c]=a,new t(d,l)}addToIndexes(e,n){let r=yp(this.indexes_,(i,o)=>{let s=$s(this.indexSet_,o);if(Y(s,"Missing index implementation for "+o),i===Sd)if(s.isDefinedOn(e.node)){let a=[],c=n.getIterator(Le.Wrap),l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),Ly(a,s.getCompare())}else return Sd;else{let a=n.get(e.name),c=i;return a&&(c=c.remove(new Le(e.name,a))),c.insert(e,e.node)}});return new t(r,this.indexSet_)}removeFromIndexes(e,n){let r=yp(this.indexes_,i=>{if(i===Sd)return i;{let o=n.get(e.name);return o?i.remove(new Le(e.name,o)):i}});return new t(r,this.indexSet_)}};var Hp,ve=(()=>{class t{static get EMPTY_NODE(){return Hp||(Hp=new t(new Xr(mb),null,wd.Default))}constructor(n,r,i){this.children_=n,this.priorityNode_=r,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&Jj(this.priorityNode_),this.children_.isEmpty()&&Y(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Hp}updatePriority(n){return this.children_.isEmpty()?this:new t(this.children_,n,this.indexMap_)}getImmediateChild(n){if(n===".priority")return this.getPriority();{let r=this.children_.get(n);return r===null?Hp:r}}getChild(n){let r=be(n);return r===null?this:this.getImmediateChild(r).getChild(ct(n))}hasChild(n){return this.children_.get(n)!==null}updateImmediateChild(n,r){if(Y(r,"We should always be passing snapshot nodes"),n===".priority")return this.updatePriority(r);{let i=new Le(n,r),o,s;r.isEmpty()?(o=this.children_.remove(n),s=this.indexMap_.removeFromIndexes(i,this.children_)):(o=this.children_.insert(n,r),s=this.indexMap_.addToIndexes(i,this.children_));let a=o.isEmpty()?Hp:this.priorityNode_;return new t(o,a,s)}}updateChild(n,r){let i=be(n);if(i===null)return r;{Y(be(n)!==".priority"||aa(n)===1,".priority must be the last token in a path");let o=this.getImmediateChild(i).updateChild(ct(n),r);return this.updateImmediateChild(i,o)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;let r={},i=0,o=0,s=!0;if(this.forEachChild(ht,(a,c)=>{r[a]=c.val(n),i++,s&&t.INTEGER_REGEXP_.test(a)?o=Math.max(o,Number(a)):s=!1}),!n&&s&&o<2*i){let a=[];for(let c in r)a[c]=r[c];return a}else return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(this.lazyHash_===null){let n="";this.getPriority().isEmpty()||(n+="priority:"+Qj(this.getPriority().val())+":"),this.forEachChild(ht,(r,i)=>{let o=i.hash();o!==""&&(n+=":"+r+":"+o)}),this.lazyHash_=n===""?"":bj(n)}return this.lazyHash_}getPredecessorChildName(n,r,i){let o=this.resolveIndex_(i);if(o){let s=o.getPredecessorKey(new Le(n,r));return s?s.name:null}else return this.children_.getPredecessorKey(n)}getFirstChildName(n){let r=this.resolveIndex_(n);if(r){let i=r.minKey();return i&&i.name}else return this.children_.minKey()}getFirstChild(n){let r=this.getFirstChildName(n);return r?new Le(r,this.children_.get(r)):null}getLastChildName(n){let r=this.resolveIndex_(n);if(r){let i=r.maxKey();return i&&i.name}else return this.children_.maxKey()}getLastChild(n){let r=this.getLastChildName(n);return r?new Le(r,this.children_.get(r)):null}forEachChild(n,r){let i=this.resolveIndex_(n);return i?i.inorderTraversal(o=>r(o.name,o.node)):this.children_.inorderTraversal(r)}getIterator(n){return this.getIteratorFrom(n.minPost(),n)}getIteratorFrom(n,r){let i=this.resolveIndex_(r);if(i)return i.getIteratorFrom(n,o=>o);{let o=this.children_.getIteratorFrom(n.name,Le.Wrap),s=o.peek();for(;s!=null&&r.compare(s,n)<0;)o.getNext(),s=o.peek();return o}}getReverseIterator(n){return this.getReverseIteratorFrom(n.maxPost(),n)}getReverseIteratorFrom(n,r){let i=this.resolveIndex_(r);if(i)return i.getReverseIteratorFrom(n,o=>o);{let o=this.children_.getReverseIteratorFrom(n.name,Le.Wrap),s=o.peek();for(;s!=null&&r.compare(s,n)>0;)o.getNext(),s=o.peek();return o}}compareTo(n){return this.isEmpty()?n.isEmpty()?0:-1:n.isLeafNode()||n.isEmpty()?1:n===ug?-1:0}withIndex(n){if(n===ll||this.indexMap_.hasIndex(n))return this;{let r=this.indexMap_.addIndex(n,this.children_);return new t(this.children_,this.priorityNode_,r)}}isIndexed(n){return n===ll||this.indexMap_.hasIndex(n)}equals(n){if(n===this)return!0;if(n.isLeafNode())return!1;{let r=n;if(this.getPriority().equals(r.getPriority()))if(this.children_.count()===r.children_.count()){let i=this.getIterator(ht),o=r.getIterator(ht),s=i.getNext(),a=o.getNext();for(;s&&a;){if(s.name!==a.name||!s.node.equals(a.node))return!1;s=i.getNext(),a=o.getNext()}return s===null&&a===null}else return!1;else return!1}}resolveIndex_(n){return n===ll?null:this.indexMap_.get(n.toString())}}return t.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,t})(),ww=class extends ve{constructor(){super(new Xr(mb),ve.EMPTY_NODE,wd.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ve.EMPTY_NODE}isEmpty(){return!1}},ug=new ww;Object.defineProperties(Le,{MIN:{value:new Le(ul,ve.EMPTY_NODE)},MAX:{value:new Le(sa,ug)}});My.__EMPTY_NODE=ve.EMPTY_NODE;Nd.__childrenNodeConstructor=ve;cie(ug);uie(ug);var hie=!0;function St(t,e=null){if(t===null)return ve.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),Y(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){let n=t;return new Nd(n,St(e))}if(!(t instanceof Array)&&hie){let n=[],r=!1;if(un(t,(s,a)=>{if(s.substring(0,1)!=="."){let c=St(a);c.isEmpty()||(r=r||!c.getPriority().isEmpty(),n.push(new Le(s,c)))}}),n.length===0)return ve.EMPTY_NODE;let o=Ly(n,aie,s=>s.name,mb);if(r){let s=Ly(n,ht.getCompare());return new ve(o,St(e),new wd({".priority":s},{".priority":ht}))}else return new ve(o,St(e),wd.Default)}else{let n=ve.EMPTY_NODE;return un(t,(r,i)=>{if(zr(t,r)&&r.substring(0,1)!=="."){let o=St(i);(o.isLeafNode()||!o.isEmpty())&&(n=n.updateImmediateChild(r,o))}}),n.updatePriority(St(e))}}lie(St);var Qp=class extends Rd{constructor(e){super(),this.indexPath_=e,Y(!Oe(e)&&be(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,n){let r=this.extractChild(e.node),i=this.extractChild(n.node),o=r.compareTo(i);return o===0?ml(e.name,n.name):o}makePost(e,n){let r=St(e),i=ve.EMPTY_NODE.updateChild(this.indexPath_,r);return new Le(n,i)}maxPost(){let e=ve.EMPTY_NODE.updateChild(this.indexPath_,ug);return new Le(sa,e)}toString(){return Xp(this.indexPath_,0).join("/")}};var bw=class extends Rd{compare(e,n){let r=e.node.compareTo(n.node);return r===0?ml(e.name,n.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return Le.MIN}maxPost(){return Le.MAX}makePost(e,n){let r=St(e);return new Le(n,r)}toString(){return".value"}},tH=new bw;function nH(t){return{type:"value",snapshotNode:t}}function bd(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function Jp(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function Zp(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function fie(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}var eg=class{constructor(e){this.index_=e}updateChild(e,n,r,i,o,s){Y(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let a=e.getImmediateChild(n);return a.getChild(i).equals(r.getChild(i))&&a.isEmpty()===r.isEmpty()||(s!=null&&(r.isEmpty()?e.hasChild(n)?s.trackChildChange(Jp(n,a)):Y(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(bd(n,r)):s.trackChildChange(Zp(n,r,a))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(n,r).withIndex(this.index_)}updateFullNode(e,n,r){return r!=null&&(e.isLeafNode()||e.forEachChild(ht,(i,o)=>{n.hasChild(i)||r.trackChildChange(Jp(i,o))}),n.isLeafNode()||n.forEachChild(ht,(i,o)=>{if(e.hasChild(i)){let s=e.getImmediateChild(i);s.equals(o)||r.trackChildChange(Zp(i,o,s))}else r.trackChildChange(bd(i,o))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?ve.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}};var Py=class t{constructor(e){this.indexedFilter_=new eg(e.getIndex()),this.index_=e.getIndex(),this.startPost_=t.getStartPost_(e),this.endPost_=t.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&r}updateChild(e,n,r,i,o,s){return this.matches(new Le(n,r))||(r=ve.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,r,i,o,s)}updateFullNode(e,n,r){n.isLeafNode()&&(n=ve.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(ve.EMPTY_NODE);let o=this;return n.forEachChild(ht,(s,a)=>{o.matches(new Le(s,a))||(i=i.updateImmediateChild(s,ve.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){let n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){let n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}};var Ow=class{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{let r=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?r<=0:r<0},this.withinEndPost=n=>{let r=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?r<=0:r<0},this.rangedFilter_=new Py(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,r,i,o,s){return this.rangedFilter_.matches(new Le(n,r))||(r=ve.EMPTY_NODE),e.getImmediateChild(n).equals(r)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,n,r,i,o,s):this.fullLimitUpdateChild_(e,n,r,o,s)}updateFullNode(e,n,r){let i;if(n.isLeafNode()||n.isEmpty())i=ve.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<n.numChildren()&&n.isIndexed(this.index_)){i=ve.EMPTY_NODE.withIndex(this.index_);let o;this.reverse_?o=n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):o=n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let s=0;for(;o.hasNext()&&s<this.limit_;){let a=o.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))i=i.updateImmediateChild(a.name,a.node),s++;else break;else continue}}else{i=n.withIndex(this.index_),i=i.updatePriority(ve.EMPTY_NODE);let o;this.reverse_?o=i.getReverseIterator(this.index_):o=i.getIterator(this.index_);let s=0;for(;o.hasNext();){let a=o.getNext();s<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?s++:i=i.updateImmediateChild(a.name,ve.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,n,r,i,o){let s;if(this.reverse_){let h=this.index_.getCompare();s=(f,g)=>h(g,f)}else s=this.index_.getCompare();let a=e;Y(a.numChildren()===this.limit_,"");let c=new Le(n,r),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),d=this.rangedFilter_.matches(c);if(a.hasChild(n)){let h=a.getImmediateChild(n),f=i.getChildAfterChild(this.index_,l,this.reverse_);for(;f!=null&&(f.name===n||a.hasChild(f.name));)f=i.getChildAfterChild(this.index_,f,this.reverse_);let g=f==null?1:s(f,c);if(d&&!r.isEmpty()&&g>=0)return o?.trackChildChange(Zp(n,r,h)),a.updateImmediateChild(n,r);{o?.trackChildChange(Jp(n,h));let I=a.updateImmediateChild(n,ve.EMPTY_NODE);return f!=null&&this.rangedFilter_.matches(f)?(o?.trackChildChange(bd(f.name,f.node)),I.updateImmediateChild(f.name,f.node)):I}}else return r.isEmpty()?e:d&&s(l,c)>=0?(o!=null&&(o.trackChildChange(Jp(l.name,l.node)),o.trackChildChange(bd(n,r))),a.updateImmediateChild(n,r).updateImmediateChild(l.name,ve.EMPTY_NODE)):e}};var Mw=class t{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_=ht}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return Y(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Y(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:ul}hasEnd(){return this.endSet_}getIndexEndValue(){return Y(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Y(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:sa}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return Y(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_===ht}copy(){let e=new t;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 pie(t){return t.loadsAllData()?new eg(t.getIndex()):t.hasLimit()?new Ow(t):new Py(t)}function gie(t,e){let n=t.copy();return n.limitSet_=!0,n.limit_=e,n.viewFrom_="r",n}function mie(t,e,n){let r=t.copy();return r.startSet_=!0,e===void 0&&(e=null),r.indexStartValue_=e,n!=null?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function Eie(t,e,n){let r=t.copy();return r.endSet_=!0,e===void 0&&(e=null),r.indexEndValue_=e,n!==void 0?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function _ie(t,e){let n=t.copy();return n.index_=e,n}function dj(t){let e={};if(t.isDefault())return e;let n;if(t.index_===ht?n="$priority":t.index_===tH?n="$value":t.index_===ll?n="$key":(Y(t.index_ instanceof Qp,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Pt(n),t.startSet_){let r=t.startAfterSet_?"startAfter":"startAt";e[r]=Pt(t.indexStartValue_),t.startNameSet_&&(e[r]+=","+Pt(t.indexStartName_))}if(t.endSet_){let r=t.endBeforeSet_?"endBefore":"endAt";e[r]=Pt(t.indexEndValue_),t.endNameSet_&&(e[r]+=","+Pt(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function hj(t){let e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==ht&&(e.i=t.index_.toString()),e}var Lw=class t extends wy{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(Y(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,n,r,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=r,this.appCheckTokenProvider_=i,this.log_=lg("p:rest:"),this.listens_={}}listen(e,n,r,i){let o=e._path.toString();this.log_("Listen called for "+o+" "+e._queryIdentifier);let s=t.getListenId_(e,r),a={};this.listens_[s]=a;let c=dj(e._queryParams);this.restRequest_(o+".json",c,(l,d)=>{let h=d;if(l===404&&(h=null,l=null),l===null&&this.onDataUpdate_(o,h,!1,r),$s(this.listens_,s)===a){let f;l?l===401?f="permission_denied":f="rest_error:"+l:f="ok",i(f,null)}})}unlisten(e,n){let r=t.getListenId_(e,n);delete this.listens_[r]}get(e){let n=dj(e._queryParams),r=e._path.toString(),i=new an;return this.restRequest_(r+".json",n,(o,s)=>{let a=s;o===404&&(a=null,o=null),o===null?(this.onDataUpdate_(r,a,!1,null),i.resolve(a)):i.reject(new Error(a))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},r){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,o])=>{i&&i.accessToken&&(n.auth=i.accessToken),o&&o.token&&(n.ac=o.token);let s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+Ip(n);this.log_("Sending REST request for "+s);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(r&&a.readyState===4){this.log_("REST Response for "+s+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=hd(a.responseText)}catch{Fn("Failed to parse JSON response for "+s+": "+a.responseText)}r(null,c)}else a.status!==401&&a.status!==404&&Fn("Got unsuccessful REST response for "+s+" Status: "+a.status),r(a.status);r=null}},a.open("GET",s,!0),a.send()})}};var Pw=class{constructor(){this.rootNode_=ve.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}};function xy(){return{value:null,children:new Map}}function kd(t,e,n){if(Oe(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{let r=be(e);t.children.has(r)||t.children.set(r,xy());let i=t.children.get(r);e=ct(e),kd(i,e,n)}}function xw(t,e){if(Oe(e))return t.value=null,t.children.clear(),!0;if(t.value!==null){if(t.value.isLeafNode())return!1;{let n=t.value;return t.value=null,n.forEachChild(ht,(r,i)=>{kd(t,new He(r),i)}),xw(t,e)}}else if(t.children.size>0){let n=be(e);return e=ct(e),t.children.has(n)&&xw(t.children.get(n),e)&&t.children.delete(n),t.children.size===0}else return!0}function kw(t,e,n){t.value!==null?n(e,t.value):Tie(t,(r,i)=>{let o=new He(e.toString()+"/"+r);kw(i,o,n)})}function Tie(t,e){t.children.forEach((n,r)=>{e(r,n)})}var Fw=class{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),n=Object.assign({},e);return this.last_&&un(this.last_,(r,i)=>{n[r]=n[r]-i}),this.last_=e,n}};var fj=10*1e3,yie=30*1e3,Iie=300*1e3,Uw=class{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new Fw(e);let r=fj+(yie-fj)*Math.random();Wp(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){let e=this.statsListener_.get(),n={},r=!1;un(e,(i,o)=>{o>0&&zr(this.statsToReport_,i)&&(n[i]=o,r=!0)}),r&&this.server_.reportStats(n),Wp(this.reportStats_.bind(this),Math.floor(Math.random()*2*Iie))}};var po=(function(t){return t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE",t})(po||{});function Eb(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function _b(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Tb(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}var Vw=class t{constructor(e,n,r){this.path=e,this.affectedTree=n,this.revert=r,this.type=po.ACK_USER_WRITE,this.source=Eb()}operationForChild(e){if(Oe(this.path)){if(this.affectedTree.value!=null)return Y(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let n=this.affectedTree.subtree(new He(e));return new t(je(),n,this.revert)}}else return Y(be(this.path)===e,"operationForChild called for unrelated child."),new t(ct(this.path),this.affectedTree,this.revert)}};var ky=class t{constructor(e,n){this.source=e,this.path=n,this.type=po.LISTEN_COMPLETE}operationForChild(e){return Oe(this.path)?new t(this.source,je()):new t(this.source,ct(this.path))}};var Od=class t{constructor(e,n,r){this.source=e,this.path=n,this.snap=r,this.type=po.OVERWRITE}operationForChild(e){return Oe(this.path)?new t(this.source,je(),this.snap.getImmediateChild(e)):new t(this.source,ct(this.path),this.snap)}};var tg=class t{constructor(e,n,r){this.source=e,this.path=n,this.children=r,this.type=po.MERGE}operationForChild(e){if(Oe(this.path)){let n=this.children.subtree(new He(e));return n.isEmpty()?null:n.value?new Od(this.source,je(),n.value):new t(this.source,je(),n)}else return Y(be(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new t(this.source,ct(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}};var go=class{constructor(e,n,r){this.node_=e,this.fullyInitialized_=n,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Oe(e))return this.isFullyInitialized()&&!this.filtered_;let n=be(e);return this.isCompleteForChild(n)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}};var Bw=class{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}};function vie(t,e,n,r){let i=[],o=[];return e.forEach(s=>{s.type==="child_changed"&&t.index_.indexedValueChanged(s.oldSnap,s.snapshotNode)&&o.push(fie(s.childName,s.snapshotNode))}),$p(t,i,"child_removed",e,r,n),$p(t,i,"child_added",e,r,n),$p(t,i,"child_moved",o,r,n),$p(t,i,"child_changed",e,r,n),$p(t,i,"value",e,r,n),i}function $p(t,e,n,r,i,o){let s=r.filter(a=>a.type===n);s.sort((a,c)=>Aie(t,a,c)),s.forEach(a=>{let c=Sie(t,a,o);i.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,t.query_))})})}function Sie(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function Aie(t,e,n){if(e.childName==null||n.childName==null)throw zc("Should only compare child_ events.");let r=new Le(e.childName,e.snapshotNode),i=new Le(n.childName,n.snapshotNode);return t.index_.compare(r,i)}function Qy(t,e){return{eventCache:t,serverCache:e}}function qp(t,e,n,r){return Qy(new go(e,n,r),t.serverCache)}function rH(t,e,n,r){return Qy(t.eventCache,new go(e,n,r))}function Fy(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function dl(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}var lw,Cie=()=>(lw||(lw=new Xr(Sre)),lw),Yn=class t{static fromObject(e){let n=new t(null);return un(e,(r,i)=>{n=n.set(new He(r),i)}),n}constructor(e,n=Cie()){this.value=e,this.children=n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:je(),value:this.value};if(Oe(e))return null;{let r=be(e),i=this.children.get(r);if(i!==null){let o=i.findRootMostMatchingPathAndValue(ct(e),n);return o!=null?{path:At(new He(r),o.path),value:o.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(Oe(e))return this;{let n=be(e),r=this.children.get(n);return r!==null?r.subtree(ct(e)):new t(null)}}set(e,n){if(Oe(e))return new t(n,this.children);{let r=be(e),o=(this.children.get(r)||new t(null)).set(ct(e),n),s=this.children.insert(r,o);return new t(this.value,s)}}remove(e){if(Oe(e))return this.children.isEmpty()?new t(null):new t(null,this.children);{let n=be(e),r=this.children.get(n);if(r){let i=r.remove(ct(e)),o;return i.isEmpty()?o=this.children.remove(n):o=this.children.insert(n,i),this.value===null&&o.isEmpty()?new t(null):new t(this.value,o)}else return this}}get(e){if(Oe(e))return this.value;{let n=be(e),r=this.children.get(n);return r?r.get(ct(e)):null}}setTree(e,n){if(Oe(e))return n;{let r=be(e),o=(this.children.get(r)||new t(null)).setTree(ct(e),n),s;return o.isEmpty()?s=this.children.remove(r):s=this.children.insert(r,o),new t(this.value,s)}}fold(e){return this.fold_(je(),e)}fold_(e,n){let r={};return this.children.inorderTraversal((i,o)=>{r[i]=o.fold_(At(e,i),n)}),n(e,this.value,r)}findOnPath(e,n){return this.findOnPath_(e,je(),n)}findOnPath_(e,n,r){let i=this.value?r(n,this.value):!1;if(i)return i;if(Oe(e))return null;{let o=be(e),s=this.children.get(o);return s?s.findOnPath_(ct(e),At(n,o),r):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,je(),n)}foreachOnPath_(e,n,r){if(Oe(e))return this;{this.value&&r(n,this.value);let i=be(e),o=this.children.get(i);return o?o.foreachOnPath_(ct(e),At(n,i),r):new t(null)}}foreach(e){this.foreach_(je(),e)}foreach_(e,n){this.children.inorderTraversal((r,i)=>{i.foreach_(At(e,r),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,r)=>{r.value&&e(n,r.value)})}};var vi=class t{constructor(e){this.writeTree_=e}static empty(){return new t(new Yn(null))}};function Kp(t,e,n){if(Oe(e))return new vi(new Yn(n));{let r=t.writeTree_.findRootMostValueAndPath(e);if(r!=null){let i=r.path,o=r.value,s=Kn(i,e);return o=o.updateChild(s,n),new vi(t.writeTree_.set(i,o))}else{let i=new Yn(n),o=t.writeTree_.setTree(e,i);return new vi(o)}}}function Gw(t,e,n){let r=t;return un(n,(i,o)=>{r=Kp(r,At(e,i),o)}),r}function pj(t,e){if(Oe(e))return vi.empty();{let n=t.writeTree_.setTree(e,new Yn(null));return new vi(n)}}function jw(t,e){return El(t,e)!=null}function El(t,e){let n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(Kn(n.path,e)):null}function gj(t){let e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(ht,(r,i)=>{e.push(new Le(r,i))}):t.writeTree_.children.inorderTraversal((r,i)=>{i.value!=null&&e.push(new Le(r,i.value))}),e}function ia(t,e){if(Oe(e))return t;{let n=El(t,e);return n!=null?new vi(new Yn(n)):new vi(t.writeTree_.subtree(e))}}function Hw(t){return t.writeTree_.isEmpty()}function Md(t,e){return iH(je(),t.writeTree_,e)}function iH(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let r=null;return e.children.inorderTraversal((i,o)=>{i===".priority"?(Y(o.value!==null,"Priority writes must always be leaf nodes"),r=o.value):n=iH(At(t,i),o,n)}),!n.getChild(t).isEmpty()&&r!==null&&(n=n.updateChild(At(t,".priority"),r)),n}}function Jy(t,e){return cH(e,t)}function Die(t,e,n,r,i){Y(r>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:r,visible:i}),i&&(t.visibleWrites=Kp(t.visibleWrites,e,n)),t.lastWriteId=r}function Rie(t,e,n,r){Y(r>t.lastWriteId,"Stacking an older merge on top of newer ones"),t.allWrites.push({path:e,children:n,writeId:r,visible:!0}),t.visibleWrites=Gw(t.visibleWrites,e,n),t.lastWriteId=r}function Nie(t,e){for(let n=0;n<t.allWrites.length;n++){let r=t.allWrites[n];if(r.writeId===e)return r}return null}function wie(t,e){let n=t.allWrites.findIndex(a=>a.writeId===e);Y(n>=0,"removeWrite called with nonexistent writeId.");let r=t.allWrites[n];t.allWrites.splice(n,1);let i=r.visible,o=!1,s=t.allWrites.length-1;for(;i&&s>=0;){let a=t.allWrites[s];a.visible&&(s>=n&&bie(a,r.path)?i=!1:Yr(r.path,a.path)&&(o=!0)),s--}if(i){if(o)return Oie(t),!0;if(r.snap)t.visibleWrites=pj(t.visibleWrites,r.path);else{let a=r.children;un(a,c=>{t.visibleWrites=pj(t.visibleWrites,At(r.path,c))})}return!0}else return!1}function bie(t,e){if(t.snap)return Yr(t.path,e);for(let n in t.children)if(t.children.hasOwnProperty(n)&&Yr(At(t.path,n),e))return!0;return!1}function Oie(t){t.visibleWrites=oH(t.allWrites,Mie,je()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function Mie(t){return t.visible}function oH(t,e,n){let r=vi.empty();for(let i=0;i<t.length;++i){let o=t[i];if(e(o)){let s=o.path,a;if(o.snap)Yr(n,s)?(a=Kn(n,s),r=Kp(r,a,o.snap)):Yr(s,n)&&(a=Kn(s,n),r=Kp(r,je(),o.snap.getChild(a)));else if(o.children){if(Yr(n,s))a=Kn(n,s),r=Gw(r,a,o.children);else if(Yr(s,n))if(a=Kn(s,n),Oe(a))r=Gw(r,je(),o.children);else{let c=$s(o.children,be(a));if(c){let l=c.getChild(ct(a));r=Kp(r,je(),l)}}}else throw zc("WriteRecord should have .snap or .children")}}return r}function sH(t,e,n,r,i){if(!r&&!i){let o=El(t.visibleWrites,e);if(o!=null)return o;{let s=ia(t.visibleWrites,e);if(Hw(s))return n;if(n==null&&!jw(s,je()))return null;{let a=n||ve.EMPTY_NODE;return Md(s,a)}}}else{let o=ia(t.visibleWrites,e);if(!i&&Hw(o))return n;if(!i&&n==null&&!jw(o,je()))return null;{let s=function(l){return(l.visible||i)&&(!r||!~r.indexOf(l.writeId))&&(Yr(l.path,e)||Yr(e,l.path))},a=oH(t.allWrites,s,e),c=n||ve.EMPTY_NODE;return Md(a,c)}}}function Lie(t,e,n){let r=ve.EMPTY_NODE,i=El(t.visibleWrites,e);if(i)return i.isLeafNode()||i.forEachChild(ht,(o,s)=>{r=r.updateImmediateChild(o,s)}),r;if(n){let o=ia(t.visibleWrites,e);return n.forEachChild(ht,(s,a)=>{let c=Md(ia(o,new He(s)),a);r=r.updateImmediateChild(s,c)}),gj(o).forEach(s=>{r=r.updateImmediateChild(s.name,s.node)}),r}else{let o=ia(t.visibleWrites,e);return gj(o).forEach(s=>{r=r.updateImmediateChild(s.name,s.node)}),r}}function Pie(t,e,n,r,i){Y(r||i,"Either existingEventSnap or existingServerSnap must exist");let o=At(e,n);if(jw(t.visibleWrites,o))return null;{let s=ia(t.visibleWrites,o);return Hw(s)?i.getChild(n):Md(s,i.getChild(n))}}function xie(t,e,n,r){let i=At(e,n),o=El(t.visibleWrites,i);if(o!=null)return o;if(r.isCompleteForChild(n)){let s=ia(t.visibleWrites,i);return Md(s,r.getNode().getImmediateChild(n))}else return null}function kie(t,e){return El(t.visibleWrites,e)}function Fie(t,e,n,r,i,o,s){let a,c=ia(t.visibleWrites,e),l=El(c,je());if(l!=null)a=l;else if(n!=null)a=Md(c,n);else return[];if(a=a.withIndex(s),!a.isEmpty()&&!a.isLeafNode()){let d=[],h=s.getCompare(),f=o?a.getReverseIteratorFrom(r,s):a.getIteratorFrom(r,s),g=f.getNext();for(;g&&d.length<i;)h(g,r)!==0&&d.push(g),g=f.getNext();return d}else return[]}function Uie(){return{visibleWrites:vi.empty(),allWrites:[],lastWriteId:-1}}function Uy(t,e,n,r){return sH(t.writeTree,t.treePath,e,n,r)}function yb(t,e){return Lie(t.writeTree,t.treePath,e)}function mj(t,e,n,r){return Pie(t.writeTree,t.treePath,e,n,r)}function Vy(t,e){return kie(t.writeTree,At(t.treePath,e))}function Vie(t,e,n,r,i,o){return Fie(t.writeTree,t.treePath,e,n,r,i,o)}function Ib(t,e,n){return xie(t.writeTree,t.treePath,e,n)}function aH(t,e){return cH(At(t.treePath,e),t.writeTree)}function cH(t,e){return{treePath:t,writeTree:e}}var $w=class{constructor(){this.changeMap=new Map}trackChildChange(e){let n=e.type,r=e.childName;Y(n==="child_added"||n==="child_changed"||n==="child_removed","Only child changes supported for tracking"),Y(r!==".priority","Only non-priority child changes can be tracked.");let i=this.changeMap.get(r);if(i){let o=i.type;if(n==="child_added"&&o==="child_removed")this.changeMap.set(r,Zp(r,e.snapshotNode,i.snapshotNode));else if(n==="child_removed"&&o==="child_added")this.changeMap.delete(r);else if(n==="child_removed"&&o==="child_changed")this.changeMap.set(r,Jp(r,i.oldSnap));else if(n==="child_changed"&&o==="child_added")this.changeMap.set(r,bd(r,e.snapshotNode));else if(n==="child_changed"&&o==="child_changed")this.changeMap.set(r,Zp(r,e.snapshotNode,i.oldSnap));else throw zc("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}};var Ww=class{getCompleteChild(e){return null}getChildAfterChild(e,n,r){return null}},lH=new Ww,ng=class{constructor(e,n,r=null){this.writes_=e,this.viewCache_=n,this.optCompleteServerCache_=r}getCompleteChild(e){let n=this.viewCache_.eventCache;if(n.isCompleteForChild(e))return n.getNode().getImmediateChild(e);{let r=this.optCompleteServerCache_!=null?new go(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Ib(this.writes_,e,r)}}getChildAfterChild(e,n,r){let i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:dl(this.viewCache_),o=Vie(this.writes_,i,n,1,r,e);return o.length===0?null:o[0]}};function Bie(t){return{filter:t}}function Gie(t,e){Y(e.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),Y(e.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed")}function jie(t,e,n,r,i){let o=new $w,s,a;if(n.type===po.OVERWRITE){let l=n;l.source.fromUser?s=zw(t,e,l.path,l.snap,r,i,o):(Y(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!Oe(l.path),s=By(t,e,l.path,l.snap,r,i,a,o))}else if(n.type===po.MERGE){let l=n;l.source.fromUser?s=$ie(t,e,l.path,l.children,r,i,o):(Y(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),s=qw(t,e,l.path,l.children,r,i,a,o))}else if(n.type===po.ACK_USER_WRITE){let l=n;l.revert?s=qie(t,e,l.path,r,i,o):s=Wie(t,e,l.path,l.affectedTree,r,i,o)}else if(n.type===po.LISTEN_COMPLETE)s=zie(t,e,n.path,r,o);else throw zc("Unknown operation type: "+n.type);let c=o.getChanges();return Hie(e,s,c),{viewCache:s,changes:c}}function Hie(t,e,n){let r=e.eventCache;if(r.isFullyInitialized()){let i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=Fy(t);(n.length>0||!t.eventCache.isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(nH(Fy(e)))}}function uH(t,e,n,r,i,o){let s=e.eventCache;if(Vy(r,n)!=null)return e;{let a,c;if(Oe(n))if(Y(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){let l=dl(e),d=l instanceof ve?l:ve.EMPTY_NODE,h=yb(r,d);a=t.filter.updateFullNode(e.eventCache.getNode(),h,o)}else{let l=Uy(r,dl(e));a=t.filter.updateFullNode(e.eventCache.getNode(),l,o)}else{let l=be(n);if(l===".priority"){Y(aa(n)===1,"Can't have a priority with additional path components");let d=s.getNode();c=e.serverCache.getNode();let h=mj(r,n,d,c);h!=null?a=t.filter.updatePriority(d,h):a=s.getNode()}else{let d=ct(n),h;if(s.isCompleteForChild(l)){c=e.serverCache.getNode();let f=mj(r,n,s.getNode(),c);f!=null?h=s.getNode().getImmediateChild(l).updateChild(d,f):h=s.getNode().getImmediateChild(l)}else h=Ib(r,l,e.serverCache);h!=null?a=t.filter.updateChild(s.getNode(),l,h,d,i,o):a=s.getNode()}}return qp(e,a,s.isFullyInitialized()||Oe(n),t.filter.filtersNodes())}}function By(t,e,n,r,i,o,s,a){let c=e.serverCache,l,d=s?t.filter:t.filter.getIndexedFilter();if(Oe(n))l=d.updateFullNode(c.getNode(),r,null);else if(d.filtersNodes()&&!c.isFiltered()){let g=c.getNode().updateChild(n,r);l=d.updateFullNode(c.getNode(),g,null)}else{let g=be(n);if(!c.isCompleteForPath(n)&&aa(n)>1)return e;let E=ct(n),S=c.getNode().getImmediateChild(g).updateChild(E,r);g===".priority"?l=d.updatePriority(c.getNode(),S):l=d.updateChild(c.getNode(),g,S,E,lH,null)}let h=rH(e,l,c.isFullyInitialized()||Oe(n),d.filtersNodes()),f=new ng(i,h,o);return uH(t,h,n,i,f,a)}function zw(t,e,n,r,i,o,s){let a=e.eventCache,c,l,d=new ng(i,e,o);if(Oe(n))l=t.filter.updateFullNode(e.eventCache.getNode(),r,s),c=qp(e,l,!0,t.filter.filtersNodes());else{let h=be(n);if(h===".priority")l=t.filter.updatePriority(e.eventCache.getNode(),r),c=qp(e,l,a.isFullyInitialized(),a.isFiltered());else{let f=ct(n),g=a.getNode().getImmediateChild(h),E;if(Oe(f))E=r;else{let I=d.getCompleteChild(h);I!=null?fb(f)===".priority"&&I.getChild(Yj(f)).isEmpty()?E=I:E=I.updateChild(f,r):E=ve.EMPTY_NODE}if(g.equals(E))c=e;else{let I=t.filter.updateChild(a.getNode(),h,E,f,d,s);c=qp(e,I,a.isFullyInitialized(),t.filter.filtersNodes())}}}return c}function Ej(t,e){return t.eventCache.isCompleteForChild(e)}function $ie(t,e,n,r,i,o,s){let a=e;return r.foreach((c,l)=>{let d=At(n,c);Ej(e,be(d))&&(a=zw(t,a,d,l,i,o,s))}),r.foreach((c,l)=>{let d=At(n,c);Ej(e,be(d))||(a=zw(t,a,d,l,i,o,s))}),a}function _j(t,e,n){return n.foreach((r,i)=>{e=e.updateChild(r,i)}),e}function qw(t,e,n,r,i,o,s,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;Oe(n)?l=r:l=new Yn(null).setTree(n,r);let d=e.serverCache.getNode();return l.children.inorderTraversal((h,f)=>{if(d.hasChild(h)){let g=e.serverCache.getNode().getImmediateChild(h),E=_j(t,g,f);c=By(t,c,new He(h),E,i,o,s,a)}}),l.children.inorderTraversal((h,f)=>{let g=!e.serverCache.isCompleteForChild(h)&&f.value===null;if(!d.hasChild(h)&&!g){let E=e.serverCache.getNode().getImmediateChild(h),I=_j(t,E,f);c=By(t,c,new He(h),I,i,o,s,a)}}),c}function Wie(t,e,n,r,i,o,s){if(Vy(i,n)!=null)return e;let a=e.serverCache.isFiltered(),c=e.serverCache;if(r.value!=null){if(Oe(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return By(t,e,n,c.getNode().getChild(n),i,o,a,s);if(Oe(n)){let l=new Yn(null);return c.getNode().forEachChild(ll,(d,h)=>{l=l.set(new He(d),h)}),qw(t,e,n,l,i,o,a,s)}else return e}else{let l=new Yn(null);return r.foreach((d,h)=>{let f=At(n,d);c.isCompleteForPath(f)&&(l=l.set(d,c.getNode().getChild(f)))}),qw(t,e,n,l,i,o,a,s)}}function zie(t,e,n,r,i){let o=e.serverCache,s=rH(e,o.getNode(),o.isFullyInitialized()||Oe(n),o.isFiltered());return uH(t,s,n,r,lH,i)}function qie(t,e,n,r,i,o){let s;if(Vy(r,n)!=null)return e;{let a=new ng(r,e,i),c=e.eventCache.getNode(),l;if(Oe(n)||be(n)===".priority"){let d;if(e.serverCache.isFullyInitialized())d=Uy(r,dl(e));else{let h=e.serverCache.getNode();Y(h instanceof ve,"serverChildren would be complete if leaf node"),d=yb(r,h)}d=d,l=t.filter.updateFullNode(c,d,o)}else{let d=be(n),h=Ib(r,d,e.serverCache);h==null&&e.serverCache.isCompleteForChild(d)&&(h=c.getImmediateChild(d)),h!=null?l=t.filter.updateChild(c,d,h,ct(n),a,o):e.eventCache.getNode().hasChild(d)?l=t.filter.updateChild(c,d,ve.EMPTY_NODE,ct(n),a,o):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(s=Uy(r,dl(e)),s.isLeafNode()&&(l=t.filter.updateFullNode(l,s,o)))}return s=e.serverCache.isFullyInitialized()||Vy(r,je())!=null,qp(e,l,s,t.filter.filtersNodes())}}var Kw=class{constructor(e,n){this.query_=e,this.eventRegistrations_=[];let r=this.query_._queryParams,i=new eg(r.getIndex()),o=pie(r);this.processor_=Bie(o);let s=n.serverCache,a=n.eventCache,c=i.updateFullNode(ve.EMPTY_NODE,s.getNode(),null),l=o.updateFullNode(ve.EMPTY_NODE,a.getNode(),null),d=new go(c,s.isFullyInitialized(),i.filtersNodes()),h=new go(l,a.isFullyInitialized(),o.filtersNodes());this.viewCache_=Qy(h,d),this.eventGenerator_=new Bw(this.query_)}get query(){return this.query_}};function Kie(t){return t.viewCache_.serverCache.getNode()}function Yie(t){return Fy(t.viewCache_)}function Xie(t,e){let n=dl(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!Oe(e)&&!n.getImmediateChild(be(e)).isEmpty())?n.getChild(e):null}function Tj(t){return t.eventRegistrations_.length===0}function Qie(t,e){t.eventRegistrations_.push(e)}function yj(t,e,n){let r=[];if(n){Y(e==null,"A cancel should cancel all event registrations.");let i=t.query._path;t.eventRegistrations_.forEach(o=>{let s=o.createCancelEvent(n,i);s&&r.push(s)})}if(e){let i=[];for(let o=0;o<t.eventRegistrations_.length;++o){let s=t.eventRegistrations_[o];if(!s.matches(e))i.push(s);else if(e.hasAnyCallback()){i=i.concat(t.eventRegistrations_.slice(o+1));break}}t.eventRegistrations_=i}else t.eventRegistrations_=[];return r}function Ij(t,e,n,r){e.type===po.MERGE&&e.source.queryId!==null&&(Y(dl(t.viewCache_),"We should always have a full cache before handling merges"),Y(Fy(t.viewCache_),"Missing event cache, even though we have a server cache"));let i=t.viewCache_,o=jie(t.processor_,i,e,n,r);return Gie(t.processor_,o.viewCache),Y(o.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),t.viewCache_=o.viewCache,dH(t,o.changes,o.viewCache.eventCache.getNode(),null)}function Jie(t,e){let n=t.viewCache_.eventCache,r=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(ht,(o,s)=>{r.push(bd(o,s))}),n.isFullyInitialized()&&r.push(nH(n.getNode())),dH(t,r,n.getNode(),e)}function dH(t,e,n,r){let i=r?[r]:t.eventRegistrations_;return vie(t.eventGenerator_,e,n,i)}var Gy,jy=class{constructor(){this.views=new Map}};function Zie(t){Y(!Gy,"__referenceConstructor has already been defined"),Gy=t}function eoe(){return Y(Gy,"Reference.ts has not been loaded"),Gy}function toe(t){return t.views.size===0}function vb(t,e,n,r){let i=e.source.queryId;if(i!==null){let o=t.views.get(i);return Y(o!=null,"SyncTree gave us an op for an invalid query."),Ij(o,e,n,r)}else{let o=[];for(let s of t.views.values())o=o.concat(Ij(s,e,n,r));return o}}function hH(t,e,n,r,i){let o=e._queryIdentifier,s=t.views.get(o);if(!s){let a=Uy(n,i?r:null),c=!1;a?c=!0:r instanceof ve?(a=yb(n,r),c=!1):(a=ve.EMPTY_NODE,c=!1);let l=Qy(new go(a,c,!1),new go(r,i,!1));return new Kw(e,l)}return s}function noe(t,e,n,r,i,o){let s=hH(t,e,r,i,o);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,s),Qie(s,n),Jie(s,n)}function roe(t,e,n,r){let i=e._queryIdentifier,o=[],s=[],a=ca(t);if(i==="default")for(let[c,l]of t.views.entries())s=s.concat(yj(l,n,r)),Tj(l)&&(t.views.delete(c),l.query._queryParams.loadsAllData()||o.push(l.query));else{let c=t.views.get(i);c&&(s=s.concat(yj(c,n,r)),Tj(c)&&(t.views.delete(i),c.query._queryParams.loadsAllData()||o.push(c.query)))}return a&&!ca(t)&&o.push(new(eoe())(e._repo,e._path)),{removed:o,events:s}}function fH(t){let e=[];for(let n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function oa(t,e){let n=null;for(let r of t.views.values())n=n||Xie(r,e);return n}function pH(t,e){if(e._queryParams.loadsAllData())return Zy(t);{let r=e._queryIdentifier;return t.views.get(r)}}function gH(t,e){return pH(t,e)!=null}function ca(t){return Zy(t)!=null}function Zy(t){for(let e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}var Hy;function ioe(t){Y(!Hy,"__referenceConstructor has already been defined"),Hy=t}function ooe(){return Y(Hy,"Reference.ts has not been loaded"),Hy}var soe=1,$y=class{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Yn(null),this.pendingWriteTree_=Uie(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}};function Sb(t,e,n,r,i){return Die(t.pendingWriteTree_,e,n,r,i),i?Fd(t,new Od(Eb(),e,n)):[]}function aoe(t,e,n,r){Rie(t.pendingWriteTree_,e,n,r);let i=Yn.fromObject(n);return Fd(t,new tg(Eb(),e,i))}function na(t,e,n=!1){let r=Nie(t.pendingWriteTree_,e);if(wie(t.pendingWriteTree_,e)){let o=new Yn(null);return r.snap!=null?o=o.set(je(),!0):un(r.children,s=>{o=o.set(new He(s),!0)}),Fd(t,new Vw(r.path,o,n))}else return[]}function dg(t,e,n){return Fd(t,new Od(_b(),e,n))}function coe(t,e,n){let r=Yn.fromObject(n);return Fd(t,new tg(_b(),e,r))}function loe(t,e){return Fd(t,new ky(_b(),e))}function uoe(t,e,n){let r=Ab(t,n);if(r){let i=Cb(r),o=i.path,s=i.queryId,a=Kn(o,e),c=new ky(Tb(s),a);return Db(t,o,c)}else return[]}function Wy(t,e,n,r,i=!1){let o=e._path,s=t.syncPointTree_.get(o),a=[];if(s&&(e._queryIdentifier==="default"||gH(s,e))){let c=roe(s,e,n,r);toe(s)&&(t.syncPointTree_=t.syncPointTree_.remove(o));let l=c.removed;if(a=c.events,!i){let d=l.findIndex(f=>f._queryParams.loadsAllData())!==-1,h=t.syncPointTree_.findOnPath(o,(f,g)=>ca(g));if(d&&!h){let f=t.syncPointTree_.subtree(o);if(!f.isEmpty()){let g=foe(f);for(let E=0;E<g.length;++E){let I=g[E],S=I.query,L=TH(t,I);t.listenProvider_.startListening(Yp(S),rg(t,S),L.hashFn,L.onComplete)}}}!h&&l.length>0&&!r&&(d?t.listenProvider_.stopListening(Yp(e),null):l.forEach(f=>{let g=t.queryToTagMap.get(tI(f));t.listenProvider_.stopListening(Yp(f),g)}))}poe(t,l)}return a}function mH(t,e,n,r){let i=Ab(t,r);if(i!=null){let o=Cb(i),s=o.path,a=o.queryId,c=Kn(s,e),l=new Od(Tb(a),c,n);return Db(t,s,l)}else return[]}function doe(t,e,n,r){let i=Ab(t,r);if(i){let o=Cb(i),s=o.path,a=o.queryId,c=Kn(s,e),l=Yn.fromObject(n),d=new tg(Tb(a),c,l);return Db(t,s,d)}else return[]}function Yw(t,e,n,r=!1){let i=e._path,o=null,s=!1;t.syncPointTree_.foreachOnPath(i,(f,g)=>{let E=Kn(f,i);o=o||oa(g,E),s=s||ca(g)});let a=t.syncPointTree_.get(i);a?(s=s||ca(a),o=o||oa(a,je())):(a=new jy,t.syncPointTree_=t.syncPointTree_.set(i,a));let c;o!=null?c=!0:(c=!1,o=ve.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((g,E)=>{let I=oa(E,je());I&&(o=o.updateImmediateChild(g,I))}));let l=gH(a,e);if(!l&&!e._queryParams.loadsAllData()){let f=tI(e);Y(!t.queryToTagMap.has(f),"View does not exist, but we have a tag");let g=goe();t.queryToTagMap.set(f,g),t.tagToQueryMap.set(g,f)}let d=Jy(t.pendingWriteTree_,i),h=noe(a,e,n,d,o,c);if(!l&&!s&&!r){let f=pH(a,e);h=h.concat(moe(t,e,f))}return h}function eI(t,e,n){let i=t.pendingWriteTree_,o=t.syncPointTree_.findOnPath(e,(s,a)=>{let c=Kn(s,e),l=oa(a,c);if(l)return l});return sH(i,e,o,n,!0)}function hoe(t,e){let n=e._path,r=null;t.syncPointTree_.foreachOnPath(n,(l,d)=>{let h=Kn(l,n);r=r||oa(d,h)});let i=t.syncPointTree_.get(n);i?r=r||oa(i,je()):(i=new jy,t.syncPointTree_=t.syncPointTree_.set(n,i));let o=r!=null,s=o?new go(r,!0,!1):null,a=Jy(t.pendingWriteTree_,e._path),c=hH(i,e,a,o?s.getNode():ve.EMPTY_NODE,o);return Yie(c)}function Fd(t,e){return EH(e,t.syncPointTree_,null,Jy(t.pendingWriteTree_,je()))}function EH(t,e,n,r){if(Oe(t.path))return _H(t,e,n,r);{let i=e.get(je());n==null&&i!=null&&(n=oa(i,je()));let o=[],s=be(t.path),a=t.operationForChild(s),c=e.children.get(s);if(c&&a){let l=n?n.getImmediateChild(s):null,d=aH(r,s);o=o.concat(EH(a,c,l,d))}return i&&(o=o.concat(vb(i,t,r,n))),o}}function _H(t,e,n,r){let i=e.get(je());n==null&&i!=null&&(n=oa(i,je()));let o=[];return e.children.inorderTraversal((s,a)=>{let c=n?n.getImmediateChild(s):null,l=aH(r,s),d=t.operationForChild(s);d&&(o=o.concat(_H(d,a,c,l)))}),i&&(o=o.concat(vb(i,t,r,n))),o}function TH(t,e){let n=e.query,r=rg(t,n);return{hashFn:()=>(Kie(e)||ve.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return r?uoe(t,n._path,r):loe(t,n._path);{let o=Dre(i,n);return Wy(t,n,null,o)}}}}function rg(t,e){let n=tI(e);return t.queryToTagMap.get(n)}function tI(t){return t._path.toString()+"$"+t._queryIdentifier}function Ab(t,e){return t.tagToQueryMap.get(e)}function Cb(t){let e=t.indexOf("$");return Y(e!==-1&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new He(t.substr(0,e))}}function Db(t,e,n){let r=t.syncPointTree_.get(e);Y(r,"Missing sync point for query tag that we're tracking");let i=Jy(t.pendingWriteTree_,e);return vb(r,n,i,null)}function foe(t){return t.fold((e,n,r)=>{if(n&&ca(n))return[Zy(n)];{let i=[];return n&&(i=fH(n)),un(r,(o,s)=>{i=i.concat(s)}),i}})}function Yp(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(ooe())(t._repo,t._path):t}function poe(t,e){for(let n=0;n<e.length;++n){let r=e[n];if(!r._queryParams.loadsAllData()){let i=tI(r),o=t.queryToTagMap.get(i);t.queryToTagMap.delete(i),t.tagToQueryMap.delete(o)}}}function goe(){return soe++}function moe(t,e,n){let r=e._path,i=rg(t,e),o=TH(t,n),s=t.listenProvider_.startListening(Yp(e),i,o.hashFn,o.onComplete),a=t.syncPointTree_.subtree(r);if(i)Y(!ca(a.value),"If we're adding a query, it shouldn't be shadowed");else{let c=a.fold((l,d,h)=>{if(!Oe(l)&&d&&ca(d))return[Zy(d).query];{let f=[];return d&&(f=f.concat(fH(d).map(g=>g.query))),un(h,(g,E)=>{f=f.concat(E)}),f}});for(let l=0;l<c.length;++l){let d=c[l];t.listenProvider_.stopListening(Yp(d),rg(t,d))}}return s}var Xw=class t{constructor(e){this.node_=e}getImmediateChild(e){let n=this.node_.getImmediateChild(e);return new t(n)}node(){return this.node_}},Qw=class t{constructor(e,n){this.syncTree_=e,this.path_=n}getImmediateChild(e){let n=At(this.path_,e);return new t(this.syncTree_,n)}node(){return eI(this.syncTree_,this.path_)}},Eoe=function(t){return t=t||{},t.timestamp=t.timestamp||new Date().getTime(),t},vj=function(t,e,n){if(!t||typeof t!="object")return t;if(Y(".sv"in t,"Unexpected leaf node or priority contents"),typeof t[".sv"]=="string")return _oe(t[".sv"],e,n);if(typeof t[".sv"]=="object")return Toe(t[".sv"],e);Y(!1,"Unexpected server value: "+JSON.stringify(t,null,2))},_oe=function(t,e,n){if(t==="timestamp")return n.timestamp;Y(!1,"Unexpected server value: "+t)},Toe=function(t,e,n){t.hasOwnProperty("increment")||Y(!1,"Unexpected server value: "+JSON.stringify(t,null,2));let r=t.increment;typeof r!="number"&&Y(!1,"Unexpected increment value: "+r);let i=e.node();if(Y(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;let s=i.getValue();return typeof s!="number"?r:s+r},yH=function(t,e,n,r){return Nb(e,new Qw(n,t),r)},Rb=function(t,e,n){return Nb(t,new Xw(e),n)};function Nb(t,e,n){let r=t.getPriority().val(),i=vj(r,e.getImmediateChild(".priority"),n),o;if(t.isLeafNode()){let s=t,a=vj(s.getValue(),e,n);return a!==s.getValue()||i!==s.getPriority().val()?new Nd(a,St(i)):t}else{let s=t;return o=s,i!==s.getPriority().val()&&(o=o.updatePriority(new Nd(i))),s.forEachChild(ht,(a,c)=>{let l=Nb(c,e.getImmediateChild(a),n);l!==c&&(o=o.updateImmediateChild(a,l))}),o}}var ig=class{constructor(e="",n=null,r={children:{},childCount:0}){this.name=e,this.parent=n,this.node=r}};function nI(t,e){let n=e instanceof He?e:new He(e),r=t,i=be(n);for(;i!==null;){let o=$s(r.node.children,i)||{children:{},childCount:0};r=new ig(i,r,o),n=ct(n),i=be(n)}return r}function _l(t){return t.node.value}function wb(t,e){t.node.value=e,Jw(t)}function IH(t){return t.node.childCount>0}function yoe(t){return _l(t)===void 0&&!IH(t)}function rI(t,e){un(t.node.children,(n,r)=>{e(new ig(n,t,r))})}function vH(t,e,n,r){n&&!r&&e(t),rI(t,i=>{vH(i,e,!0,r)}),n&&r&&e(t)}function Ioe(t,e,n){let r=n?t:t.parent;for(;r!==null;){if(e(r))return!0;r=r.parent}return!1}function hg(t){return new He(t.parent===null?t.name:hg(t.parent)+"/"+t.name)}function Jw(t){t.parent!==null&&voe(t.parent,t.name,t)}function voe(t,e,n){let r=yoe(n),i=zr(t.node.children,e);r&&i?(delete t.node.children[e],t.node.childCount--,Jw(t)):!r&&!i&&(t.node.children[e]=n.node,t.node.childCount++,Jw(t))}var Soe=/[\[\].#$\/\u0000-\u001F\u007F]/,Aoe=/[\[\].#$\u0000-\u001F\u007F]/,uw=10*1024*1024,iI=function(t){return typeof t=="string"&&t.length!==0&&!Soe.test(t)},SH=function(t){return typeof t=="string"&&t.length!==0&&!Aoe.test(t)},Coe=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),SH(t)},og=function(t){return t===null||typeof t=="string"||typeof t=="number"&&!Xy(t)||t&&typeof t=="object"&&zr(t,".sv")},hl=function(t,e,n,r){r&&e===void 0||fg(Ws(t,"value"),e,n)},fg=function(t,e,n){let r=n instanceof He?new Sw(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+sl(r));if(typeof e=="function")throw new Error(t+"contains a function "+sl(r)+" with contents = "+e.toString());if(Xy(e))throw new Error(t+"contains "+e.toString()+" "+sl(r));if(typeof e=="string"&&e.length>uw/3&&vp(e)>uw)throw new Error(t+"contains a string greater than "+uw+" utf8 bytes "+sl(r)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,o=!1;if(un(e,(s,a)=>{if(s===".value")i=!0;else if(s!==".priority"&&s!==".sv"&&(o=!0,!iI(s)))throw new Error(t+" contains an invalid key ("+s+") "+sl(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);tie(r,s),fg(t,a,r),nie(r)}),i&&o)throw new Error(t+' contains ".value" child '+sl(r)+" in addition to actual children.")}},Doe=function(t,e){let n,r;for(n=0;n<e.length;n++){r=e[n];let o=Xp(r);for(let s=0;s<o.length;s++)if(!(o[s]===".priority"&&s===o.length-1)){if(!iI(o[s]))throw new Error(t+"contains an invalid key ("+o[s]+") in path "+r.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}}e.sort(eie);let i=null;for(n=0;n<e.length;n++){if(r=e[n],i!==null&&Yr(i,r))throw new Error(t+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}},AH=function(t,e,n,r){if(r&&e===void 0)return;let i=Ws(t,"values");if(!(e&&typeof e=="object")||Array.isArray(e))throw new Error(i+" must be an object containing the children to replace.");let o=[];un(e,(s,a)=>{let c=new He(s);if(fg(i,a,At(n,c)),fb(c)===".priority"&&!og(a))throw new Error(i+"contains an invalid value for '"+c.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(c)}),Doe(i,o)},Roe=function(t,e,n){if(!(n&&e===void 0)){if(Xy(e))throw new Error(Ws(t,"priority")+"is "+e.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!og(e))throw new Error(Ws(t,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},CH=function(t,e,n,r){if(!(r&&n===void 0)&&!iI(n))throw new Error(Ws(t,e)+'was an invalid key = "'+n+`". Firebase keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]").`)},bb=function(t,e,n,r){if(!(r&&n===void 0)&&!SH(n))throw new Error(Ws(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Noe=function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),bb(t,e,n,r)},ra=function(t,e){if(be(e)===".info")throw new Error(t+" failed = Can't modify data under /.info/")},woe=function(t,e){let n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!iI(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Coe(n))throw new Error(Ws(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};var Zw=class{constructor(){this.eventLists_=[],this.recursionDepth_=0}};function oI(t,e){let n=null;for(let r=0;r<e.length;r++){let i=e[r],o=i.getPath();n!==null&&!pb(o,n.path)&&(t.eventLists_.push(n),n=null),n===null&&(n={events:[],path:o}),n.events.push(i)}n&&t.eventLists_.push(n)}function DH(t,e,n){oI(t,n),RH(t,r=>pb(r,e))}function Cr(t,e,n){oI(t,n),RH(t,r=>Yr(r,e)||Yr(e,r))}function RH(t,e){t.recursionDepth_++;let n=!0;for(let r=0;r<t.eventLists_.length;r++){let i=t.eventLists_[r];if(i){let o=i.path;e(o)?(boe(t.eventLists_[r]),t.eventLists_[r]=null):n=!1}}n&&(t.eventLists_=[]),t.recursionDepth_--}function boe(t){for(let e=0;e<t.events.length;e++){let n=t.events[e];if(n!==null){t.events[e]=null;let r=n.getEventRunner();cl&&ln("event: "+n.toString()),xd(r)}}}var Ooe="repo_interrupt",Moe=25,eb=class{constructor(e,n,r,i){this.repoInfo_=e,this.forceRestClient_=n,this.authTokenProvider_=r,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Zw,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=xy(),this.transactionQueueTree_=new ig,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}};function Loe(t,e,n){if(t.stats_=hb(t.repoInfo_),t.forceRestClient_||bre())t.server_=new Lw(t.repoInfo_,(r,i,o,s)=>{Sj(t,r,i,o,s)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>Aj(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Pt(n)}catch(r){throw new Error("Invalid authOverride provided: "+r)}}t.persistentConnection_=new gb(t.repoInfo_,e,(r,i,o,s)=>{Sj(t,r,i,o,s)},r=>{Aj(t,r)},r=>{Poe(t,r)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(r=>{t.server_.refreshAuthToken(r)}),t.appCheckProvider_.addTokenChangeListener(r=>{t.server_.refreshAppCheckToken(r.token)}),t.statsReporter_=Mre(t.repoInfo_,()=>new Uw(t.stats_,t.server_)),t.infoData_=new Pw,t.infoSyncTree_=new $y({startListening:(r,i,o,s)=>{let a=[],c=t.infoData_.getNode(r._path);return c.isEmpty()||(a=dg(t.infoSyncTree_,r._path,c),setTimeout(()=>{s("ok")},0)),a},stopListening:()=>{}}),Ob(t,"connected",!1),t.serverSyncTree_=new $y({startListening:(r,i,o,s)=>(t.server_.listen(r,o,i,(a,c)=>{let l=s(a,c);Cr(t.eventQueue_,r._path,l)}),[]),stopListening:(r,i)=>{t.server_.unlisten(r,i)}})}function NH(t){let n=t.infoData_.getNode(new He(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function pg(t){return Eoe({timestamp:NH(t)})}function Sj(t,e,n,r,i){t.dataUpdateCount++;let o=new He(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let s=[];if(i)if(r){let c=yp(n,l=>St(l));s=doe(t.serverSyncTree_,o,c,i)}else{let c=St(n);s=mH(t.serverSyncTree_,o,c,i)}else if(r){let c=yp(n,l=>St(l));s=coe(t.serverSyncTree_,o,c)}else{let c=St(n);s=dg(t.serverSyncTree_,o,c)}let a=o;s.length>0&&(a=Ld(t,o)),Cr(t.eventQueue_,a,s)}function Aj(t,e){Ob(t,"connected",e),e===!1&&Uoe(t)}function Poe(t,e){un(e,(n,r)=>{Ob(t,n,r)})}function Ob(t,e,n){let r=new He("/.info/"+e),i=St(n);t.infoData_.updateSnapshot(r,i);let o=dg(t.infoSyncTree_,r,i);Cr(t.eventQueue_,r,o)}function sI(t){return t.nextWriteId_++}function xoe(t,e,n){let r=hoe(t.serverSyncTree_,e);return r!=null?Promise.resolve(r):t.server_.get(e).then(i=>{let o=St(i).withIndex(e._queryParams.getIndex());Yw(t.serverSyncTree_,e,n,!0);let s;if(e._queryParams.loadsAllData())s=dg(t.serverSyncTree_,e._path,o);else{let a=rg(t.serverSyncTree_,e);s=mH(t.serverSyncTree_,e._path,o,a)}return Cr(t.eventQueue_,e._path,s),Wy(t.serverSyncTree_,e,n,null,!0),o},i=>(Ud(t,"get for query "+Pt(e)+" failed: "+i),Promise.reject(new Error(i))))}function koe(t,e,n,r,i){Ud(t,"set",{path:e.toString(),value:n,priority:r});let o=pg(t),s=St(n,r),a=eI(t.serverSyncTree_,e),c=Rb(s,a,o),l=sI(t),d=Sb(t.serverSyncTree_,e,c,l,!0);oI(t.eventQueue_,d),t.server_.put(e.toString(),s.val(!0),(f,g)=>{let E=f==="ok";E||Fn("set at "+e+" failed: "+f);let I=na(t.serverSyncTree_,l,!E);Cr(t.eventQueue_,e,I),la(t,i,f,g)});let h=Lb(t,e);Ld(t,h),Cr(t.eventQueue_,h,[])}function Foe(t,e,n,r){Ud(t,"update",{path:e.toString(),value:n});let i=!0,o=pg(t),s={};if(un(n,(a,c)=>{i=!1,s[a]=yH(At(e,a),St(c),t.serverSyncTree_,o)}),i)ln("update() called with empty data. Don't do anything."),la(t,r,"ok",void 0);else{let a=sI(t),c=aoe(t.serverSyncTree_,e,s,a);oI(t.eventQueue_,c),t.server_.merge(e.toString(),n,(l,d)=>{let h=l==="ok";h||Fn("update at "+e+" failed: "+l);let f=na(t.serverSyncTree_,a,!h),g=f.length>0?Ld(t,e):e;Cr(t.eventQueue_,g,f),la(t,r,l,d)}),un(n,l=>{let d=Lb(t,At(e,l));Ld(t,d)}),Cr(t.eventQueue_,e,[])}}function Uoe(t){Ud(t,"onDisconnectEvents");let e=pg(t),n=xy();kw(t.onDisconnect_,je(),(i,o)=>{let s=yH(i,o,t.serverSyncTree_,e);kd(n,i,s)});let r=[];kw(n,je(),(i,o)=>{r=r.concat(dg(t.serverSyncTree_,i,o));let s=Lb(t,i);Ld(t,s)}),t.onDisconnect_=xy(),Cr(t.eventQueue_,je(),r)}function Voe(t,e,n){t.server_.onDisconnectCancel(e.toString(),(r,i)=>{r==="ok"&&xw(t.onDisconnect_,e),la(t,n,r,i)})}function Cj(t,e,n,r){let i=St(n);t.server_.onDisconnectPut(e.toString(),i.val(!0),(o,s)=>{o==="ok"&&kd(t.onDisconnect_,e,i),la(t,r,o,s)})}function Boe(t,e,n,r,i){let o=St(n,r);t.server_.onDisconnectPut(e.toString(),o.val(!0),(s,a)=>{s==="ok"&&kd(t.onDisconnect_,e,o),la(t,i,s,a)})}function Goe(t,e,n,r){if(Tp(n)){ln("onDisconnect().update() called with empty data. Don't do anything."),la(t,r,"ok",void 0);return}t.server_.onDisconnectMerge(e.toString(),n,(i,o)=>{i==="ok"&&un(n,(s,a)=>{let c=St(a);kd(t.onDisconnect_,At(e,s),c)}),la(t,r,i,o)})}function joe(t,e,n){let r;be(e._path)===".info"?r=Yw(t.infoSyncTree_,e,n):r=Yw(t.serverSyncTree_,e,n),DH(t.eventQueue_,e._path,r)}function tb(t,e,n){let r;be(e._path)===".info"?r=Wy(t.infoSyncTree_,e,n):r=Wy(t.serverSyncTree_,e,n),DH(t.eventQueue_,e._path,r)}function Hoe(t){t.persistentConnection_&&t.persistentConnection_.interrupt(Ooe)}function Ud(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),ln(n,...e)}function la(t,e,n,r){e&&xd(()=>{if(n==="ok")e(null);else{let i=(n||"error").toUpperCase(),o=i;r&&(o+=": "+r);let s=new Error(o);s.code=i,e(s)}})}function $oe(t,e,n,r,i,o){Ud(t,"transaction on "+e);let s={path:e,update:n,onComplete:r,status:null,order:wj(),applyLocally:o,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=Mb(t,e,void 0);s.currentInputSnapshot=a;let c=s.update(a.val());if(c===void 0)s.unwatcher(),s.currentOutputSnapshotRaw=null,s.currentOutputSnapshotResolved=null,s.onComplete&&s.onComplete(null,!1,s.currentInputSnapshot);else{fg("transaction failed: Data returned ",c,s.path),s.status=0;let l=nI(t.transactionQueueTree_,e),d=_l(l)||[];d.push(s),wb(l,d);let h;typeof c=="object"&&c!==null&&zr(c,".priority")?(h=$s(c,".priority"),Y(og(h),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):h=(eI(t.serverSyncTree_,e)||ve.EMPTY_NODE).getPriority().val();let f=pg(t),g=St(c,h),E=Rb(g,a,f);s.currentOutputSnapshotRaw=g,s.currentOutputSnapshotResolved=E,s.currentWriteId=sI(t);let I=Sb(t.serverSyncTree_,e,E,s.currentWriteId,s.applyLocally);Cr(t.eventQueue_,e,I),aI(t,t.transactionQueueTree_)}}function Mb(t,e,n){return eI(t.serverSyncTree_,e,n)||ve.EMPTY_NODE}function aI(t,e=t.transactionQueueTree_){if(e||cI(t,e),_l(e)){let n=bH(t,e);Y(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&Woe(t,hg(e),n)}else IH(e)&&rI(e,n=>{aI(t,n)})}function Woe(t,e,n){let r=n.map(l=>l.currentWriteId),i=Mb(t,e,r),o=i,s=i.hash();for(let l=0;l<n.length;l++){let d=n[l];Y(d.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),d.status=1,d.retryCount++;let h=Kn(e,d.path);o=o.updateChild(h,d.currentOutputSnapshotRaw)}let a=o.val(!0),c=e;t.server_.put(c.toString(),a,l=>{Ud(t,"transaction put response",{path:c.toString(),status:l});let d=[];if(l==="ok"){let h=[];for(let f=0;f<n.length;f++)n[f].status=2,d=d.concat(na(t.serverSyncTree_,n[f].currentWriteId)),n[f].onComplete&&h.push(()=>n[f].onComplete(null,!0,n[f].currentOutputSnapshotResolved)),n[f].unwatcher();cI(t,nI(t.transactionQueueTree_,e)),aI(t,t.transactionQueueTree_),Cr(t.eventQueue_,e,d);for(let f=0;f<h.length;f++)xd(h[f])}else{if(l==="datastale")for(let h=0;h<n.length;h++)n[h].status===3?n[h].status=4:n[h].status=0;else{Fn("transaction at "+c.toString()+" failed: "+l);for(let h=0;h<n.length;h++)n[h].status=4,n[h].abortReason=l}Ld(t,e)}},s)}function Ld(t,e){let n=wH(t,e),r=hg(n),i=bH(t,n);return zoe(t,i,r),r}function zoe(t,e,n){if(e.length===0)return;let r=[],i=[],s=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){let c=e[a],l=Kn(n,c.path),d=!1,h;if(Y(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)d=!0,h=c.abortReason,i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=Moe)d=!0,h="maxretry",i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0));else{let f=Mb(t,c.path,s);c.currentInputSnapshot=f;let g=e[a].update(f.val());if(g!==void 0){fg("transaction failed: Data returned ",g,c.path);let E=St(g);typeof g=="object"&&g!=null&&zr(g,".priority")||(E=E.updatePriority(f.getPriority()));let S=c.currentWriteId,L=pg(t),j=Rb(E,f,L);c.currentOutputSnapshotRaw=E,c.currentOutputSnapshotResolved=j,c.currentWriteId=sI(t),s.splice(s.indexOf(S),1),i=i.concat(Sb(t.serverSyncTree_,c.path,j,c.currentWriteId,c.applyLocally)),i=i.concat(na(t.serverSyncTree_,S,!0))}else d=!0,h="nodata",i=i.concat(na(t.serverSyncTree_,c.currentWriteId,!0))}Cr(t.eventQueue_,n,i),i=[],d&&(e[a].status=2,(function(f){setTimeout(f,Math.floor(0))})(e[a].unwatcher),e[a].onComplete&&(h==="nodata"?r.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):r.push(()=>e[a].onComplete(new Error(h),!1,null))))}cI(t,t.transactionQueueTree_);for(let a=0;a<r.length;a++)xd(r[a]);aI(t,t.transactionQueueTree_)}function wH(t,e){let n,r=t.transactionQueueTree_;for(n=be(e);n!==null&&_l(r)===void 0;)r=nI(r,n),e=ct(e),n=be(e);return r}function bH(t,e){let n=[];return OH(t,e,n),n.sort((r,i)=>r.order-i.order),n}function OH(t,e,n){let r=_l(e);if(r)for(let i=0;i<r.length;i++)n.push(r[i]);rI(e,i=>{OH(t,i,n)})}function cI(t,e){let n=_l(e);if(n){let r=0;for(let i=0;i<n.length;i++)n[i].status!==2&&(n[r]=n[i],r++);n.length=r,wb(e,n.length>0?n:void 0)}rI(e,r=>{cI(t,r)})}function Lb(t,e){let n=hg(wH(t,e)),r=nI(t.transactionQueueTree_,e);return Ioe(r,i=>{dw(t,i)}),dw(t,r),vH(r,i=>{dw(t,i)}),n}function dw(t,e){let n=_l(e);if(n){let r=[],i=[],o=-1;for(let s=0;s<n.length;s++)n[s].status===3||(n[s].status===1?(Y(o===s-1,"All SENT items should be at beginning of queue."),o=s,n[s].status=3,n[s].abortReason="set"):(Y(n[s].status===0,"Unexpected transaction status in abort"),n[s].unwatcher(),i=i.concat(na(t.serverSyncTree_,n[s].currentWriteId,!0)),n[s].onComplete&&r.push(n[s].onComplete.bind(null,new Error("set"),!1,null))));o===-1?wb(e,void 0):n.length=o+1,Cr(t.eventQueue_,hg(e),i);for(let s=0;s<r.length;s++)xd(r[s])}}function qoe(t){let e="",n=t.split("/");for(let r=0;r<n.length;r++)if(n[r].length>0){let i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function Koe(t){let e={};t.charAt(0)==="?"&&(t=t.substring(1));for(let n of t.split("&")){if(n.length===0)continue;let r=n.split("=");r.length===2?e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):Fn(`Invalid query segment '${n}' in query '${t}'`)}return e}var Dj=function(t,e){let n=Yoe(t),r=n.namespace;n.domain==="firebase.com"&&rs(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!r||r==="undefined")&&n.domain!=="localhost"&&rs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Ire();let i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new Dy(n.host,n.secure,r,i,e,"",r!==n.subdomain),path:new He(n.pathString)}},Yoe=function(t){let e="",n="",r="",i="",o="",s=!0,a="https",c=443;if(typeof t=="string"){let l=t.indexOf("//");l>=0&&(a=t.substring(0,l-1),t=t.substring(l+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),e=t.substring(0,Math.min(d,h)),d<h&&(i=qoe(t.substring(d,h)));let f=Koe(t.substring(Math.min(t.length,h)));l=e.indexOf(":"),l>=0?(s=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;let g=e.slice(0,l);if(g.toLowerCase()==="localhost")n="localhost";else if(g.split(".").length<=2)n=g;else{let E=e.indexOf(".");r=e.substring(0,E).toLowerCase(),n=e.substring(E+1),o=r}"ns"in f&&(o=f.ns)}return{host:e,port:c,domain:n,subdomain:r,secure:s,scheme:a,pathString:i,namespace:o}};var Rj="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Xoe=(function(){let t=0,e=[];return function(n){let r=n===t;t=n;let i,o=new Array(8);for(i=7;i>=0;i--)o[i]=Rj.charAt(n%64),n=Math.floor(n/64);Y(n===0,"Cannot push at time == 0");let s=o.join("");if(r){for(i=11;i>=0&&e[i]===63;i--)e[i]=0;e[i]++}else for(i=0;i<12;i++)e[i]=Math.floor(Math.random()*64);for(i=0;i<12;i++)s+=Rj.charAt(e[i]);return Y(s.length===20,"nextPushId: Length should be 20."),s}})();var zy=class{constructor(e,n,r,i){this.eventType=e,this.eventRegistration=n,this.snapshot=r,this.prevName=i}getPath(){let 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+":"+Pt(this.snapshot.exportVal())}},qy=class{constructor(e,n,r){this.eventRegistration=e,this.error=n,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}};var sg=class{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return Y(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}};var nb=class{constructor(e,n){this._repo=e,this._path=n}cancel(){let e=new an;return Voe(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){ra("OnDisconnect.remove",this._path);let e=new an;return Cj(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){ra("OnDisconnect.set",this._path),hl("OnDisconnect.set",e,this._path,!1);let n=new an;return Cj(this._repo,this._path,e,n.wrapCallback(()=>{})),n.promise}setWithPriority(e,n){ra("OnDisconnect.setWithPriority",this._path),hl("OnDisconnect.setWithPriority",e,this._path,!1),Roe("OnDisconnect.setWithPriority",n,!1);let r=new an;return Boe(this._repo,this._path,e,n,r.wrapCallback(()=>{})),r.promise}update(e){ra("OnDisconnect.update",this._path),AH("OnDisconnect.update",e,this._path,!1);let n=new an;return Goe(this._repo,this._path,e,n.wrapCallback(()=>{})),n.promise}};var fl=class t{constructor(e,n,r,i){this._repo=e,this._path=n,this._queryParams=r,this._orderByCalled=i}get key(){return Oe(this._path)?null:fb(this._path)}get ref(){return new Si(this._repo,this._path)}get _queryIdentifier(){let e=hj(this._queryParams),n=db(e);return n==="{}"?"default":n}get _queryObject(){return hj(this._queryParams)}isEqual(e){if(e=Pe(e),!(e instanceof t))return!1;let n=this._repo===e._repo,r=pb(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+Zre(this._path)}};function Qoe(t,e){if(t._orderByCalled===!0)throw new Error(e+": You can't combine multiple orderBy calls.")}function Pb(t){let e=null,n=null;if(t.hasStart()&&(e=t.getIndexStartValue()),t.hasEnd()&&(n=t.getIndexEndValue()),t.getIndex()===ll){let r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(t.hasStart()){if(t.getIndexStartName()!==ul)throw new Error(r);if(typeof e!="string")throw new Error(i)}if(t.hasEnd()){if(t.getIndexEndName()!==sa)throw new Error(r);if(typeof n!="string")throw new Error(i)}}else if(t.getIndex()===ht){if(e!=null&&!og(e)||n!=null&&!og(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(Y(t.getIndex()instanceof Qp||t.getIndex()===tH,"unknown index type."),e!=null&&typeof e=="object"||n!=null&&typeof n=="object")throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function MH(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}var Si=class t extends fl{constructor(e,n){super(e,n,new Mw,!1)}get parent(){let e=Yj(this._path);return e===null?null:new t(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}},Pd=class t{constructor(e,n,r){this._node=e,this.ref=n,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){let n=new He(e),r=pl(this.ref,e);return new t(this._node.getChild(n),r,ht)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(r,i)=>e(new t(i,pl(this.ref,r),ht)))}hasChild(e){let n=new He(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}};function LH(t,e){return t=Pe(t),t._checkNotDeleted("ref"),e!==void 0?pl(t._root,e):t._root}function pl(t,e){return t=Pe(t),be(t._path)===null?Noe("child","path",e,!1):bb("child","path",e,!1),new Si(t._repo,At(t._path,e))}function PH(t){return t=Pe(t),new nb(t._repo,t._path)}function xH(t,e){t=Pe(t),ra("push",t._path),hl("push",e,t._path,!0);let n=NH(t._repo),r=Xoe(n),i=pl(t,r),o=pl(t,r),s;return e!=null?s=lI(o,e).then(()=>o):s=Promise.resolve(o),i.then=s.then.bind(s),i.catch=s.then.bind(s,void 0),i}function kH(t){return ra("remove",t._path),lI(t,null)}function lI(t,e){t=Pe(t),ra("set",t._path),hl("set",e,t._path,!1);let n=new an;return koe(t._repo,t._path,e,null,n.wrapCallback(()=>{})),n.promise}function FH(t,e){AH("update",e,t._path,!1);let n=new an;return Foe(t._repo,t._path,e,n.wrapCallback(()=>{})),n.promise}function uI(t){t=Pe(t);let e=new sg(()=>{}),n=new ag(e);return xoe(t._repo,t,n).then(r=>new Pd(r,new Si(t._repo,t._path),t._queryParams.getIndex()))}var ag=class t{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){let r=n._queryParams.getIndex();return new zy("value",this,new Pd(e.snapshotNode,new Si(n._repo,n._path),r))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qy(this,e,n):null}matches(e){return e instanceof t?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}},Ky=class t{constructor(e,n){this.eventType=e,this.callbackContext=n}respondsTo(e){let n=e==="children_added"?"child_added":e;return n=n==="children_removed"?"child_removed":n,this.eventType===n}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qy(this,e,n):null}createEvent(e,n){Y(e.childName!=null,"Child events should have a childName.");let r=pl(new Si(n._repo,n._path),e.childName),i=n._queryParams.getIndex();return new zy(e.type,this,new Pd(e.snapshotNode,r,i),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof t?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}};function gg(t,e,n,r,i){let o;if(typeof r=="object"&&(o=void 0,i=r),typeof r=="function"&&(o=r),i&&i.onlyOnce){let c=n,l=(d,h)=>{tb(t._repo,t,a),c(d,h)};l.userCallback=n.userCallback,l.context=n.context,n=l}let s=new sg(n,o||void 0),a=e==="value"?new ag(s):new Ky(e,s);return joe(t._repo,t,a),()=>tb(t._repo,t,a)}function mg(t,e,n,r){return gg(t,"value",e,n,r)}function dI(t,e,n,r){return gg(t,"child_added",e,n,r)}function hI(t,e,n,r){return gg(t,"child_changed",e,n,r)}function xb(t,e,n,r){return gg(t,"child_moved",e,n,r)}function fI(t,e,n,r){return gg(t,"child_removed",e,n,r)}function pI(t,e,n){let r=null,i=n?new sg(n):null;e==="value"?r=new ag(i):e&&(r=new Ky(e,i)),tb(t._repo,t,r)}var gl=class{},rb=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="endAt"}_apply(e){hl("endAt",this._value,e._path,!0);let n=Eie(e._queryParams,this._value,this._key);if(MH(n),Pb(n),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new fl(e._repo,e._path,n,e._orderByCalled)}};var Yy=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="startAt"}_apply(e){hl("startAt",this._value,e._path,!0);let n=mie(e._queryParams,this._value,this._key);if(MH(n),Pb(n),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new fl(e._repo,e._path,n,e._orderByCalled)}};function UH(t=null,e){return CH("startAt","key",e,!0),new Yy(t,e)}var ib=class extends gl{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new fl(e._repo,e._path,gie(e._queryParams,this._limit),e._orderByCalled)}};function VH(t){if(typeof t!="number"||Math.floor(t)!==t||t<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new ib(t)}var ob=class extends gl{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Qoe(e,"orderByChild");let n=new He(this._path);if(Oe(n))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");let r=new Qp(n),i=_ie(e._queryParams,r);return Pb(i),new fl(e._repo,e._path,i,!0)}};function BH(t){if(t==="$key")throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if(t==="$priority")throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if(t==="$value")throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return bb("orderByChild","path",t,!1),new ob(t)}var sb=class extends gl{constructor(e,n){super(),this._value=e,this._key=n,this.type="equalTo"}_apply(e){if(hl("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new rb(this._value,this._key)._apply(new Yy(this._value,this._key)._apply(e))}};function GH(t,e){return CH("equalTo","key",e,!0),new sb(t,e)}function jH(t,...e){let n=Pe(t);for(let r of e)n=r._apply(n);return n}Zie(Si);ioe(Si);var Joe="FIREBASE_DATABASE_EMULATOR_HOST",ab={},Zoe=!1;function ese(t,e,n,r){let i=e.lastIndexOf(":"),o=e.substring(0,i),s=vr(o);t.repoInfo_=new Dy(e,s,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(t.authTokenProvider_=r)}function tse(t,e,n,r,i){let o=r||t.options.databaseURL;o===void 0&&(t.options.projectId||rs("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),ln("Using default host for project ",t.options.projectId),o=`${t.options.projectId}-default-rtdb.firebaseio.com`);let s=Dj(o,i),a=s.repoInfo,c,l;typeof process<"u"&&process.env&&(l=process.env[Joe]),l?(c=!0,o=`http://${l}?ns=${a.namespace}`,s=Dj(o,i),a=s.repoInfo):c=!s.repoInfo.secure;let d=i&&c?new zp(zp.OWNER):new Ew(t.name,t.options,e);woe("Invalid Firebase Database URL",s),Oe(s.path)||rs("Database URL must point to the root of a Firebase Database (not including a child path).");let h=rse(a,t,d,new mw(t,n));return new cb(h,t)}function nse(t,e){let n=ab[e];(!n||n[t.key]!==t)&&rs(`Database ${e}(${t.repoInfo_}) has already been deleted.`),Hoe(t),delete n[t.key]}function rse(t,e,n,r){let i=ab[e.name];i||(i={},ab[e.name]=i);let o=i[t.toURLString()];return o&&rs("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),o=new eb(t,Zoe,n,r),i[t.toURLString()]=o,o}var cb=class{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Loe(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Si(this._repo,je())),this._rootInternal}_delete(){return this._rootInternal!==null&&(nse(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&rs("Cannot call "+e+" on a deleted database.")}};function ise(){Kj.IS_TRANSPORT_INITIALIZED&&Fn("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function kb(){ise(),Ad.forceDisallow(),Ry.forceAllow()}function Vd(t=ir(),e){let n=uo(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){let r=pd("database");r&&HH(n,...r)}return n}function HH(t,e,n,r={}){t=Pe(t),t._checkNotDeleted("useEmulator");let i=`${e}:${n}`,o=t._repoInternal;if(t._instanceStarted){if(i===t._repoInternal.repoInfo_.host&&mi(r,o.repoInfo_.emulatorOptions))return;rs("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let s;if(o.repoInfo_.nodeAdmin)r.mockUserToken&&rs('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new zp(zp.OWNER);else if(r.mockUserToken){let a=typeof r.mockUserToken=="string"?r.mockUserToken:zT(r.mockUserToken,t.app.options.projectId);s=new zp(a)}vr(e)&&(Hs(e),qc("Database",!0)),ese(o,i,r,s)}function ose(t){Tre(qs),zn(new Xt("database",(e,{instanceIdentifier:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),o=e.getProvider("app-check-internal");return tse(r,i,o,n)},"PUBLIC").setMultipleInstances(!0)),$e(Y2,X2,t),$e(Y2,X2,"esm2017")}var lb=class{constructor(e,n){this.committed=e,this.snapshot=n}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function $H(t,e,n){var r;if(t=Pe(t),ra("Reference.transaction",t._path),t.key===".length"||t.key===".keys")throw"Reference.transaction failed: "+t.key+" is a read-only object.";let i=(r=n?.applyLocally)!==null&&r!==void 0?r:!0,o=new an,s=(c,l,d)=>{let h=null;c?o.reject(c):(h=new Pd(d,new Si(t._repo,t._path),ht),o.resolve(new lb(l,h)))},a=mg(t,()=>{});return $oe(t._repo,t._path,e,s,a,i),o.promise}gb.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};gb.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};ose();var Tl,dn=(function(t){return t.added="child_added",t.removed="child_removed",t.changed="child_changed",t.moved="child_moved",t.value="value",t})(dn||{}),sse=Object.freeze((Tl={},Tl[dn.added]=dI,Tl[dn.removed]=fI,Tl[dn.changed]=hI,Tl[dn.moved]=xb,Tl[dn.value]=mg,Tl));function mI(t,e){return new ue(function(n){var r=sse[e](t,function(i,o){n.next({snapshot:i,prevKey:o,event:e})},n.error.bind(n));return{unsubscribe:function(){pI(t,e,r)}}}).pipe(yS(0))}var gI=function(){return gI=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},gI.apply(this,arguments)};function Fb(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}function WH(t){return(t==null||t.length===0)&&(t=[dn.added,dn.removed,dn.changed,dn.moved]),t}function zH(t,e){return e===void 0&&(e={}),mI(t,dn.value).pipe(De(function(n){return Ub(n,e)}))}function Ub(t,e){var n;e===void 0&&(e={});var r=t.snapshot.val();return!t.snapshot.exists()||typeof r!="object"?r:gI(gI({},r),e.keyField?(n={},n[e.keyField]=t.snapshot.key,n):null)}function qH(t,e){e===void 0&&(e={});var n=WH(e.events),r=n.map(function(i){return mI(t,i)});return vs.apply(void 0,r)}function ase(t){return hr(uI(t)).pipe(De(function(e){var n=dn.value;return{snapshot:e,prevKey:null,event:n}}))}function KH(t,e){e===void 0&&(e={});var n=WH(e.events);return ase(t).pipe(Zn(function(r){var i=[ot(r)];return n.forEach(function(o){i.push(mI(t,o))}),vs.apply(void 0,i).pipe(aE(lse,[]))}),ai())}function YH(t,e){return e===void 0&&(e={}),KH(t).pipe(De(function(n){return n.map(function(r){return Ub(r,e)})}))}function XH(t,e){for(var n=t.length,r=0;r<n;r++)if(t[r].snapshot.key===e)return r;return-1}function cse(t,e){if(e==null)return 0;var n=XH(t,e);return n===-1?t.length:n+1}function lse(t,e){var n=e.snapshot,r=e.prevKey,i=e.event,o=n.key,s=XH(t,o),a=cse(t,r||void 0);switch(i){case dn.value:if(e.snapshot&&e.snapshot.exists()){var c=null;e.snapshot.forEach(function(h){var f={snapshot:h,event:dn.value,prevKey:c};return c=h.key,t=Fb(Fb([],t,!0),[f],!1),!1})}return t;case dn.added:if(s>-1){var l=t[s-1];(l&&l.snapshot.key||null)!==r&&(t=t.filter(function(h){return h.snapshot.key!==n.key}),t.splice(a,0,e))}else{if(r==null)return Fb([e],t,!0);t=t.slice(),t.splice(a,0,e)}return t;case dn.removed:return t.filter(function(h){return h.snapshot.key!==n.key});case dn.changed:return t.map(function(h){return h.snapshot.key===o?e:h});case dn.moved:if(s>-1){var d=t.splice(s,1)[0];return t=t.slice(),t.splice(a,0,d),t}return t;default:return t}}var Eg=class{constructor(e){return e}},QH="database",Vb=class{constructor(){return Qo(QH)}};var Bb=new q("angularfire2.database-instances");function use(t,e){let n=Ks(QH,t,e);return n&&new Eg(n)}function dse(t){return(e,n)=>{let r=e.runOutsideAngular(()=>t(n));return new Eg(r)}}var hse={provide:Vb,deps:[[new Wt,Bb]]},fse={provide:Eg,useFactory:use,deps:[[new Wt,Bb],Ti]};function qFe(t,...e){return $e("angularfire",Ei.full,"rtdb"),er([fse,hse,{provide:Bb,useFactory:dse(t),multi:!0,deps:[Re,Ke,_i,Jo,[new Wt,el],[new Wt,Xs],...e]}])}var JH=de(YH,!0);var ZH=de(zH,!0),e$=de(qH,!0);var KFe=de(GH,!0,2);var _g=de(uI,!0),YFe=de(Vd,!0);var XFe=de(VH,!0,2),t$=de(pI,!0),n$=de(dI,!0),r$=de(hI,!0);var i$=de(fI,!0),o$=de(PH,!0),Gb=de(mg,!0),QFe=de(BH,!0,2);var s$=de(xH,!0,2),a$=de(jH,!0,2),Bd=de(LH,!0,2);var c$=de(kH,!0,2),l$=de($H,!0),u$=de(lI,!0,2);var JFe=de(UH,!0,2),d$=de(FH,!0,2);var h$=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},f$={};var is,jb;(function(){var t;function e(A,v){function C(){}C.prototype=v.prototype,A.D=v.prototype,A.prototype=new C,A.prototype.constructor=A,A.C=function(w,R,O){for(var D=Array(arguments.length-2),Mr=2;Mr<arguments.length;Mr++)D[Mr-2]=arguments[Mr];return v.prototype[R].apply(w,D)}}function n(){this.blockSize=-1}function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}e(r,n),r.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function i(A,v,C){C||(C=0);var w=Array(16);if(typeof v=="string")for(var R=0;16>R;++R)w[R]=v.charCodeAt(C++)|v.charCodeAt(C++)<<8|v.charCodeAt(C++)<<16|v.charCodeAt(C++)<<24;else for(R=0;16>R;++R)w[R]=v[C++]|v[C++]<<8|v[C++]<<16|v[C++]<<24;v=A.g[0],C=A.g[1],R=A.g[2];var O=A.g[3],D=v+(O^C&(R^O))+w[0]+3614090360&4294967295;v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[1]+3905402710&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[2]+606105819&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[3]+3250441966&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[4]+4118548399&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[5]+1200080426&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[6]+2821735955&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[7]+4249261313&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[8]+1770035416&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[9]+2336552879&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[10]+4294925233&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[11]+2304563134&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(O^C&(R^O))+w[12]+1804603682&4294967295,v=C+(D<<7&4294967295|D>>>25),D=O+(R^v&(C^R))+w[13]+4254626195&4294967295,O=v+(D<<12&4294967295|D>>>20),D=R+(C^O&(v^C))+w[14]+2792965006&4294967295,R=O+(D<<17&4294967295|D>>>15),D=C+(v^R&(O^v))+w[15]+1236535329&4294967295,C=R+(D<<22&4294967295|D>>>10),D=v+(R^O&(C^R))+w[1]+4129170786&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[6]+3225465664&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[11]+643717713&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[0]+3921069994&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[5]+3593408605&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[10]+38016083&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[15]+3634488961&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[4]+3889429448&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[9]+568446438&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[14]+3275163606&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[3]+4107603335&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[8]+1163531501&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(R^O&(C^R))+w[13]+2850285829&4294967295,v=C+(D<<5&4294967295|D>>>27),D=O+(C^R&(v^C))+w[2]+4243563512&4294967295,O=v+(D<<9&4294967295|D>>>23),D=R+(v^C&(O^v))+w[7]+1735328473&4294967295,R=O+(D<<14&4294967295|D>>>18),D=C+(O^v&(R^O))+w[12]+2368359562&4294967295,C=R+(D<<20&4294967295|D>>>12),D=v+(C^R^O)+w[5]+4294588738&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[8]+2272392833&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[11]+1839030562&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[14]+4259657740&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[1]+2763975236&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[4]+1272893353&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[7]+4139469664&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[10]+3200236656&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[13]+681279174&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[0]+3936430074&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[3]+3572445317&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[6]+76029189&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(C^R^O)+w[9]+3654602809&4294967295,v=C+(D<<4&4294967295|D>>>28),D=O+(v^C^R)+w[12]+3873151461&4294967295,O=v+(D<<11&4294967295|D>>>21),D=R+(O^v^C)+w[15]+530742520&4294967295,R=O+(D<<16&4294967295|D>>>16),D=C+(R^O^v)+w[2]+3299628645&4294967295,C=R+(D<<23&4294967295|D>>>9),D=v+(R^(C|~O))+w[0]+4096336452&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[7]+1126891415&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[14]+2878612391&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[5]+4237533241&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[12]+1700485571&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[3]+2399980690&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[10]+4293915773&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[1]+2240044497&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[8]+1873313359&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[15]+4264355552&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[6]+2734768916&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[13]+1309151649&4294967295,C=R+(D<<21&4294967295|D>>>11),D=v+(R^(C|~O))+w[4]+4149444226&4294967295,v=C+(D<<6&4294967295|D>>>26),D=O+(C^(v|~R))+w[11]+3174756917&4294967295,O=v+(D<<10&4294967295|D>>>22),D=R+(v^(O|~C))+w[2]+718787259&4294967295,R=O+(D<<15&4294967295|D>>>17),D=C+(O^(R|~v))+w[9]+3951481745&4294967295,A.g[0]=A.g[0]+v&4294967295,A.g[1]=A.g[1]+(R+(D<<21&4294967295|D>>>11))&4294967295,A.g[2]=A.g[2]+R&4294967295,A.g[3]=A.g[3]+O&4294967295}r.prototype.u=function(A,v){v===void 0&&(v=A.length);for(var C=v-this.blockSize,w=this.B,R=this.h,O=0;O<v;){if(R==0)for(;O<=C;)i(this,A,O),O+=this.blockSize;if(typeof A=="string"){for(;O<v;)if(w[R++]=A.charCodeAt(O++),R==this.blockSize){i(this,w),R=0;break}}else for(;O<v;)if(w[R++]=A[O++],R==this.blockSize){i(this,w),R=0;break}}this.h=R,this.o+=v},r.prototype.v=function(){var A=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);A[0]=128;for(var v=1;v<A.length-8;++v)A[v]=0;var C=8*this.o;for(v=A.length-8;v<A.length;++v)A[v]=C&255,C/=256;for(this.u(A),A=Array(16),v=C=0;4>v;++v)for(var w=0;32>w;w+=8)A[C++]=this.g[v]>>>w&255;return A};function o(A,v){var C=a;return Object.prototype.hasOwnProperty.call(C,A)?C[A]:C[A]=v(A)}function s(A,v){this.h=v;for(var C=[],w=!0,R=A.length-1;0<=R;R--){var O=A[R]|0;w&&O==v||(C[R]=O,w=!1)}this.g=C}var a={};function c(A){return-128<=A&&128>A?o(A,function(v){return new s([v|0],0>v?-1:0)}):new s([A|0],0>A?-1:0)}function l(A){if(isNaN(A)||!isFinite(A))return h;if(0>A)return S(l(-A));for(var v=[],C=1,w=0;A>=C;w++)v[w]=A/C|0,C*=4294967296;return new s(v,0)}function d(A,v){if(A.length==0)throw Error("number format error: empty string");if(v=v||10,2>v||36<v)throw Error("radix out of range: "+v);if(A.charAt(0)=="-")return S(d(A.substring(1),v));if(0<=A.indexOf("-"))throw Error('number format error: interior "-" character');for(var C=l(Math.pow(v,8)),w=h,R=0;R<A.length;R+=8){var O=Math.min(8,A.length-R),D=parseInt(A.substring(R,R+O),v);8>O?(O=l(Math.pow(v,O)),w=w.j(O).add(l(D))):(w=w.j(C),w=w.add(l(D)))}return w}var h=c(0),f=c(1),g=c(16777216);t=s.prototype,t.m=function(){if(I(this))return-S(this).m();for(var A=0,v=1,C=0;C<this.g.length;C++){var w=this.i(C);A+=(0<=w?w:4294967296+w)*v,v*=4294967296}return A},t.toString=function(A){if(A=A||10,2>A||36<A)throw Error("radix out of range: "+A);if(E(this))return"0";if(I(this))return"-"+S(this).toString(A);for(var v=l(Math.pow(A,6)),C=this,w="";;){var R=te(C,v).g;C=L(C,R.j(v));var O=((0<C.g.length?C.g[0]:C.h)>>>0).toString(A);if(C=R,E(C))return O+w;for(;6>O.length;)O="0"+O;w=O+w}},t.i=function(A){return 0>A?0:A<this.g.length?this.g[A]:this.h};function E(A){if(A.h!=0)return!1;for(var v=0;v<A.g.length;v++)if(A.g[v]!=0)return!1;return!0}function I(A){return A.h==-1}t.l=function(A){return A=L(this,A),I(A)?-1:E(A)?0:1};function S(A){for(var v=A.g.length,C=[],w=0;w<v;w++)C[w]=~A.g[w];return new s(C,~A.h).add(f)}t.abs=function(){return I(this)?S(this):this},t.add=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0,R=0;R<=v;R++){var O=w+(this.i(R)&65535)+(A.i(R)&65535),D=(O>>>16)+(this.i(R)>>>16)+(A.i(R)>>>16);w=D>>>16,O&=65535,D&=65535,C[R]=D<<16|O}return new s(C,C[C.length-1]&-2147483648?-1:0)};function L(A,v){return A.add(S(v))}t.j=function(A){if(E(this)||E(A))return h;if(I(this))return I(A)?S(this).j(S(A)):S(S(this).j(A));if(I(A))return S(this.j(S(A)));if(0>this.l(g)&&0>A.l(g))return l(this.m()*A.m());for(var v=this.g.length+A.g.length,C=[],w=0;w<2*v;w++)C[w]=0;for(w=0;w<this.g.length;w++)for(var R=0;R<A.g.length;R++){var O=this.i(w)>>>16,D=this.i(w)&65535,Mr=A.i(R)>>>16,Jr=A.i(R)&65535;C[2*w+2*R]+=D*Jr,j(C,2*w+2*R),C[2*w+2*R+1]+=O*Jr,j(C,2*w+2*R+1),C[2*w+2*R+1]+=D*Mr,j(C,2*w+2*R+1),C[2*w+2*R+2]+=O*Mr,j(C,2*w+2*R+2)}for(w=0;w<v;w++)C[w]=C[2*w+1]<<16|C[2*w];for(w=v;w<2*v;w++)C[w]=0;return new s(C,0)};function j(A,v){for(;(A[v]&65535)!=A[v];)A[v+1]+=A[v]>>>16,A[v]&=65535,v++}function K(A,v){this.g=A,this.h=v}function te(A,v){if(E(v))throw Error("division by zero");if(E(A))return new K(h,h);if(I(A))return v=te(S(A),v),new K(S(v.g),S(v.h));if(I(v))return v=te(A,S(v)),new K(S(v.g),v.h);if(30<A.g.length){if(I(A)||I(v))throw Error("slowDivide_ only works with positive integers.");for(var C=f,w=v;0>=w.l(A);)C=pe(C),w=pe(w);var R=ie(C,1),O=ie(w,1);for(w=ie(w,2),C=ie(C,2);!E(w);){var D=O.add(w);0>=D.l(A)&&(R=R.add(C),O=D),w=ie(w,1),C=ie(C,1)}return v=L(A,R.j(v)),new K(R,v)}for(R=h;0<=A.l(v);){for(C=Math.max(1,Math.floor(A.m()/v.m())),w=Math.ceil(Math.log(C)/Math.LN2),w=48>=w?1:Math.pow(2,w-48),O=l(C),D=O.j(v);I(D)||0<D.l(A);)C-=w,O=l(C),D=O.j(v);E(O)&&(O=f),R=R.add(O),A=L(A,D)}return new K(R,A)}t.A=function(A){return te(this,A).h},t.and=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)&A.i(w);return new s(C,this.h&A.h)},t.or=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)|A.i(w);return new s(C,this.h|A.h)},t.xor=function(A){for(var v=Math.max(this.g.length,A.g.length),C=[],w=0;w<v;w++)C[w]=this.i(w)^A.i(w);return new s(C,this.h^A.h)};function pe(A){for(var v=A.g.length+1,C=[],w=0;w<v;w++)C[w]=A.i(w)<<1|A.i(w-1)>>>31;return new s(C,A.h)}function ie(A,v){var C=v>>5;v%=32;for(var w=A.g.length-C,R=[],O=0;O<w;O++)R[O]=0<v?A.i(O+C)>>>v|A.i(O+C+1)<<32-v:A.i(O+C);return new s(R,A.h)}r.prototype.digest=r.prototype.v,r.prototype.reset=r.prototype.s,r.prototype.update=r.prototype.u,jb=f$.Md5=r,s.prototype.add=s.prototype.add,s.prototype.multiply=s.prototype.j,s.prototype.modulo=s.prototype.A,s.prototype.compare=s.prototype.l,s.prototype.toNumber=s.prototype.m,s.prototype.toString=s.prototype.toString,s.prototype.getBits=s.prototype.i,s.fromNumber=l,s.fromString=d,is=f$.Integer=s}).apply(typeof h$<"u"?h$:typeof self<"u"?self:typeof window<"u"?window:{});var EI=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},os={};var Hb,pse,Gd,$b,Tg,_I,Wb,zb,qb;(function(){var t,e=typeof Object.defineProperties=="function"?Object.defineProperty:function(u,p,m){return u==Array.prototype||u==Object.prototype||(u[p]=m.value),u};function n(u){u=[typeof globalThis=="object"&&globalThis,u,typeof window=="object"&&window,typeof self=="object"&&self,typeof EI=="object"&&EI];for(var p=0;p<u.length;++p){var m=u[p];if(m&&m.Math==Math)return m}throw Error("Cannot find global object")}var r=n(this);function i(u,p){if(p)e:{var m=r;u=u.split(".");for(var _=0;_<u.length-1;_++){var M=u[_];if(!(M in m))break e;m=m[M]}u=u[u.length-1],_=m[u],p=p(_),p!=_&&p!=null&&e(m,u,{configurable:!0,writable:!0,value:p})}}function o(u,p){u instanceof String&&(u+="");var m=0,_=!1,M={next:function(){if(!_&&m<u.length){var F=m++;return{value:p(F,u[F]),done:!1}}return _=!0,{done:!0,value:void 0}}};return M[Symbol.iterator]=function(){return M},M}i("Array.prototype.values",function(u){return u||function(){return o(this,function(p,m){return m})}});var s=s||{},a=this||self;function c(u){var p=typeof u;return p=p!="object"?p:u?Array.isArray(u)?"array":p:"null",p=="array"||p=="object"&&typeof u.length=="number"}function l(u){var p=typeof u;return p=="object"&&u!=null||p=="function"}function d(u,p,m){return u.call.apply(u.bind,arguments)}function h(u,p,m){if(!u)throw Error();if(2<arguments.length){var _=Array.prototype.slice.call(arguments,2);return function(){var M=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(M,_),u.apply(p,M)}}return function(){return u.apply(p,arguments)}}function f(u,p,m){return f=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?d:h,f.apply(null,arguments)}function g(u,p){var m=Array.prototype.slice.call(arguments,1);return function(){var _=m.slice();return _.push.apply(_,arguments),u.apply(this,_)}}function E(u,p){function m(){}m.prototype=p.prototype,u.aa=p.prototype,u.prototype=new m,u.prototype.constructor=u,u.Qb=function(_,M,F){for(var Q=Array(arguments.length-2),it=2;it<arguments.length;it++)Q[it-2]=arguments[it];return p.prototype[M].apply(_,Q)}}function I(u){let p=u.length;if(0<p){let m=Array(p);for(let _=0;_<p;_++)m[_]=u[_];return m}return[]}function S(u,p){for(let m=1;m<arguments.length;m++){let _=arguments[m];if(c(_)){let M=u.length||0,F=_.length||0;u.length=M+F;for(let Q=0;Q<F;Q++)u[M+Q]=_[Q]}else u.push(_)}}class L{constructor(p,m){this.i=p,this.j=m,this.h=0,this.g=null}get(){let p;return 0<this.h?(this.h--,p=this.g,this.g=p.next,p.next=null):p=this.i(),p}}function j(u){return/^[\s\xa0]*$/.test(u)}function K(){var u=a.navigator;return u&&(u=u.userAgent)?u:""}function te(u){return te[" "](u),u}te[" "]=function(){};var pe=K().indexOf("Gecko")!=-1&&!(K().toLowerCase().indexOf("webkit")!=-1&&K().indexOf("Edge")==-1)&&!(K().indexOf("Trident")!=-1||K().indexOf("MSIE")!=-1)&&K().indexOf("Edge")==-1;function ie(u,p,m){for(let _ in u)p.call(m,u[_],_,u)}function A(u,p){for(let m in u)p.call(void 0,u[m],m,u)}function v(u){let p={};for(let m in u)p[m]=u[m];return p}let C="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function w(u,p){let m,_;for(let M=1;M<arguments.length;M++){_=arguments[M];for(m in _)u[m]=_[m];for(let F=0;F<C.length;F++)m=C[F],Object.prototype.hasOwnProperty.call(_,m)&&(u[m]=_[m])}}function R(u){var p=1;u=u.split(":");let m=[];for(;0<p&&u.length;)m.push(u.shift()),p--;return u.length&&m.push(u.join(":")),m}function O(u){a.setTimeout(()=>{throw u},0)}function D(){var u=Lh;let p=null;return u.g&&(p=u.g,u.g=u.g.next,u.g||(u.h=null),p.next=null),p}class Mr{constructor(){this.h=this.g=null}add(p,m){let _=Jr.get();_.set(p,m),this.h?this.h.next=_:this.g=_,this.h=_}}var Jr=new L(()=>new _m,u=>u.reset());class _m{constructor(){this.next=this.g=this.h=null}set(p,m){this.h=p,this.g=m,this.next=null}reset(){this.next=this.g=this.h=null}}let Lr,Pa=!1,Lh=new Mr,xa=()=>{let u=a.Promise.resolve(void 0);Lr=()=>{u.then(Ph)}};var Ph=()=>{for(var u;u=D();){try{u.h.call(u.g)}catch(m){O(m)}var p=Jr;p.j(u),100>p.h&&(p.h++,u.next=p.g,p.g=u)}Pa=!1};function Zr(){this.s=this.s,this.C=this.C}Zr.prototype.s=!1,Zr.prototype.ma=function(){this.s||(this.s=!0,this.N())},Zr.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function tn(u,p){this.type=u,this.g=this.target=p,this.defaultPrevented=!1}tn.prototype.h=function(){this.defaultPrevented=!0};var Kv=(function(){if(!a.addEventListener||!Object.defineProperty)return!1;var u=!1,p=Object.defineProperty({},"passive",{get:function(){u=!0}});try{let m=()=>{};a.addEventListener("test",m,p),a.removeEventListener("test",m,p)}catch{}return u})();function ka(u,p){if(tn.call(this,u?u.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,u){var m=this.type=u.type,_=u.changedTouches&&u.changedTouches.length?u.changedTouches[0]:null;if(this.target=u.target||u.srcElement,this.g=p,p=u.relatedTarget){if(pe){e:{try{te(p.nodeName);var M=!0;break e}catch{}M=!1}M||(p=null)}}else m=="mouseover"?p=u.fromElement:m=="mouseout"&&(p=u.toElement);this.relatedTarget=p,_?(this.clientX=_.clientX!==void 0?_.clientX:_.pageX,this.clientY=_.clientY!==void 0?_.clientY:_.pageY,this.screenX=_.screenX||0,this.screenY=_.screenY||0):(this.clientX=u.clientX!==void 0?u.clientX:u.pageX,this.clientY=u.clientY!==void 0?u.clientY:u.pageY,this.screenX=u.screenX||0,this.screenY=u.screenY||0),this.button=u.button,this.key=u.key||"",this.ctrlKey=u.ctrlKey,this.altKey=u.altKey,this.shiftKey=u.shiftKey,this.metaKey=u.metaKey,this.pointerId=u.pointerId||0,this.pointerType=typeof u.pointerType=="string"?u.pointerType:nt[u.pointerType]||"",this.state=u.state,this.i=u,u.defaultPrevented&&ka.aa.h.call(this)}}E(ka,tn);var nt={2:"touch",3:"pen",4:"mouse"};ka.prototype.h=function(){ka.aa.h.call(this);var u=this.i;u.preventDefault?u.preventDefault():u.returnValue=!1};var Fa="closure_listenable_"+(1e6*Math.random()|0),Yv=0;function Xv(u,p,m,_,M){this.listener=u,this.proxy=null,this.src=p,this.type=m,this.capture=!!_,this.ha=M,this.key=++Yv,this.da=this.fa=!1}function zl(u){u.da=!0,u.listener=null,u.proxy=null,u.src=null,u.ha=null}function ql(u){this.src=u,this.g={},this.h=0}ql.prototype.add=function(u,p,m,_,M){var F=u.toString();u=this.g[F],u||(u=this.g[F]=[],this.h++);var Q=Kl(u,p,_,M);return-1<Q?(p=u[Q],m||(p.fa=!1)):(p=new Xv(p,this.src,F,!!_,M),p.fa=m,u.push(p)),p};function xh(u,p){var m=p.type;if(m in u.g){var _=u.g[m],M=Array.prototype.indexOf.call(_,p,void 0),F;(F=0<=M)&&Array.prototype.splice.call(_,M,1),F&&(zl(p),u.g[m].length==0&&(delete u.g[m],u.h--))}}function Kl(u,p,m,_){for(var M=0;M<u.length;++M){var F=u[M];if(!F.da&&F.listener==p&&F.capture==!!m&&F.ha==_)return M}return-1}var kh="closure_lm_"+(1e6*Math.random()|0),Yl={};function rt(u,p,m,_,M){if(_&&_.once)return Ql(u,p,m,_,M);if(Array.isArray(p)){for(var F=0;F<p.length;F++)rt(u,p[F],m,_,M);return null}return m=Zl(m),u&&u[Fa]?u.K(p,m,l(_)?!!_.capture:!!_,M):Xl(u,p,m,!1,_,M)}function Xl(u,p,m,_,M,F){if(!p)throw Error("Invalid event type");var Q=l(M)?!!M.capture:!!M,it=Jl(u);if(it||(u[kh]=it=new ql(u)),m=it.add(p,m,_,Q,F),m.proxy)return m;if(_=lt(),m.proxy=_,_.src=u,_.listener=m,u.addEventListener)Kv||(M=Q),M===void 0&&(M=!1),u.addEventListener(p.toString(),_,M);else if(u.attachEvent)u.attachEvent(Fh(p.toString()),_);else if(u.addListener&&u.removeListener)u.addListener(_);else throw Error("addEventListener and attachEvent are unavailable.");return m}function lt(){function u(m){return p.call(u.src,u.listener,m)}let p=wi;return u}function Ql(u,p,m,_,M){if(Array.isArray(p)){for(var F=0;F<p.length;F++)Ql(u,p[F],m,_,M);return null}return m=Zl(m),u&&u[Fa]?u.L(p,m,l(_)?!!_.capture:!!_,M):Xl(u,p,m,!0,_,M)}function ur(u,p,m,_,M){if(Array.isArray(p))for(var F=0;F<p.length;F++)ur(u,p[F],m,_,M);else _=l(_)?!!_.capture:!!_,m=Zl(m),u&&u[Fa]?(u=u.i,p=String(p).toString(),p in u.g&&(F=u.g[p],m=Kl(F,m,_,M),-1<m&&(zl(F[m]),Array.prototype.splice.call(F,m,1),F.length==0&&(delete u.g[p],u.h--)))):u&&(u=Jl(u))&&(p=u.g[p.toString()],u=-1,p&&(u=Kl(p,m,_,M)),(m=-1<u?p[u]:null)&&So(m))}function So(u){if(typeof u!="number"&&u&&!u.da){var p=u.src;if(p&&p[Fa])xh(p.i,u);else{var m=u.type,_=u.proxy;p.removeEventListener?p.removeEventListener(m,_,u.capture):p.detachEvent?p.detachEvent(Fh(m),_):p.addListener&&p.removeListener&&p.removeListener(_),(m=Jl(p))?(xh(m,u),m.h==0&&(m.src=null,p[kh]=null)):zl(u)}}}function Fh(u){return u in Yl?Yl[u]:Yl[u]="on"+u}function wi(u,p){if(u.da)u=!0;else{p=new ka(p,this);var m=u.listener,_=u.ha||u.src;u.fa&&So(u),u=m.call(_,p)}return u}function Jl(u){return u=u[kh],u instanceof ql?u:null}var Ua="__closure_events_fn_"+(1e9*Math.random()>>>0);function Zl(u){return typeof u=="function"?u:(u[Ua]||(u[Ua]=function(p){return u.handleEvent(p)}),u[Ua])}function bt(){Zr.call(this),this.i=new ql(this),this.M=this,this.F=null}E(bt,Zr),bt.prototype[Fa]=!0,bt.prototype.removeEventListener=function(u,p,m,_){ur(this,u,p,m,_)};function dt(u,p){var m,_=u.F;if(_)for(m=[];_;_=_.F)m.push(_);if(u=u.M,_=p.type||p,typeof p=="string")p=new tn(p,u);else if(p instanceof tn)p.target=p.target||u;else{var M=p;p=new tn(_,u),w(p,M)}if(M=!0,m)for(var F=m.length-1;0<=F;F--){var Q=p.g=m[F];M=Pr(Q,_,!0,p)&&M}if(Q=p.g=u,M=Pr(Q,_,!0,p)&&M,M=Pr(Q,_,!1,p)&&M,m)for(F=0;F<m.length;F++)Q=p.g=m[F],M=Pr(Q,_,!1,p)&&M}bt.prototype.N=function(){if(bt.aa.N.call(this),this.i){var u=this.i,p;for(p in u.g){for(var m=u.g[p],_=0;_<m.length;_++)zl(m[_]);delete u.g[p],u.h--}}this.F=null},bt.prototype.K=function(u,p,m,_){return this.i.add(String(u),p,!1,m,_)},bt.prototype.L=function(u,p,m,_){return this.i.add(String(u),p,!0,m,_)};function Pr(u,p,m,_){if(p=u.i.g[String(p)],!p)return!0;p=p.concat();for(var M=!0,F=0;F<p.length;++F){var Q=p[F];if(Q&&!Q.da&&Q.capture==m){var it=Q.listener,mn=Q.ha||Q.src;Q.fa&&xh(u.i,Q),M=it.call(mn,_)!==!1&&M}}return M&&!_.defaultPrevented}function bi(u,p,m){if(typeof u=="function")m&&(u=f(u,m));else if(u&&typeof u.handleEvent=="function")u=f(u.handleEvent,u);else throw Error("Invalid listener argument");return 2147483647<Number(p)?-1:a.setTimeout(u,p||0)}function eu(u){u.g=bi(()=>{u.g=null,u.i&&(u.i=!1,eu(u))},u.l);let p=u.h;u.h=null,u.m.apply(null,p)}class tu extends Zr{constructor(p,m){super(),this.m=p,this.l=m,this.h=null,this.i=!1,this.g=null}j(p){this.h=arguments,this.g?this.i=!0:eu(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Oi(u){Zr.call(this),this.h=u,this.g={}}E(Oi,Zr);var nu=[];function Ao(u){ie(u.g,function(p,m){this.g.hasOwnProperty(m)&&So(p)},u),u.g={}}Oi.prototype.N=function(){Oi.aa.N.call(this),Ao(this)},Oi.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var hs=a.JSON.stringify,ru=a.JSON.parse,Tm=class{stringify(u){return a.JSON.stringify(u,void 0)}parse(u){return a.JSON.parse(u,void 0)}};function iu(){}iu.prototype.h=null;function Uh(u){return u.h||(u.h=u.i())}function ou(){}var Co={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function ei(){tn.call(this,"d")}E(ei,tn);function Mi(){tn.call(this,"c")}E(Mi,tn);var Gn={},Vh=null;function Va(){return Vh=Vh||new bt}Gn.La="serverreachability";function Bh(u){tn.call(this,Gn.La,u)}E(Bh,tn);function fs(u){let p=Va();dt(p,new Bh(p))}Gn.STAT_EVENT="statevent";function Gh(u,p){tn.call(this,Gn.STAT_EVENT,u),this.stat=p}E(Gh,tn);function Ot(u){let p=Va();dt(p,new Gh(p,u))}Gn.Ma="timingevent";function Ba(u,p){tn.call(this,Gn.Ma,u),this.size=p}E(Ba,tn);function An(u,p){if(typeof u!="function")throw Error("Fn must not be null and must be a function");return a.setTimeout(function(){u()},p)}function xr(){this.g=!0}xr.prototype.xa=function(){this.g=!1};function jh(u,p,m,_,M,F){u.info(function(){if(u.g)if(F)for(var Q="",it=F.split("&"),mn=0;mn<it.length;mn++){var Ve=it[mn].split("=");if(1<Ve.length){var Cn=Ve[0];Ve=Ve[1];var Dn=Cn.split("_");Q=2<=Dn.length&&Dn[1]=="type"?Q+(Cn+"="+Ve+"&"):Q+(Cn+"=redacted&")}}else Q=null;else Q=F;return"XMLHTTP REQ ("+_+") [attempt "+M+"]: "+p+`
|
|
154
154
|
`+m+`
|
|
155
155
|
`+Q})}function Hh(u,p,m,_,M,F,Q){u.info(function(){return"XMLHTTP RESP ("+_+") [ attempt "+M+"]: "+p+`
|
|
156
156
|
`+m+`
|
|
@@ -171,4 +171,4 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
171
171
|
`+e.join(`
|
|
172
172
|
`)+`
|
|
173
173
|
)`}copy(e,n){let r=new t;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=n,r}};var Ev=class{constructor(){this.fa=new ft(ee.comparator)}track(e){let n=e.doc.key,r=this.fa.get(n);r?e.type!==0&&r.type===3?this.fa=this.fa.insert(n,e):e.type===3&&r.type!==1?this.fa=this.fa.insert(n,{type:r.type,doc:e.doc}):e.type===2&&r.type===2?this.fa=this.fa.insert(n,{type:2,doc:e.doc}):e.type===2&&r.type===0?this.fa=this.fa.insert(n,{type:0,doc:e.doc}):e.type===1&&r.type===0?this.fa=this.fa.remove(n):e.type===1&&r.type===2?this.fa=this.fa.insert(n,{type:1,doc:r.doc}):e.type===0&&r.type===1?this.fa=this.fa.insert(n,{type:2,doc:e.doc}):re(63341,{At:e,ga:r}):this.fa=this.fa.insert(n,e)}pa(){let e=[];return this.fa.inorderTraversal((n,r)=>{e.push(r)}),e}},vh=class t{constructor(e,n,r,i,o,s,a,c,l){this.query=e,this.docs=n,this.oldDocs=r,this.docChanges=i,this.mutatedKeys=o,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=c,this.hasCachedResults=l}static fromInitialDocuments(e,n,r,i,o){let s=[];return n.forEach(a=>{s.push({type:0,doc:a})}),new t(e,n,mv.emptySet(n),s,r,i,!0,!1,o)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&xv(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let n=this.docChanges,r=e.docChanges;if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i].type!==r[i].type||!n[i].doc.isEqual(r[i].doc))return!1;return!0}};var L0=class{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}},P0=class{constructor(){this.queries=_3(),this.onlineState="Unknown",this.Da=new Set}terminate(){(function(n,r){let i=oe(n),o=i.queries;i.queries=_3(),o.forEach((s,a)=>{for(let c of a.wa)c.onError(r)})})(this,new $(x.ABORTED,"Firestore shutting down"))}};function _3(){return new Ci(t=>dW(t),xv)}function OM(t,e){return y(this,null,function*(){let n=oe(t),r=3,i=e.query,o=n.queries.get(i);o?!o.Sa()&&e.ba()&&(r=2):(o=new L0,r=e.ba()?0:1);try{switch(r){case 0:o.ya=yield n.onListen(i,!0);break;case 1:o.ya=yield n.onListen(i,!1);break;case 2:yield n.onFirstRemoteStoreListen(i)}}catch(s){let a=bM(s,`Initialization of query '${Yd(e.query)}' failed`);return void e.onError(a)}n.queries.set(i,o),o.wa.push(e),e.va(n.onlineState),o.ya&&e.Ca(o.ya)&&LM(n)})}function MM(t,e){return y(this,null,function*(){let n=oe(t),r=e.query,i=3,o=n.queries.get(r);if(o){let s=o.wa.indexOf(e);s>=0&&(o.wa.splice(s,1),o.wa.length===0?i=e.ba()?0:1:!o.Sa()&&e.ba()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}})}function $ae(t,e){let n=oe(t),r=!1;for(let i of e){let o=i.query,s=n.queries.get(o);if(s){for(let a of s.wa)a.Ca(i)&&(r=!0);s.ya=i}}r&&LM(n)}function Wae(t,e,n){let r=oe(t),i=r.queries.get(e);if(i)for(let o of i.wa)o.onError(n);r.queries.delete(e)}function LM(t){t.Da.forEach(e=>{e.next()})}var x0,T3;(T3=x0||(x0={})).Fa="default",T3.Cache="cache";var im=class{constructor(e,n,r){this.query=e,this.Ma=n,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=r||{}}Ca(e){if(!this.options.includeMetadataChanges){let r=[];for(let i of e.docChanges)i.type!==3&&r.push(i);e=new vh(e.query,e.docs,e.oldDocs,r,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let n=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),n=!0):this.Ba(e,this.onlineState)&&(this.La(e),n=!0),this.Oa=e,n}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let n=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),n=!0),n}Ba(e,n){if(!e.fromCache||!this.ba())return!0;let r=n!=="Offline";return(!this.options.ka||!r)&&(!e.docs.isEmpty()||e.hasCachedResults||n==="Offline")}Na(e){if(e.docChanges.length>0)return!0;let n=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!n)&&this.options.includeMetadataChanges===!0}La(e){e=vh.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==x0.Cache}};var _v=class{constructor(e){this.key=e}},Tv=class{constructor(e){this.key=e}},k0=class{constructor(e,n){this.query=e,this.Ha=n,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=Me(),this.mutatedKeys=Me(),this.Xa=fW(e),this.eu=new mv(this.Xa)}get tu(){return this.Ha}nu(e,n){let r=n?n.ru:new Ev,i=n?n.eu:this.eu,o=n?n.mutatedKeys:this.mutatedKeys,s=i,a=!1,c=this.query.limitType==="F"&&i.size===this.query.limit?i.last():null,l=this.query.limitType==="L"&&i.size===this.query.limit?i.first():null;if(e.inorderTraversal((d,h)=>{let f=i.get(d),g=pm(this.query,h)?h:null,E=!!f&&this.mutatedKeys.has(f.key),I=!!g&&(g.hasLocalMutations||this.mutatedKeys.has(g.key)&&g.hasCommittedMutations),S=!1;f&&g?f.data.isEqual(g.data)?E!==I&&(r.track({type:3,doc:g}),S=!0):this.iu(f,g)||(r.track({type:2,doc:g}),S=!0,(c&&this.Xa(g,c)>0||l&&this.Xa(g,l)<0)&&(a=!0)):!f&&g?(r.track({type:0,doc:g}),S=!0):f&&!g&&(r.track({type:1,doc:f}),S=!0,(c||l)&&(a=!0)),S&&(g?(s=s.add(g),o=I?o.add(d):o.delete(d)):(s=s.delete(d),o=o.delete(d)))}),this.query.limit!==null)for(;s.size>this.query.limit;){let d=this.query.limitType==="F"?s.last():s.first();s=s.delete(d.key),o=o.delete(d.key),r.track({type:1,doc:d})}return{eu:s,ru:r,Ds:a,mutatedKeys:o}}iu(e,n){return e.hasLocalMutations&&n.hasCommittedMutations&&!n.hasLocalMutations}applyChanges(e,n,r,i){let o=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let s=e.ru.pa();s.sort((d,h)=>(function(g,E){let I=S=>{switch(S){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return re(20277,{At:S})}};return I(g)-I(E)})(d.type,h.type)||this.Xa(d.doc,h.doc)),this.su(r),i=i!=null&&i;let a=n&&!i?this.ou():[],c=this.Za.size===0&&this.current&&!i?1:0,l=c!==this.Ya;return this.Ya=c,s.length!==0||l?{snapshot:new vh(this.query,e.eu,o,s,e.mutatedKeys,c===0,l,!1,!!r&&r.resumeToken.approximateByteSize()>0),_u:a}:{_u:a}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({eu:this.eu,ru:new Ev,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach(n=>this.Ha=this.Ha.add(n)),e.modifiedDocuments.forEach(n=>{}),e.removedDocuments.forEach(n=>this.Ha=this.Ha.delete(n)),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=Me(),this.eu.forEach(r=>{this.au(r.key)&&(this.Za=this.Za.add(r.key))});let n=[];return e.forEach(r=>{this.Za.has(r)||n.push(new Tv(r))}),this.Za.forEach(r=>{e.has(r)||n.push(new _v(r))}),n}uu(e){this.Ha=e.qs,this.Za=Me();let n=this.nu(e.documents);return this.applyChanges(n,!0)}cu(){return vh.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,this.Ya===0,this.hasCachedResults)}},bh="SyncEngine",F0=class{constructor(e,n,r){this.query=e,this.targetId=n,this.view=r}},U0=class{constructor(e){this.key=e,this.lu=!1}},V0=class{constructor(e,n,r,i,o,s){this.localStore=e,this.remoteStore=n,this.eventManager=r,this.sharedClientState=i,this.currentUser=o,this.maxConcurrentLimboResolutions=s,this.hu={},this.Pu=new Ci(a=>dW(a),xv),this.Tu=new Map,this.Iu=new Set,this.du=new ft(ee.comparator),this.Eu=new Map,this.Au=new em,this.Ru={},this.Vu=new Map,this.mu=Th.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return this.fu===!0}};function zae(t,e,n=!0){return y(this,null,function*(){let r=Vv(t),i,o=r.Pu.get(e);return o?(r.sharedClientState.addLocalQueryTarget(o.targetId),i=o.view.cu()):i=yield l6(r,e,n,!0),i})}function qae(t,e){return y(this,null,function*(){let n=Vv(t);yield l6(n,e,!0,!1)})}function l6(t,e,n,r){return y(this,null,function*(){let i=yield lv(t.localStore,br(e)),o=i.targetId,s=t.sharedClientState.addLocalQueryTarget(o,n),a;return r&&(a=yield PM(t,e,o,s==="current",i.resumeToken)),t.isPrimaryClient&&n&&Uv(t.remoteStore,i),a})}function PM(t,e,n,r,i){return y(this,null,function*(){t.gu=(h,f,g)=>(function(I,S,L,j){return y(this,null,function*(){let K=S.view.nu(L);K.Ds&&(K=yield _0(I.localStore,S.query,!1).then(({documents:A})=>S.view.nu(A,K)));let te=j&&j.targetChanges.get(S.targetId),pe=j&&j.targetMismatches.get(S.targetId)!=null,ie=S.view.applyChanges(K,I.isPrimaryClient,te,pe);return B0(I,S.targetId,ie._u),ie.snapshot})})(t,h,f,g);let o=yield _0(t.localStore,e,!0),s=new k0(e,o.qs),a=s.nu(o.documents),c=Xg.createSynthesizedTargetChangeForCurrentChange(n,r&&t.onlineState!=="Offline",i),l=s.applyChanges(a,t.isPrimaryClient,c);B0(t,n,l._u);let d=new F0(e,n,s);return t.Pu.set(e,d),t.Tu.has(n)?t.Tu.get(n).push(e):t.Tu.set(n,[e]),l.snapshot})}function Kae(t,e,n){return y(this,null,function*(){let r=oe(t),i=r.Pu.get(e),o=r.Tu.get(i.targetId);if(o.length>1)return r.Tu.set(i.targetId,o.filter(s=>!xv(s,e))),void r.Pu.delete(e);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||(yield yh(r.localStore,i.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(i.targetId),n&&Ih(r.remoteStore,i.targetId),Sh(r,i.targetId)}).catch(wa))):(Sh(r,i.targetId),yield yh(r.localStore,i.targetId,!0))})}function Yae(t,e){return y(this,null,function*(){let n=oe(t),r=n.Pu.get(e),i=n.Tu.get(r.targetId);n.isPrimaryClient&&i.length===1&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),Ih(n.remoteStore,r.targetId))})}function Xae(t,e,n){return y(this,null,function*(){let r=UM(t);try{let i=yield(function(s,a){let c=oe(s),l=yt.now(),d=a.reduce((g,E)=>g.add(E.key),Me()),h,f;return c.persistence.runTransaction("Locally write mutations","readwrite",g=>{let E=wr(),I=Me();return c.Os.getEntries(g,d).next(S=>{E=S,E.forEach((L,j)=>{j.isValidDocument()||(I=I.add(L))})}).next(()=>c.localDocuments.getOverlayedDocuments(g,E)).next(S=>{h=S;let L=[];for(let j of a){let K=cae(j,h.get(j.key).overlayedDocument);K!=null&&L.push(new Di(j.key,K,rW(K.value.mapValue),Sn.exists(!0)))}return c.mutationQueue.addMutationBatch(g,l,L,a)}).next(S=>{f=S;let L=S.applyToLocalDocumentSet(h,I);return c.documentOverlayCache.saveOverlays(g,S.batchId,L)})}).then(()=>({batchId:f.batchId,changes:gW(h)}))})(r.localStore,e);r.sharedClientState.addPendingMutation(i.batchId),(function(s,a,c){let l=s.Ru[s.currentUser.toKey()];l||(l=new ft(Ie)),l=l.insert(a,c),s.Ru[s.currentUser.toKey()]=l})(r,i.batchId,n),yield Ma(r,i.changes),yield Nh(r.remoteStore)}catch(i){let o=bM(i,"Failed to persist write");n.reject(o)}})}function u6(t,e){return y(this,null,function*(){let n=oe(t);try{let r=yield bae(n.localStore,e);e.targetChanges.forEach((i,o)=>{let s=n.Eu.get(o);s&&(se(i.addedDocuments.size+i.modifiedDocuments.size+i.removedDocuments.size<=1,22616),i.addedDocuments.size>0?s.lu=!0:i.modifiedDocuments.size>0?se(s.lu,14607):i.removedDocuments.size>0&&(se(s.lu,42227),s.lu=!1))}),yield Ma(n,r,e)}catch(r){yield wa(r)}})}function y3(t,e,n){let r=oe(t);if(r.isPrimaryClient&&n===0||!r.isPrimaryClient&&n===1){let i=[];r.Pu.forEach((o,s)=>{let a=s.view.va(e);a.snapshot&&i.push(a.snapshot)}),(function(s,a){let c=oe(s);c.onlineState=a;let l=!1;c.queries.forEach((d,h)=>{for(let f of h.wa)f.va(a)&&(l=!0)}),l&&LM(c)})(r.eventManager,e),i.length&&r.hu.J_(i),r.onlineState=e,r.isPrimaryClient&&r.sharedClientState.setOnlineState(e)}}function Qae(t,e,n){return y(this,null,function*(){let r=oe(t);r.sharedClientState.updateQueryState(e,"rejected",n);let i=r.Eu.get(e),o=i&&i.key;if(o){let s=new ft(ee.comparator);s=s.insert(o,Jt.newNoDocument(o,ce.min()));let a=Me().add(o),c=new Yg(ce.min(),new Map,new ft(Ie),s,a);yield u6(r,c),r.du=r.du.remove(o),r.Eu.delete(e),FM(r)}else yield yh(r.localStore,e,!1).then(()=>Sh(r,e,n)).catch(wa)})}function Jae(t,e){return y(this,null,function*(){let n=oe(t),r=e.batch.batchId;try{let i=yield wae(n.localStore,e);kM(n,r,null),xM(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),yield Ma(n,i)}catch(i){yield wa(i)}})}function Zae(t,e,n){return y(this,null,function*(){let r=oe(t);try{let i=yield(function(s,a){let c=oe(s);return c.persistence.runTransaction("Reject batch","readwrite-primary",l=>{let d;return c.mutationQueue.lookupMutationBatch(l,a).next(h=>(se(h!==null,37113),d=h.keys(),c.mutationQueue.removeMutationBatch(l,h))).next(()=>c.mutationQueue.performConsistencyCheck(l)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(l,d,a)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(l,d)).next(()=>c.localDocuments.getDocuments(l,d))})})(r.localStore,e);kM(r,e,n),xM(r,e),r.sharedClientState.updateMutationState(e,"rejected",n),yield Ma(r,i)}catch(i){yield wa(i)}})}function xM(t,e){(t.Vu.get(e)||[]).forEach(n=>{n.resolve()}),t.Vu.delete(e)}function kM(t,e,n){let r=oe(t),i=r.Ru[r.currentUser.toKey()];if(i){let o=i.get(e);o&&(n?o.reject(n):o.resolve(),i=i.remove(e)),r.Ru[r.currentUser.toKey()]=i}}function Sh(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(let r of t.Tu.get(e))t.Pu.delete(r),n&&t.hu.pu(r,n);t.Tu.delete(e),t.isPrimaryClient&&t.Au.zr(e).forEach(r=>{t.Au.containsKey(r)||d6(t,r)})}function d6(t,e){t.Iu.delete(e.path.canonicalString());let n=t.du.get(e);n!==null&&(Ih(t.remoteStore,n),t.du=t.du.remove(e),t.Eu.delete(n),FM(t))}function B0(t,e,n){for(let r of n)r instanceof _v?(t.Au.addReference(r.key,e),ece(t,r)):r instanceof Tv?(W(bh,"Document no longer in limbo: "+r.key),t.Au.removeReference(r.key,e),t.Au.containsKey(r.key)||d6(t,r.key)):re(19791,{yu:r})}function ece(t,e){let n=e.key,r=n.path.canonicalString();t.du.get(n)||t.Iu.has(r)||(W(bh,"New document in limbo: "+n),t.Iu.add(r),FM(t))}function FM(t){for(;t.Iu.size>0&&t.du.size<t.maxConcurrentLimboResolutions;){let e=t.Iu.values().next().value;t.Iu.delete(e);let n=new ee(Ue.fromString(e)),r=t.mu.next();t.Eu.set(r,new U0(n)),t.du=t.du.insert(n,r),Uv(t.remoteStore,new _h(br(fm(n.path)),r,"TargetPurposeLimboResolution",Rr.ue))}}function Ma(t,e,n){return y(this,null,function*(){let r=oe(t),i=[],o=[],s=[];r.Pu.isEmpty()||(r.Pu.forEach((a,c)=>{s.push(r.gu(c,e,n).then(l=>{var d;if((l||n)&&r.isPrimaryClient){let h=l?!l.fromCache:(d=n?.targetChanges.get(c.targetId))===null||d===void 0?void 0:d.current;r.sharedClientState.updateQueryState(c.targetId,h?"current":"not-current")}if(l){i.push(l);let h=g0.Es(c.targetId,l);o.push(h)}}))}),yield Promise.all(s),r.hu.J_(i),yield(function(c,l){return y(this,null,function*(){let d=oe(c);try{yield d.persistence.runTransaction("notifyLocalViewChanges","readwrite",h=>P.forEach(l,f=>P.forEach(f.Is,g=>d.persistence.referenceDelegate.addReference(h,f.targetId,g)).next(()=>P.forEach(f.ds,g=>d.persistence.referenceDelegate.removeReference(h,f.targetId,g)))))}catch(h){if(!ba(h))throw h;W(DM,"Failed to update sequence numbers: "+h)}for(let h of l){let f=h.targetId;if(!h.fromCache){let g=d.Fs.get(f),E=g.snapshotVersion,I=g.withLastLimboFreeSnapshotVersion(E);d.Fs=d.Fs.insert(f,I)}}})})(r.localStore,o))})}function tce(t,e){return y(this,null,function*(){let n=oe(t);if(!n.currentUser.isEqual(e)){W(bh,"User change. New user:",e.toKey());let r=yield YW(n.localStore,e);n.currentUser=e,(function(o,s){o.Vu.forEach(a=>{a.forEach(c=>{c.reject(new $(x.CANCELLED,s))})}),o.Vu.clear()})(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(e,r.removedBatchIds,r.addedBatchIds),yield Ma(n,r.Bs)}})}function nce(t,e){let n=oe(t),r=n.Eu.get(e);if(r&&r.lu)return Me().add(r.key);{let i=Me(),o=n.Tu.get(e);if(!o)return i;for(let s of o){let a=n.Pu.get(s);i=i.unionWith(a.view.tu)}return i}}function rce(t,e){return y(this,null,function*(){let n=oe(t),r=yield _0(n.localStore,e.query,!0),i=e.view.uu(r);return n.isPrimaryClient&&B0(n,e.targetId,i._u),i})}function ice(t,e){return y(this,null,function*(){let n=oe(t);return JW(n.localStore,e).then(r=>Ma(n,r))})}function oce(t,e,n,r){return y(this,null,function*(){let i=oe(t),o=yield(function(a,c){let l=oe(a),d=oe(l.mutationQueue);return l.persistence.runTransaction("Lookup mutation documents","readonly",h=>d.Xn(h,c).next(f=>f?l.localDocuments.getDocuments(h,f):P.resolve(null)))})(i.localStore,e);o!==null?(n==="pending"?yield Nh(i.remoteStore):n==="acknowledged"||n==="rejected"?(kM(i,e,r||null),xM(i,e),(function(a,c){oe(oe(a).mutationQueue).rr(c)})(i.localStore,e)):re(6720,"Unknown batchState",{wu:n}),yield Ma(i,o)):W(bh,"Cannot apply mutation batch with id: "+e)})}function sce(t,e){return y(this,null,function*(){let n=oe(t);if(Vv(n),UM(n),e===!0&&n.fu!==!0){let r=n.sharedClientState.getAllActiveQueryTargets(),i=yield I3(n,r.toArray());n.fu=!0,yield O0(n.remoteStore,!0);for(let o of i)Uv(n.remoteStore,o)}else if(e===!1&&n.fu!==!1){let r=[],i=Promise.resolve();n.Tu.forEach((o,s)=>{n.sharedClientState.isLocalQueryTarget(s)?r.push(s):i=i.then(()=>(Sh(n,s),yh(n.localStore,s,!0))),Ih(n.remoteStore,s)}),yield i,yield I3(n,r),(function(s){let a=oe(s);a.Eu.forEach((c,l)=>{Ih(a.remoteStore,l)}),a.Au.jr(),a.Eu=new Map,a.du=new ft(ee.comparator)})(n),n.fu=!1,yield O0(n.remoteStore,!1)}})}function I3(t,e,n){return y(this,null,function*(){let r=oe(t),i=[],o=[];for(let s of e){let a,c=r.Tu.get(s);if(c&&c.length!==0){a=yield lv(r.localStore,br(c[0]));for(let l of c){let d=r.Pu.get(l),h=yield rce(r,d);h.snapshot&&o.push(h.snapshot)}}else{let l=yield QW(r.localStore,s);a=yield lv(r.localStore,l),yield PM(r,h6(l),s,!1,a.resumeToken)}i.push(a)}return r.hu.J_(o),i})}function h6(t){return lW(t.path,t.collectionGroup,t.orderBy,t.filters,t.limit,"F",t.startAt,t.endAt)}function ace(t){return(function(n){return oe(oe(n).persistence).Ps()})(oe(t).localStore)}function cce(t,e,n,r){return y(this,null,function*(){let i=oe(t);if(i.fu)return void W(bh,"Ignoring unexpected query state notification.");let o=i.Tu.get(e);if(o&&o.length>0)switch(n){case"current":case"not-current":{let s=yield JW(i.localStore,hW(o[0])),a=Yg.createSynthesizedRemoteEventForCurrentChange(e,n==="current",Bt.EMPTY_BYTE_STRING);yield Ma(i,s,a);break}case"rejected":yield yh(i.localStore,e,!0),Sh(i,e,r);break;default:re(64155,n)}})}function lce(t,e,n){return y(this,null,function*(){let r=Vv(t);if(r.fu){for(let i of e){if(r.Tu.has(i)&&r.sharedClientState.isActiveQueryTarget(i)){W(bh,"Adding an already active target "+i);continue}let o=yield QW(r.localStore,i),s=yield lv(r.localStore,o);yield PM(r,h6(o),s.targetId,!1,s.resumeToken),Uv(r.remoteStore,s)}for(let i of n)r.Tu.has(i)&&(yield yh(r.localStore,i,!1).then(()=>{Ih(r.remoteStore,i),Sh(r,i)}).catch(wa))}})}function Vv(t){let e=oe(t);return e.remoteStore.remoteSyncer.applyRemoteEvent=u6.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=nce.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=Qae.bind(null,e),e.hu.J_=$ae.bind(null,e.eventManager),e.hu.pu=Wae.bind(null,e.eventManager),e}function UM(t){let e=oe(t);return e.remoteStore.remoteSyncer.applySuccessfulWrite=Jae.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=Zae.bind(null,e),e}var VM=(()=>{class t{constructor(){this.kind="memory",this.synchronizeTabs=!1}initialize(n){return y(this,null,function*(){this.serializer=kv(n.databaseInfo.databaseId),this.sharedClientState=this.bu(n),this.persistence=this.Du(n),yield this.persistence.start(),this.localStore=this.vu(n),this.gcScheduler=this.Cu(n,this.localStore),this.indexBackfillerScheduler=this.Fu(n,this.localStore)})}Cu(n,r){return null}Fu(n,r){return null}vu(n){return KW(this.persistence,new cv,n.initialUser,this.serializer)}Du(n){return new tm(sv.Vi,this.serializer)}bu(n){return new hv}terminate(){return y(this,null,function*(){var n,r;(n=this.gcScheduler)===null||n===void 0||n.stop(),(r=this.indexBackfillerScheduler)===null||r===void 0||r.stop(),this.sharedClientState.shutdown(),yield this.persistence.shutdown()})}}return t.provider={build:()=>new t},t})(),G0=class extends VM{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,n){se(this.persistence.referenceDelegate instanceof av,46915);let r=this.persistence.referenceDelegate.garbageCollector;return new rv(r,e.asyncQueue,n)}Du(e){let n=this.cacheSizeBytes!==void 0?ar.withCacheSize(this.cacheSizeBytes):ar.DEFAULT;return new tm(r=>av.Vi(r,n),this.serializer)}},yv=class t extends VM{constructor(e,n,r){super(),this.Mu=e,this.cacheSizeBytes=n,this.forceOwnership=r,this.kind="persistent",this.synchronizeTabs=!1}initialize(e){return y(this,null,function*(){yield Ja(t.prototype,this,"initialize").call(this,e),yield this.Mu.initialize(this,e),yield UM(this.Mu.syncEngine),yield Nh(this.Mu.remoteStore),yield this.persistence.ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))})}vu(e){return KW(this.persistence,new cv,e.initialUser,this.serializer)}Cu(e,n){let r=this.persistence.referenceDelegate.garbageCollector;return new rv(r,e.asyncQueue,n)}Fu(e,n){let r=new hO(n,this.persistence);return new dO(e.asyncQueue,r)}Du(e){let n=qW(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),r=this.cacheSizeBytes!==void 0?ar.withCacheSize(this.cacheSizeBytes):ar.DEFAULT;return new p0(this.synchronizeTabs,n,e.clientId,r,e.asyncQueue,r6(),OI(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new hv}},j0=class t extends yv{constructor(e,n){super(e,n,!1),this.Mu=e,this.cacheSizeBytes=n,this.synchronizeTabs=!0}initialize(e){return y(this,null,function*(){yield Ja(t.prototype,this,"initialize").call(this,e);let n=this.Mu.syncEngine;this.sharedClientState instanceof Pg&&(this.sharedClientState.syncEngine={Do:oce.bind(null,n),vo:cce.bind(null,n),Co:lce.bind(null,n),Ps:ace.bind(null,n),bo:ice.bind(null,n)},yield this.sharedClientState.start()),yield this.persistence.ji(r=>y(this,null,function*(){yield sce(this.Mu.syncEngine,r),this.gcScheduler&&(r&&!this.gcScheduler.started?this.gcScheduler.start():r||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(r&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():r||this.indexBackfillerScheduler.stop())}))})}bu(e){let n=r6();if(!Pg.C(n))throw new $(x.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let r=qW(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Pg(n,e.asyncQueue,r,e.clientId,e.initialUser)}},BM=(()=>{class t{initialize(n,r){return y(this,null,function*(){this.localStore||(this.localStore=n.localStore,this.sharedClientState=n.sharedClientState,this.datastore=this.createDatastore(r),this.remoteStore=this.createRemoteStore(r),this.eventManager=this.createEventManager(r),this.syncEngine=this.createSyncEngine(r,!n.synchronizeTabs),this.sharedClientState.onlineStateHandler=i=>y3(this.syncEngine,i,1),this.remoteStore.remoteSyncer.handleCredentialChange=tce.bind(null,this.syncEngine),yield O0(this.remoteStore,this.syncEngine.isPrimaryClient))})}createEventManager(n){return(function(){return new P0})()}createDatastore(n){let r=kv(n.databaseInfo.databaseId),i=(function(s){return new A0(s)})(n.databaseInfo);return(function(s,a,c,l){return new N0(s,a,c,l)})(n.authCredentials,n.appCheckCredentials,i,r)}createRemoteStore(n){return(function(i,o,s,a,c){return new b0(i,o,s,a,c)})(this.localStore,this.datastore,n.asyncQueue,r=>y3(this.syncEngine,r,0),(function(){return fv.C()?new fv:new y0})())}createSyncEngine(n,r){return(function(o,s,a,c,l,d,h){let f=new V0(o,s,a,c,l,d);return h&&(f.fu=!0),f})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,n.initialUser,n.maxConcurrentLimboResolutions,r)}terminate(){return y(this,null,function*(){var n,r;yield(function(o){return y(this,null,function*(){let s=oe(o);W(Gl,"RemoteStore shutting down."),s.Ia.add(5),yield gm(s),s.Ea.shutdown(),s.Aa.set("Unknown")})})(this.remoteStore),(n=this.datastore)===null||n===void 0||n.terminate(),(r=this.eventManager)===null||r===void 0||r.terminate()})}}return t.provider={build:()=>new t},t})();var om=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):wt("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}xu(e,n){setTimeout(()=>{this.muted||e(n)},0)}};var H0=class{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}lookup(e){return y(this,null,function*(){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new $(x.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let n=yield(function(i,o){return y(this,null,function*(){let s=oe(i),a={documents:o.map(h=>Qg(s.serializer,h))},c=yield s.Jo("BatchGetDocuments",s.serializer.databaseId,Ue.emptyPath(),a,o.length),l=new Map;c.forEach(h=>{let f=gae(s.serializer,h);l.set(f.key.toString(),f)});let d=[];return o.forEach(h=>{let f=l.get(h.toString());se(!!f,55234,{key:h}),d.push(f)}),d})})(this.datastore,e);return n.forEach(r=>this.recordVersion(r)),n})}set(e,n){this.write(n.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,n){try{this.write(n.toMutation(e,this.preconditionForUpdate(e)))}catch(r){this.lastTransactionError=r}this.writtenDocs.add(e.toString())}delete(e){this.write(new Ul(e,this.precondition(e))),this.writtenDocs.add(e.toString())}commit(){return y(this,null,function*(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(n=>{e.delete(n.key.toString())}),e.forEach((n,r)=>{let i=ee.fromPath(r);this.mutations.push(new zg(i,this.precondition(i)))}),yield(function(r,i){return y(this,null,function*(){let o=oe(r),s={writes:i.map(a=>Jg(o.serializer,a))};yield o.Wo("Commit",o.serializer.databaseId,Ue.emptyPath(),s)})})(this.datastore,this.mutations),this.committed=!0})}recordVersion(e){let n;if(e.isFoundDocument())n=e.version;else{if(!e.isNoDocument())throw re(50498,{Wu:e.constructor.name});n=ce.min()}let r=this.readVersions.get(e.key.toString());if(r){if(!n.isEqual(r))throw new $(x.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),n)}precondition(e){let n=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&n?n.isEqual(ce.min())?Sn.exists(!1):Sn.updateTime(n):Sn.none()}preconditionForUpdate(e){let n=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&n){if(n.isEqual(ce.min()))throw new $(x.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Sn.updateTime(n)}return Sn.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}};var $0=class{constructor(e,n,r,i,o){this.asyncQueue=e,this.datastore=n,this.options=r,this.updateFunction=i,this.deferred=o,this.Gu=r.maxAttempts,this.F_=new rm(this.asyncQueue,"transaction_retry")}zu(){this.Gu-=1,this.ju()}ju(){this.F_.g_(()=>y(this,null,function*(){let e=new H0(this.datastore),n=this.Ju(e);n&&n.then(r=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(r)}).catch(i=>{this.Hu(i)}))}).catch(r=>{this.Hu(r)})}))}Ju(e){try{let n=this.updateFunction(e);return!um(n)&&n.catch&&n.then?n:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(n){return this.deferred.reject(n),null}}Hu(e){this.Gu>0&&this.Yu(e)?(this.Gu-=1,this.asyncQueue.enqueueAndForget(()=>(this.ju(),Promise.resolve()))):this.deferred.reject(e)}Yu(e){if(e.name==="FirebaseError"){let n=e.code;return n==="aborted"||n==="failed-precondition"||n==="already-exists"||!AW(n)}return!1}};var Na="FirestoreClient",W0=class{constructor(e,n,r,i,o){this.authCredentials=e,this.appCheckCredentials=n,this.asyncQueue=r,this.databaseInfo=i,this.user=Ut.UNAUTHENTICATED,this.clientId=xg.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=o,this.authCredentials.start(r,s=>y(this,null,function*(){W(Na,"Received user=",s.uid),yield this.authCredentialListener(s),this.user=s})),this.appCheckCredentials.start(r,s=>(W(Na,"Received new app check token=",s),this.appCheckCredentialListener(s,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new cr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(()=>y(this,null,function*(){try{this._onlineComponents&&(yield this._onlineComponents.terminate()),this._offlineComponents&&(yield this._offlineComponents.terminate()),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(n){let r=bM(n,"Failed to shutdown persistence");e.reject(r)}})),e.promise}};function eO(t,e){return y(this,null,function*(){t.asyncQueue.verifyOperationInProgress(),W(Na,"Initializing OfflineComponentProvider");let n=t.configuration;yield e.initialize(n);let r=n.initialUser;t.setCredentialChangeListener(i=>y(null,null,function*(){r.isEqual(i)||(yield YW(e.localStore,i),r=i)})),e.persistence.setDatabaseDeletedListener(()=>{ls("Terminating Firestore due to IndexedDb database deletion"),t.terminate().then(()=>{W("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(i=>{ls("Terminating Firestore due to IndexedDb database deletion failed",i)})}),t._offlineComponents=e})}function v3(t,e){return y(this,null,function*(){t.asyncQueue.verifyOperationInProgress();let n=yield uce(t);W(Na,"Initializing OnlineComponentProvider"),yield e.initialize(n,t.configuration),t.setCredentialChangeListener(r=>E3(e.remoteStore,r)),t.setAppCheckTokenChangeListener((r,i)=>E3(e.remoteStore,i)),t._onlineComponents=e})}function uce(t){return y(this,null,function*(){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){W(Na,"Using user provided OfflineComponentProvider");try{yield eO(t,t._uninitializedComponentsProvider._offline)}catch(e){let n=e;if(!(function(i){return i.name==="FirebaseError"?i.code===x.FAILED_PRECONDITION||i.code===x.UNIMPLEMENTED:!(typeof DOMException<"u"&&i instanceof DOMException)||i.code===22||i.code===20||i.code===11})(n))throw n;ls("Error using user provided cache. Falling back to memory cache: "+n),yield eO(t,new VM)}}else W(Na,"Using default OfflineComponentProvider"),yield eO(t,new G0(void 0));return t._offlineComponents})}function GM(t){return y(this,null,function*(){return t._onlineComponents||(t._uninitializedComponentsProvider?(W(Na,"Using user provided OnlineComponentProvider"),yield v3(t,t._uninitializedComponentsProvider._online)):(W(Na,"Using default OnlineComponentProvider"),yield v3(t,new BM))),t._onlineComponents})}function dce(t){return GM(t).then(e=>e.syncEngine)}function f6(t){return GM(t).then(e=>e.datastore)}function Iv(t){return y(this,null,function*(){let e=yield GM(t),n=e.eventManager;return n.onListen=zae.bind(null,e.syncEngine),n.onUnlisten=Kae.bind(null,e.syncEngine),n.onFirstRemoteStoreListen=qae.bind(null,e.syncEngine),n.onLastRemoteStoreUnlisten=Yae.bind(null,e.syncEngine),n})}function hce(t,e,n={}){let r=new cr;return t.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return(function(o,s,a,c,l){let d=new om({next:f=>{d.Ou(),s.enqueueAndForget(()=>MM(o,h));let g=f.docs.has(a);!g&&f.fromCache?l.reject(new $(x.UNAVAILABLE,"Failed to get document because the client is offline.")):g&&f.fromCache&&c&&c.source==="server"?l.reject(new $(x.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):l.resolve(f)},error:f=>l.reject(f)}),h=new im(fm(a.path),d,{includeMetadataChanges:!0,ka:!0});return OM(o,h)})(yield Iv(t),t.asyncQueue,e,n,r)})),r.promise}function fce(t,e,n={}){let r=new cr;return t.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return(function(o,s,a,c,l){let d=new om({next:f=>{d.Ou(),s.enqueueAndForget(()=>MM(o,h)),f.fromCache&&c.source==="server"?l.reject(new $(x.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):l.resolve(f)},error:f=>l.reject(f)}),h=new im(a,d,{includeMetadataChanges:!0,ka:!0});return OM(o,h)})(yield Iv(t),t.asyncQueue,e,n,r)})),r.promise}function pce(t,e,n){let r=new cr;return t.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){try{let i=yield f6(t);r.resolve((function(s,a,c){return y(this,null,function*(){var l;let d=oe(s),{request:h,ft:f,parent:g}=_ae(d.serializer,Qse(a),c);d.connection.Qo||delete h.parent;let E=(yield d.Jo("RunAggregationQuery",d.serializer.databaseId,g,h,1)).filter(S=>!!S.result);se(E.length===1,64727);let I=(l=E[0].result)===null||l===void 0?void 0:l.aggregateFields;return Object.keys(I).reduce((S,L)=>(S[f[L]]=I[L],S),{})})})(i,e,n))}catch(i){r.reject(i)}})),r.promise}function p6(t){let e={};return t.timeoutSeconds!==void 0&&(e.timeoutSeconds=t.timeoutSeconds),e}var S3=new Map;var g6="firestore.googleapis.com",A3=!0,vv=class{constructor(e){var n,r;if(e.host===void 0){if(e.ssl!==void 0)throw new $(x.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=g6,this.ssl=A3}else this.host=e.host,this.ssl=(n=e.ssl)!==null&&n!==void 0?n:A3;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=BW;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<$W)throw new $(x.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}_se("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=p6((r=e.experimentalLongPollingOptions)!==null&&r!==void 0?r:{}),(function(o){if(o.timeoutSeconds!==void 0){if(isNaN(o.timeoutSeconds))throw new $(x.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (must not be NaN)`);if(o.timeoutSeconds<5)throw new $(x.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (minimum allowed value is 5)`);if(o.timeoutSeconds>30)throw new $(x.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(function(r,i){return r.timeoutSeconds===i.timeoutSeconds})(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},jl=class{constructor(e,n,r,i){this._authCredentials=e,this._appCheckCredentials=n,this._databaseId=r,this._app=i,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new vv({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new $(x.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new $(x.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new vv(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(r){if(!r)return new tO;switch(r.type){case"firstParty":return new oO(r.sessionIndex||"0",r.iamToken||null,r.authTokenFactory||null);case"provider":return r.client;default:throw new $(x.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}_restart(){return y(this,null,function*(){this._terminateTask==="notTerminated"?yield this._terminate():this._terminateTask="notTerminated"})}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(n){let r=S3.get(n);r&&(W("ComponentProvider","Removing Datastore"),S3.delete(n),r.terminate())})(this),Promise.resolve()}};function m6(t,e,n,r={}){var i;t=lr(t,jl);let o=vr(e),s=t._getSettings(),a=Object.assign(Object.assign({},s),{emulatorOptions:t._getEmulatorOptions()}),c=`${e}:${n}`;o&&(Hs(`https://${c}`),qc("Firestore",!0)),s.host!==g6&&s.host!==c&&ls("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let l=Object.assign(Object.assign({},s),{host:c,ssl:o,emulatorOptions:r});if(!mi(l,a)&&(t._setSettings(l),r.mockUserToken)){let d,h;if(typeof r.mockUserToken=="string")d=r.mockUserToken,h=Ut.MOCK_USER;else{d=zT(r.mockUserToken,(i=t._app)===null||i===void 0?void 0:i.options.projectId);let f=r.mockUserToken.sub||r.mockUserToken.user_id;if(!f)throw new $(x.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");h=new Ut(f)}t._authCredentials=new nO(new MI(d,h))}}var Ri=class t{constructor(e,n,r){this.converter=n,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new t(this.firestore,e,this._query)}},Zt=class t{constructor(e,n,r){this.converter=n,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Ea(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new t(this.firestore,e,this._key)}toJSON(){return{type:t._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,n,r){if(lm(n,t._jsonSchema))return new t(e,r||null,new ee(Ue.fromString(n.referencePath)))}};Zt._jsonSchemaVersion="firestore/documentReference/1.0",Zt._jsonSchema={type:Vt("string",Zt._jsonSchemaVersion),referencePath:Vt("string")};var Ea=class t extends Ri{constructor(e,n,r){super(e,n,fm(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new Zt(this.firestore,null,new ee(e))}withConverter(e){return new t(this.firestore,e,this._path)}};function E6(t,e,...n){if(t=Pe(t),uM("collection","path",e),t instanceof jl){let r=Ue.fromString(e,...n);return T$(r),new Ea(t,null,r)}{if(!(t instanceof Zt||t instanceof Ea))throw new $(x.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=t._path.child(Ue.fromString(e,...n));return T$(r),new Ea(t.firestore,null,r)}}function _6(t,e){if(t=lr(t,jl),uM("collectionGroup","collection id",e),e.indexOf("/")>=0)throw new $(x.INVALID_ARGUMENT,`Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ri(t,null,(function(r){return new vo(Ue.emptyPath(),r)})(e))}function T6(t,e,...n){if(t=Pe(t),arguments.length===1&&(e=xg.newId()),uM("doc","path",e),t instanceof jl){let r=Ue.fromString(e,...n);return _$(r),new Zt(t,null,new ee(r))}{if(!(t instanceof Zt||t instanceof Ea))throw new $(x.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=t._path.child(Ue.fromString(e,...n));return _$(r),new Zt(t.firestore,t instanceof Ea?t.converter:null,new ee(r))}}var C3="AsyncQueue",Sv=class{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new rm(this,"async_queue_retry"),this.oc=()=>{let r=OI();r&&W(C3,"Visibility state changed to "+r.visibilityState),this.F_.y_()},this._c=e;let n=OI();n&&typeof n.addEventListener=="function"&&n.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let n=OI();n&&typeof n.removeEventListener=="function"&&n.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let n=new cr;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(e().then(n.resolve,n.reject),n.promise)).then(()=>n.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Zu.push(e),this.cc()))}cc(){return y(this,null,function*(){if(this.Zu.length!==0){try{yield this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!ba(e))throw e;W(C3,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}})}uc(e){let n=this._c.then(()=>(this.nc=!0,e().catch(r=>{throw this.tc=r,this.nc=!1,wt("INTERNAL UNHANDLED ERROR: ",D3(r)),r}).then(r=>(this.nc=!1,r))));return this._c=n,n}enqueueAfterDelay(e,n,r){this.ac(),this.sc.indexOf(e)>-1&&(n=0);let i=M0.createAndSchedule(this,e,n,r,o=>this.lc(o));return this.ec.push(i),i}ac(){this.tc&&re(47125,{hc:D3(this.tc)})}verifyOperationInProgress(){}Pc(){return y(this,null,function*(){let e;do e=this._c,yield e;while(e!==this._c)})}Tc(e){for(let n of this.ec)if(n.timerId===e)return!0;return!1}Ic(e){return this.Pc().then(()=>{this.ec.sort((n,r)=>n.targetTimeMs-r.targetTimeMs);for(let n of this.ec)if(n.skipDelay(),e!=="all"&&n.timerId===e)break;return this.Pc()})}dc(e){this.sc.push(e)}lc(e){let n=this.ec.indexOf(e);this.ec.splice(n,1)}};function D3(t){let e=t.message||"";return t.stack&&(e=t.stack.includes(t.message)?t.stack:t.message+`
|
|
174
|
-
`+t.stack),e}function R3(t){return(function(n,r){if(typeof n!="object"||n===null)return!1;let i=n;for(let o of r)if(o in i&&typeof i[o]=="function")return!0;return!1})(t,["next","error","complete"])}var Ni=class extends jl{constructor(e,n,r,i){super(e,n,r,i),this.type="firestore",this._queue=new Sv,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return y(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Sv(e),this._firestoreClient=void 0,yield e}})}};function Bv(t,e,n){n||(n=Hg);let r=uo(t,"firestore");if(r.isInitialized(n)){let i=r.getImmediate({identifier:n}),o=r.getOptions(n);if(mi(o,e))return i;throw new $(x.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new $(x.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<$W)throw new $(x.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&vr(e.host)&&Hs(e.host),r.initialize({options:e,instanceIdentifier:n})}function Oh(t,e){let n=typeof t=="object"?t:ir(),r=typeof t=="string"?t:e||Hg,i=uo(n,"firestore").getImmediate({identifier:r});if(!i._initialized){let o=pd("firestore");o&&m6(i,...o)}return i}function Mh(t){if(t._terminated)throw new $(x.FAILED_PRECONDITION,"The client has already been terminated.");return t._firestoreClient||gce(t),t._firestoreClient}function gce(t){var e,n,r;let i=t._freezeSettings(),o=(function(a,c,l,d){return new mO(a,c,l,d.host,d.ssl,d.experimentalForceLongPolling,d.experimentalAutoDetectLongPolling,p6(d.experimentalLongPollingOptions),d.useFetchStreams,d.isUsingEmulator)})(t._databaseId,((e=t._app)===null||e===void 0?void 0:e.options.appId)||"",t._persistenceKey,i);t._componentsProvider||!((n=i.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((r=i.localCache)===null||r===void 0)&&r._onlineComponentProvider)&&(t._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),t._firestoreClient=new W0(t._authCredentials,t._appCheckCredentials,t._queue,o,t._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(t._componentsProvider))}var z0=class{constructor(e="count",n){this._internalFieldPath=n,this.type="AggregateField",this.aggregateType=e}},q0=class{constructor(e,n,r){this._userDataWriter=n,this._data=r,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var cs=class t{constructor(e){this._byteString=e}static fromBase64String(e){try{return new t(Bt.fromBase64String(e))}catch(n){throw new $(x.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(e){return new t(Bt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:t._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(lm(e,t._jsonSchema))return t.fromBase64String(e.bytes)}};cs._jsonSchemaVersion="firestore/bytes/1.0",cs._jsonSchema={type:Vt("string",cs._jsonSchemaVersion),bytes:Vt("string")};var Ah=class{constructor(...e){for(let n=0;n<e.length;++n)if(e[n].length===0)throw new $(x.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Qt(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var sm=class{constructor(e){this._methodName=e}};var _a=class t{constructor(e,n){if(!isFinite(e)||e<-90||e>90)throw new $(x.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(n)||n<-180||n>180)throw new $(x.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=e,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return Ie(this._lat,e._lat)||Ie(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:t._jsonSchemaVersion}}static fromJSON(e){if(lm(e,t._jsonSchema))return new t(e.latitude,e.longitude)}};_a._jsonSchemaVersion="firestore/geoPoint/1.0",_a._jsonSchema={type:Vt("string",_a._jsonSchemaVersion),latitude:Vt("number"),longitude:Vt("number")};var Ta=class t{constructor(e){this._values=(e||[]).map(n=>n)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(r,i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;++o)if(r[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:t._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(lm(e,t._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(n=>typeof n=="number"))return new t(e.vectorValues);throw new $(x.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ta._jsonSchemaVersion="firestore/vectorValue/1.0",Ta._jsonSchema={type:Vt("string",Ta._jsonSchemaVersion),vectorValues:Vt("object")};var mce=/^__.*__$/,K0=class{constructor(e,n,r){this.data=e,this.fieldMask=n,this.fieldTransforms=r}toMutation(e,n){return this.fieldMask!==null?new Di(e,this.data,this.fieldMask,n,this.fieldTransforms):new Da(e,this.data,n,this.fieldTransforms)}},Av=class{constructor(e,n,r){this.data=e,this.fieldMask=n,this.fieldTransforms=r}toMutation(e,n){return new Di(e,this.data,this.fieldMask,n,this.fieldTransforms)}};function y6(t){switch(t){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw re(40011,{Ec:t})}}var Y0=class t{constructor(e,n,r,i,o,s){this.settings=e,this.databaseId=n,this.serializer=r,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new t(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var n;let r=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:r,mc:!1});return i.fc(e),i}gc(e){var n;let r=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:r,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return Dv(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(n=>e.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>e.isPrefixOf(n.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(y6(this.Ec)&&mce.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},X0=class{constructor(e,n,r){this.databaseId=e,this.ignoreUndefinedProperties=n,this.serializer=r||kv(e)}Dc(e,n,r,i=!1){return new Y0({Ec:e,methodName:n,bc:r,path:Qt.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function Gv(t){let e=t._freezeSettings(),n=kv(t._databaseId);return new X0(t._databaseId,!!e.ignoreUndefinedProperties,n)}function I6(t,e,n,r,i,o={}){let s=t.Dc(o.merge||o.mergeFields?2:0,e,n,i);jM("Data must be an object, but it was:",s,r);let a=S6(r,s),c,l;if(o.merge)c=new Nr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let d=[];for(let h of o.mergeFields){let f=Q0(e,h,n);if(!s.contains(f))throw new $(x.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);C6(d,f)||d.push(f)}c=new Nr(d),l=s.fieldTransforms.filter(h=>c.covers(h.field))}else c=null,l=s.fieldTransforms;return new K0(new Vn(a),c,l)}var Cv=class t extends sm{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof t}};function Ece(t,e,n,r){let i=t.Dc(1,e,n);jM("Data must be an object, but it was:",i,r);let o=[],s=Vn.empty();Oa(r,(c,l)=>{let d=HM(e,c,n);l=Pe(l);let h=i.gc(d);if(l instanceof Cv)o.push(d);else{let f=mm(l,h);f!=null&&(o.push(d),s.set(d,f))}});let a=new Nr(o);return new Av(s,a,i.fieldTransforms)}function _ce(t,e,n,r,i,o){let s=t.Dc(1,e,n),a=[Q0(e,r,n)],c=[i];if(o.length%2!=0)throw new $(x.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(Q0(e,o[f])),c.push(o[f+1]);let l=[],d=Vn.empty();for(let f=a.length-1;f>=0;--f)if(!C6(l,a[f])){let g=a[f],E=c[f];E=Pe(E);let I=s.gc(g);if(E instanceof Cv)l.push(g);else{let S=mm(E,I);S!=null&&(l.push(g),d.set(g,S))}}let h=new Nr(l);return new Av(d,h,s.fieldTransforms)}function v6(t,e,n,r=!1){return mm(n,t.Dc(r?4:3,e))}function mm(t,e){if(A6(t=Pe(t)))return jM("Unsupported field value:",e,t),S6(t,e);if(t instanceof sm)return(function(r,i){if(!y6(i.Ec))throw i.wc(`${r._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${r._methodName}() is not currently supported inside arrays`);let o=r._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(t,e),null;if(t===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(r,i){let o=[],s=0;for(let a of r){let c=mm(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(t,e)}return(function(r,i){if((r=Pe(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return rae(i.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){let o=yt.fromDate(r);return{timestampValue:Eh(i.serializer,o)}}if(r instanceof yt){let o=new yt(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:Eh(i.serializer,o)}}if(r instanceof _a)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof cs)return{bytesValue:DW(i.serializer,r._byteString)};if(r instanceof Zt){let o=i.databaseId,s=r.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:SM(r.firestore._databaseId||i.databaseId,r._key.path)}}if(r instanceof Ta)return(function(s,a){return{mapValue:{fields:{[EM]:{stringValue:_M},[hh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return vM(a.serializer,l)})}}}}}})(r,i);throw i.wc(`Unsupported field value: ${Nv(r)}`)})(t,e)}function S6(t,e){let n={};return Y3(t)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Oa(t,(r,i)=>{let o=mm(i,e.Vc(r));o!=null&&(n[r]=o)}),{mapValue:{fields:n}}}function A6(t){return!(typeof t!="object"||t===null||t instanceof Array||t instanceof Date||t instanceof yt||t instanceof _a||t instanceof cs||t instanceof Zt||t instanceof sm||t instanceof Ta)}function jM(t,e,n){if(!A6(n)||!L3(n)){let r=Nv(n);throw r==="an object"?e.wc(t+" a custom object"):e.wc(t+" "+r)}}function Q0(t,e,n){if((e=Pe(e))instanceof Ah)return e._internalPath;if(typeof e=="string")return HM(t,e);throw Dv("Field path arguments must be of type string or ",t,!1,void 0,n)}var Tce=new RegExp("[~\\*/\\[\\]]");function HM(t,e,n){if(e.search(Tce)>=0)throw Dv(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new Ah(...e.split("."))._internalPath}catch{throw Dv(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function Dv(t,e,n,r,i){let o=r&&!r.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${r}`),s&&(c+=` in document ${i}`),c+=")"),new $(x.INVALID_ARGUMENT,a+t+c)}function C6(t,e){return t.some(n=>n.isEqual(e))}var Hl=class{constructor(e,n,r,i,o){this._firestore=e,this._userDataWriter=n,this._key=r,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new Zt(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new J0(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let n=this._document.data.field(jv("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n)}}},J0=class extends Hl{data(){return super.data()}};function jv(t,e){return typeof e=="string"?HM(t,e):e instanceof Ah?e._internalPath:e._delegate._internalPath}function D6(t){if(t.limitType==="L"&&t.explicitOrderBy.length===0)throw new $(x.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var am=class{},Ch=class extends am{};function R6(t,e,...n){let r=[];e instanceof am&&r.push(e),r=r.concat(n),(function(o){let s=o.filter(c=>c instanceof Dh).length,a=o.filter(c=>c instanceof cm).length;if(s>1||s>0&&a>0)throw new $(x.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(r);for(let i of r)t=i._apply(t);return t}var cm=class t extends Ch{constructor(e,n,r){super(),this._field=e,this._op=n,this._value=r,this.type="where"}static _create(e,n,r){return new t(e,n,r)}_apply(e){let n=this._parse(e);return P6(e._query,n),new Ri(e.firestore,e.converter,wO(e._query,n))}_parse(e){let n=Gv(e.firestore);return(function(o,s,a,c,l,d,h){let f;if(l.isKeyField()){if(d==="array-contains"||d==="array-contains-any")throw new $(x.INVALID_ARGUMENT,`Invalid Query. You can't perform '${d}' queries on documentId().`);if(d==="in"||d==="not-in"){w3(h,d);let E=[];for(let I of h)E.push(N3(c,o,I));f={arrayValue:{values:E}}}else f=N3(c,o,h)}else d!=="in"&&d!=="not-in"&&d!=="array-contains-any"||w3(h,d),f=v6(a,s,h,d==="in"||d==="not-in");return xe.create(l,d,f)})(e._query,"where",n,e.firestore._databaseId,this._field,this._op,this._value)}};function N6(t,e,n){let r=e,i=jv("where",t);return cm._create(i,r,n)}var Dh=class t extends am{constructor(e,n){super(),this.type=e,this._queryConstraints=n}static _create(e,n){return new t(e,n)}_parse(e){let n=this._queryConstraints.map(r=>r._parse(e)).filter(r=>r.getFilters().length>0);return n.length===1?n[0]:Je.create(n,this._getOperator())}_apply(e){let n=this._parse(e);return n.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)P6(s,c),s=wO(s,c)})(e._query,n),new Ri(e.firestore,e.converter,wO(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function w6(...t){return t.forEach(e=>x6("or",e)),Dh._create("or",t)}function b6(...t){return t.forEach(e=>x6("and",e)),Dh._create("and",t)}var Z0=class t extends Ch{constructor(e,n){super(),this._field=e,this._direction=n,this.type="orderBy"}static _create(e,n){return new t(e,n)}_apply(e){let n=(function(i,o,s){if(i.startAt!==null)throw new $(x.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new $(x.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Pl(o,s)})(e._query,this._field,this._direction);return new Ri(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new vo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,n))}};function O6(t,e="asc"){let n=e,r=jv("orderBy",t);return Z0._create(r,n)}var eM=class t extends Ch{constructor(e,n,r){super(),this.type=e,this._limit=n,this._limitType=r}static _create(e,n,r){return new t(e,n,r)}_apply(e){return new Ri(e.firestore,e.converter,zI(e._query,this._limit,this._limitType))}};function M6(t){return Tse("limit",t),eM._create("limit",t,"F")}var tM=class t extends Ch{constructor(e,n,r){super(),this.type=e,this._docOrFields=n,this._inclusive=r}static _create(e,n,r){return new t(e,n,r)}_apply(e){let n=yce(e,this.type,this._docOrFields,this._inclusive);return new Ri(e.firestore,e.converter,(function(i,o){return new vo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,n))}};function L6(...t){return tM._create("startAfter",t,!1)}function yce(t,e,n,r){if(n[0]=Pe(n[0]),n[0]instanceof Hl)return(function(o,s,a,c,l){if(!c)throw new $(x.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let d=[];for(let h of eh(o))if(h.field.isKeyField())d.push(Ll(s,c.key));else{let f=c.data.field(h.field);if(Mv(f))throw new $(x.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+h.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=h.field.canonicalString();throw new $(x.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}d.push(f)}return new Io(d,l)})(t._query,t.firestore._databaseId,e,n[0]._document,r);{let i=Gv(t.firestore);return(function(s,a,c,l,d,h){let f=s.explicitOrderBy;if(d.length>f.length)throw new $(x.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let E=0;E<d.length;E++){let I=d[E];if(f[E].field.isKeyField()){if(typeof I!="string")throw new $(x.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof I}`);if(!yM(s)&&I.indexOf("/")!==-1)throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${I}' contains a slash.`);let S=s.path.child(Ue.fromString(I));if(!ee.isDocumentKey(S))throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${S}' is not because it contains an odd number of segments.`);let L=new ee(S);g.push(Ll(a,L))}else{let S=v6(c,l,I);g.push(S)}}return new Io(g,h)})(t._query,t.firestore._databaseId,i,e,n,r)}}function N3(t,e,n){if(typeof(n=Pe(n))=="string"){if(n==="")throw new $(x.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!yM(e)&&n.indexOf("/")!==-1)throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let r=e.path.child(Ue.fromString(n));if(!ee.isDocumentKey(r))throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Ll(t,new ee(r))}if(n instanceof Zt)return Ll(t,n._key);throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Nv(n)}.`)}function w3(t,e){if(!Array.isArray(t)||t.length===0)throw new $(x.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function P6(t,e){let n=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(t.filters,(function(i){switch(i){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(e.op));if(n!==null)throw n===e.op?new $(x.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new $(x.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`)}function x6(t,e){if(!(e instanceof cm||e instanceof Dh))throw new $(x.INVALID_ARGUMENT,`Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Rv=class{convertValue(e,n="none"){switch(va(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Tt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,n);case 5:return e.stringValue;case 6:return this.convertBytes(ds(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,n);case 11:return this.convertObject(e.mapValue,n);case 10:return this.convertVectorValue(e.mapValue);default:throw re(62114,{value:e})}}convertObject(e,n){return this.convertObjectMap(e.fields,n)}convertObjectMap(e,n="none"){let r={};return Oa(e,(i,o)=>{r[i]=this.convertValue(o,n)}),r}convertVectorValue(e){var n,r,i;let o=(i=(r=(n=e.fields)===null||n===void 0?void 0:n[hh].arrayValue)===null||r===void 0?void 0:r.values)===null||i===void 0?void 0:i.map(s=>Tt(s.doubleValue));return new Ta(o)}convertGeoPoint(e){return new _a(Tt(e.latitude),Tt(e.longitude))}convertArray(e,n){return(e.values||[]).map(r=>this.convertValue(r,n))}convertServerTimestamp(e,n){switch(n){case"previous":let r=Lv(e);return r==null?null:this.convertValue(r,n);case"estimate":return this.convertTimestamp(jg(e));default:return null}}convertTimestamp(e){let n=us(e);return new yt(n.seconds,n.nanos)}convertDocumentKey(e,n){let r=Ue.fromString(e);se(xW(r),9688,{name:e});let i=new dh(r.get(1),r.get(3)),o=new ee(r.popFirst(5));return i.isEqual(n)||wt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),o}};function k6(t,e,n){let r;return r=t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e,r}var nM=class extends Rv{constructor(e){super(),this.firestore=e}convertBytes(e){return new cs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new Zt(this.firestore,null,n)}};function Ice(){return new z0("count")}var ma=class{constructor(e,n){this.hasPendingWrites=e,this.fromCache=n}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},ya=class t extends Hl{constructor(e,n,r,i,o,s){super(e,n,r,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let n=new nh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,n={}){if(this._document){let r=this._document.data.field(jv("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r,n.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new $(x.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,n={};return n.type=t._jsonSchemaVersion,n.bundle="",n.bundleSource="DocumentSnapshot",n.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?n:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),n.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),n)}};ya._jsonSchemaVersion="firestore/documentSnapshot/1.0",ya._jsonSchema={type:Vt("string",ya._jsonSchemaVersion),bundleSource:Vt("string","DocumentSnapshot"),bundleName:Vt("string"),bundle:Vt("string")};var nh=class extends ya{data(e={}){return super.data(e)}},Ml=class t{constructor(e,n,r,i){this._firestore=e,this._userDataWriter=n,this._snapshot=i,this.metadata=new ma(i.hasPendingWrites,i.fromCache),this.query=r}get docs(){let e=[];return this.forEach(n=>e.push(n)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,n){this._snapshot.docs.forEach(r=>{e.call(n,new nh(this._firestore,this._userDataWriter,r.key,r,new ma(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let n=!!e.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new $(x.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===n||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new nh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ma(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new nh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ma(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,d=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),d=s.indexOf(a.doc.key)),{type:vce(a.type),doc:c,oldIndex:l,newIndex:d}})}})(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new $(x.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=t._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=xg.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let n=[],r=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(n.push(o._document),r.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function vce(t){switch(t){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return re(61501,{type:t})}}function F6(t){t=lr(t,Zt);let e=lr(t.firestore,Ni);return hce(Mh(e),t._key).then(n=>H6(e,t,n))}Ml._jsonSchemaVersion="firestore/querySnapshot/1.0",Ml._jsonSchema={type:Vt("string",Ml._jsonSchemaVersion),bundleSource:Vt("string","QuerySnapshot"),bundleName:Vt("string"),bundle:Vt("string")};var $l=class extends Rv{constructor(e){super(),this.firestore=e}convertBytes(e){return new cs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new Zt(this.firestore,null,n)}};function U6(t){t=lr(t,Ri);let e=lr(t.firestore,Ni),n=Mh(e),r=new $l(e);return D6(t._query),fce(n,t._query).then(i=>new Ml(e,r,t,i))}function V6(t,e,n){t=lr(t,Zt);let r=lr(t.firestore,Ni),i=k6(t.converter,e,n);return j6(r,[I6(Gv(r),"setDoc",t._key,i,t.converter!==null,n).toMutation(t._key,Sn.none())])}function B6(t){return j6(lr(t.firestore,Ni),[new Ul(t._key,Sn.none())])}function G6(t,...e){var n,r,i;t=Pe(t);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||R3(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(R3(e[s])){let h=e[s];e[s]=(n=h.next)===null||n===void 0?void 0:n.bind(h),e[s+1]=(r=h.error)===null||r===void 0?void 0:r.bind(h),e[s+2]=(i=h.complete)===null||i===void 0?void 0:i.bind(h)}let c,l,d;if(t instanceof Zt)l=lr(t.firestore,Ni),d=fm(t._key.path),c={next:h=>{e[s]&&e[s](H6(l,t,h))},error:e[s+1],complete:e[s+2]};else{let h=lr(t,Ri);l=lr(h.firestore,Ni),d=h._query;let f=new $l(l);c={next:g=>{e[s]&&e[s](new Ml(l,f,h,g))},error:e[s+1],complete:e[s+2]},D6(t._query)}return(function(f,g,E,I){let S=new om(I),L=new im(g,S,E);return f.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return OM(yield Iv(f),L)})),()=>{S.Ou(),f.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return MM(yield Iv(f),L)}))}})(Mh(l),d,a,c)}function j6(t,e){return(function(r,i){let o=new cr;return r.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return Xae(yield dce(r),i,o)})),o.promise})(Mh(t),e)}function H6(t,e,n){let r=n.docs.get(e._key),i=new $l(t);return new ya(t,i,e._key,r,new ma(n.hasPendingWrites,n.fromCache),e.converter)}function $6(t){return W6(t,{count:Ice()})}function W6(t,e){let n=lr(t.firestore,Ni),r=Mh(n),i=zse(e,(o,s)=>new LO(s,o.aggregateType,o._internalFieldPath));return pce(r,t._query,i).then(o=>(function(a,c,l){let d=new $l(a);return new q0(c,d,l)})(n,t,o))}var rM=class{constructor(e){let n;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),n=e.tabManager):(n=Sce(void 0),n._initialize(e)),this._onlineComponentProvider=n._onlineComponentProvider,this._offlineComponentProvider=n._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function $M(t){return new rM(t)}var iM=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=BM.provider,this._offlineComponentProvider={build:n=>new yv(n,e?.cacheSizeBytes,this.forceOwnership)}}},oM=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=BM.provider,this._offlineComponentProvider={build:n=>new j0(n,e?.cacheSizeBytes)}}};function Sce(t){return new iM(t?.forceOwnership)}function WM(){return new oM}var Ace={maxAttempts:5};function Dg(t,e){if((t=Pe(t)).firestore!==e)throw new $(x.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return t}var sM=class{constructor(e,n){this._firestore=e,this._transaction=n,this._dataReader=Gv(e)}get(e){let n=Dg(e,this._firestore),r=new nM(this._firestore);return this._transaction.lookup([n._key]).then(i=>{if(!i||i.length!==1)return re(24041);let o=i[0];if(o.isFoundDocument())return new Hl(this._firestore,r,o.key,o,n.converter);if(o.isNoDocument())return new Hl(this._firestore,r,n._key,null,n.converter);throw re(18433,{doc:o})})}set(e,n,r){let i=Dg(e,this._firestore),o=k6(i.converter,n,r),s=I6(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,r);return this._transaction.set(i._key,s),this}update(e,n,r,...i){let o=Dg(e,this._firestore),s;return s=typeof(n=Pe(n))=="string"||n instanceof Ah?_ce(this._dataReader,"Transaction.update",o._key,n,r,i):Ece(this._dataReader,"Transaction.update",o._key,n),this._transaction.update(o._key,s),this}delete(e){let n=Dg(e,this._firestore);return this._transaction.delete(n._key),this}};var aM=class extends sM{constructor(e,n){super(e,n),this._firestore=e}get(e){let n=Dg(e,this._firestore),r=new $l(this._firestore);return super.get(e).then(i=>new ya(this._firestore,r,n._key,i._document,new ma(!1,!1),n.converter))}};function z6(t,e,n){t=lr(t,Ni);let r=Object.assign(Object.assign({},Ace),n);return(function(o){if(o.maxAttempts<1)throw new $(x.INVALID_ARGUMENT,"Max attempts must be at least 1")})(r),(function(o,s,a){let c=new cr;return o.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){let l=yield f6(o);new $0(o.asyncQueue,l,a,s,c).zu()})),c.promise})(Mh(t),i=>e(new aM(t,i)),r)}(function(e,n=!0){(function(i){Rh=i})(qs),zn(new Xt("firestore",(r,{instanceIdentifier:i,options:o})=>{let s=r.getProvider("app").getImmediate(),a=new Ni(new rO(r.getProvider("auth-internal")),new sO(s,r.getProvider("app-check-internal")),(function(l,d){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new $(x.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new dh(l.options.projectId,d)})(s,i),s);return o=Object.assign({useFetchStreams:n},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),$e(p$,g$,e),$e(p$,g$,"esm2017")})();var tVe=de(b6,!0,2);var Hv=de(E6,!0,2),q6=de(_6,!0,2);var K6=de(B6,!0,2);var Em=de(T6,!0,2);var Y6=de($6,!0),zM=de(F6,!0);var X6=de(U6,!0);var nVe=de(M6,!0,2);var Q6=de(G6,!0);var rVe=de(w6,!0,2),iVe=de(O6,!0,2),J6=de(R6,!0,2);var Z6=de(z6,!0),e4=de(V6,!0,2);var oVe=de(L6,!0,2);var sVe=de(N6,!0,2);var $v=class{static getFirestoreProdDbName(e,n){return n?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||n?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(n){return b.error("Error in isTestingDb:",n),!1}}};var t4=(()=>{let e=class e{constructor(r,i,o){this.configService=r,this.authService=i,this.loggingService=o,this.firestore$=new le(null);try{oc([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(En(([s,a])=>!!s&&!!a),_n(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let h=sessionStorage?.getItem("veltFirestoreLogLevel")||zt?.firebaseLogLevel||"silent";cM(h)}catch(h){this.loggingService.catch("Error in FirestoreService setLogLevel: ",h)}let l=$v.getFirestoreProdDbName(a,s.firebaseOptions),d=this.configService.getProxyConfig();if(d?.v2DbHost){let h={host:d.v2DbHost,ssl:!0};d.forceLongPolling?h.experimentalForceLongPolling=!0:h.experimentalAutoDetectLongPolling=!0,c&&(h.localCache=$M({tabManager:WM()}));try{this.firestore$.next(Bv(ir(),h,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next(Oh(l))}}else if(c)try{let h=ir(),f=Bv(h,{localCache:$M({tabManager:WM()})},l);this.firestore$.next(f)}catch{this.firestore$.next(Oh(l))}else this.firestore$.next(Oh(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let r=this.getFirestoreValue()||Oh("DocumentIdDb");if(r){let i=Hv(r,"generateDocumentId");return Em(i).id}return}catch(r){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",r);return}}};e.\u0275fac=function(i){return new(i||e)(z(fo),z(vd),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Wv=(()=>{let e=class e{constructor(r,i,o){this.authService=r,this.configService=i,this.loggingService=o,this.db$=new le(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=BV(c,a.v1DbHost),a?.forceLongPolling&&kb());let l=Vd(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(r){try{let o=r?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(z(vd),z(fo),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Or={doc:Em,collection:Hv,collectionGroup:q6,query:J6,getDoc:zM,getDocs:X6,getCountFromServer:Y6,setDoc:e4,deleteDoc:K6,onSnapshot:Q6,runTransaction:Z6},r4=(()=>{let e=class e{constructor(r,i,o){this.firestoreService=r,this.databaseService=i,this.loggingService=o}read(r){return y(this,null,function*(){if((r.store??"firestore")==="rtdb"){let a=this.databaseService.getDbValue();return a?{data:(yield _g(Bd(a,r.location)))?.val()}:{data:void 0}}let o=this.firestoreService.getFirestoreValue();return o?{data:(yield zM(Em(o,r.location)))?.data()}:{data:void 0}})}runTransaction(r){return y(this,null,function*(){return r()})}firestoreDoc(r,i){return Or.doc(r,i)}firestoreCollection(r,i){return Or.collection(r,i)}firestoreCollectionGroup(r,i){return Or.collectionGroup(r,i)}firestoreQuery(r,...i){return Or.query(r,...i)}firestoreGetDoc(r){return Or.getDoc(r)}firestoreGetDocs(r){return Or.getDocs(r)}firestoreGetCountFromServer(r){return Or.getCountFromServer(r)}firestoreSetDoc(r,i,o){return o?Or.setDoc(r,i,o):Or.setDoc(r,i)}firestoreDeleteDoc(r){return Or.deleteDoc(r)}firestoreOnSnapshot(r,i,o){return o?Or.onSnapshot(r,i,o):Or.onSnapshot(r,i)}firestoreRunTransaction(r,i){return Or.runTransaction(r,i)}addComment(r){return this.deferred("addComment")}editComment(r){return this.deferred("editComment")}addReaction(r){return this.deferred("addReaction")}editReaction(r){return this.deferred("editReaction")}deleteReaction(r){return this.deferred("deleteReaction")}addArea(r){return this.deferred("addArea")}deleteArea(r){return this.deferred("deleteArea")}recordDocumentView(r){return this.deferred("recordDocumentView")}getActivitiesForDocuments(r){return this.deferred("getActivitiesForDocuments")}getActivitiesForEntity(r){return this.deferred("getActivitiesForEntity")}deleteComment(r){return this.deferred("deleteComment")}setCommentResolved(r){return this.deferred("setCommentResolved")}setCommentMetadata(r){return this.deferred("setCommentMetadata")}bumpCommentViews(r){return this.deferred("bumpCommentViews")}markCommentThreadRead(r){return this.deferred("markCommentThreadRead")}markNotificationRead(r){return this.deferred("markNotificationRead")}addNotification(r){return this.deferred("addNotification")}deleteNotification(r){return this.deferred("deleteNotification")}updateNotification(r){return this.deferred("updateNotification")}updatePresence(r){return this.deferred("updatePresence")}grantAccess(r){return this.deferred("grantAccess")}revokeAccess(r){return this.deferred("revokeAccess")}getAccess(r){return this.deferred("getAccess")}upsertOrgUserProfile(r){return this.deferred("upsertOrgUserProfile")}upsertDocMetadata(r){return this.deferred("upsertDocMetadata")}upsertOrgMetadata(r){return this.deferred("upsertOrgMetadata")}createActivity(r){return this.deferred("createActivity")}saveCrdtVersion(r){return this.deferred("saveCrdtVersion")}getCrdtVersion(r){return this.deferred("getCrdtVersion")}listCrdtVersions(r){return this.deferred("listCrdtVersions")}getOrganizationUsers(r){return this.deferred("getOrganizationUsers")}setLocationMetadata(r){return this.deferred("setLocationMetadata")}fetchLocations(r){return this.deferred("fetchLocations")}createFolder(r){return this.deferred("createFolder")}setDocumentMetadata(r){return this.deferred("setDocumentMetadata")}getDocuments(r){return this.deferred("getDocuments")}fetchDocuments(r){return this.deferred("fetchDocuments")}fetchFolders(r){return this.deferred("fetchFolders")}fetchCommentAnnotations(r){return this.deferred("fetchCommentAnnotations")}getCommentAnnotationsCount(r){return this.deferred("getCommentAnnotationsCount")}markNotificationReadDoc(r){return this.deferred("markNotificationReadDoc")}getUserPermissions(r){return this.deferred("getUserPermissions")}setUserConfig(r){return this.deferred("setUserConfig")}addMultiThread(r){return this.deferred("addMultiThread")}editMultiThread(r){return this.deferred("editMultiThread")}deleteMultiThread(r){return this.deferred("deleteMultiThread")}getUploadUrl(r){return this.deferred("getUploadUrl")}getDownloadUrl(r){return this.deferred("getDownloadUrl")}deleteAttachment(r){return this.deferred("deleteAttachment")}getNotificationsForDocuments(r){return this.deferred("getNotificationsForDocuments")}getDocumentMetadataFromIds(r){return this.deferred("getDocumentMetadataFromIds")}getCrossOrgUserNotifications(r){return this.deferred("getCrossOrgUserNotifications")}deferred(r){return this.loggingService.warn(`[WB] FirebaseDbAdapter.${r} called but write-op wiring is deferred to Phase A (self-hosting Step 0). The SDK uses its existing direct write path in Step 0.`),Promise.resolve({ok:!1,code:"unimplemented",message:`FirebaseDbAdapter.${r} wiring deferred to Phase A`})}};e.\u0275fac=function(i){return new(i||e)(z(t4),z(Wv),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Dce={comment:{mode:"persistent",scope:"doc"},notification:{mode:"persistent",scope:"user"},notificationIndex:{mode:"persistent",scope:"user"},crdt:{mode:"persistent",scope:"doc"},presence:{mode:"ephemeral",scope:"doc"},crdtSyncPresence:{mode:"ephemeral",scope:"doc"},crdtPresence:{mode:"ephemeral",scope:"doc"},liveState:{mode:"ephemeral",scope:"doc"},cursor:{mode:"ephemeral",scope:"doc"},huddle:{mode:"ephemeral",scope:"doc"},syncVideoPlayer:{mode:"ephemeral",scope:"doc"},heartbeat:{mode:"ephemeral",scope:"org"},flockSession:{mode:"ephemeral",scope:"doc"},selection:{mode:"ephemeral",scope:"doc"},reaction:{mode:"persistent",scope:"doc"},area:{mode:"persistent",scope:"doc"},lastActivityTimestamp:{mode:"persistent",scope:"org"},lastNotificationTimestamp:{mode:"persistent",scope:"org"},documentViews:{mode:"persistent",scope:"doc"},commentViews:{mode:"persistent",scope:"doc"},organizationCommentViews:{mode:"persistent",scope:"org"},folderCommentViews:{mode:"persistent",scope:"org"},userConfig:{mode:"persistent",scope:"user"},organizationUserConfig:{mode:"persistent",scope:"user"},organizationUsers:{mode:"persistent",scope:"org"},organizationGroups:{mode:"persistent",scope:"org"},customerMetadata:{mode:"persistent",scope:"org"},multiThread:{mode:"persistent",scope:"doc"}};function i4(t){return Dce[t]}var Ze={getDatabase:Vd,ref:Bd,query:a$,get:_g,set:u$,update:d$,remove:c$,push:s$,runTransaction:l$,onValue:Gb,onChildAdded:n$,onChildChanged:r$,onChildRemoved:i$,off:t$,objectVal:ZH,listVal:JH,stateChanges:e$,onDisconnect:o$},o4=(()=>{let e=class e{constructor(r,i){this.databaseService=r,this.loggingService=i}getServerTimeOffset(){return y(this,null,function*(){try{let r=this.databaseService.getDbValue();if(!r)return 0;let o=(yield _g(Bd(r,e.SERVER_TIME_OFFSET_PATH)))?.val();return typeof o=="number"?o:0}catch(r){return this.loggingService.catch("Error in FirebaseRealtimeAdapter getServerTimeOffset: ",r),0}})}onServerTimeOffset(r){let i=null,o=null;try{o=this.databaseService.getDb().subscribe(s=>{if(s){let a=Bd(s,e.SERVER_TIME_OFFSET_PATH);i=Gb(a,c=>{try{r(c?.val())}catch(l){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset callback: ",l)}})}})}catch(s){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset: ",s)}return()=>{try{i&&(i(),i=null),o?.unsubscribe(),o=null}catch(s){this.loggingService.catch("Error tearing down FirebaseRealtimeAdapter onServerTimeOffset: ",s)}}}getChannelTag(r){return i4(r)}getDatabaseInstance(r){return r?Ze.getDatabase(void 0,r):Ze.getDatabase()}rtdbRef(r,i){return Ze.ref(r,i)}rtdbQueryRef(r,...i){return Ze.query(r,...i)}rtdbGet(r){return Ze.get(r)}rtdbSet(r,i,o){return this.getChannelTag(r),Ze.set(i,o)}rtdbUpdate(r,i,o){return this.getChannelTag(r),Ze.update(i,o)}rtdbRemove(r,i){return this.getChannelTag(r),Ze.remove(i)}rtdbPush(r,i,o){return this.getChannelTag(r),o===void 0?Ze.push(i):Ze.push(i,o)}rtdbRunTransaction(r,i,o){return this.getChannelTag(r),Ze.runTransaction(i,o)}rtdbOnValue(r,i,o,s,a){return this.getChannelTag(r),typeof s=="function"?a?Ze.onValue(i,o,s,a):Ze.onValue(i,o,s):s?Ze.onValue(i,o,s):Ze.onValue(i,o)}rtdbOnChildAdded(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildAdded(i,o,s):Ze.onChildAdded(i,o)}rtdbOnChildChanged(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildChanged(i,o,s):Ze.onChildChanged(i,o)}rtdbOnChildRemoved(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildRemoved(i,o,s):Ze.onChildRemoved(i,o)}rtdbOff(r,i,o){Ze.off(r,i,o)}rtdbObjectVal$(r,i){return this.getChannelTag(r),Ze.objectVal(i)}rtdbListVal$(r,i){return this.getChannelTag(r),Ze.listVal(i)}rtdbStateChanges$(r,i){return this.getChannelTag(r),Ze.stateChanges(i)}rtdbOnDisconnectSet(r,i,o){return this.getChannelTag(r),Ze.onDisconnect(i).set(o)}rtdbOnDisconnectUpdate(r,i,o){return this.getChannelTag(r),Ze.onDisconnect(i).update(o)}rtdbOnDisconnectRemove(r,i){return this.getChannelTag(r),Ze.onDisconnect(i).remove()}rtdbOnDisconnectCancel(r,i){return this.getChannelTag(r),Ze.onDisconnect(i).cancel()}subscribe(r,i,o,s){return{unsubscribe:()=>{}}}publish(r,i,o){return y(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.publish wiring deferred to Phase A"}})}presence(r,i){return y(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.presence wiring deferred to Phase A"}})}onDisconnect(r,i){return y(this,null,function*(){return()=>{}})}};e.SERVER_TIME_OFFSET_PATH=".info/serverTimeOffset",e.\u0275fac=function(i){return new(i||e)(z(Wv),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function kVe(t,e,n){let r=t?.[e];return typeof r!="function"?Promise.resolve({ok:!1,code:"unimplemented",message:`the portable adapter does not implement '${e}'`}):r.call(t,n)}var La=null,qv=null,zv,s4;function Rce(t){if(!(t&&t===s4&&zv)){s4=t;try{zv?.()}catch(e){b.catch("Error releasing the portable capability tracker: ",e)}zv=void 0,qv=null;try{zv=t?.onCapabilitiesChanged?.(e=>{qv=e?.size?new Set(e):null})}catch(e){b.catch("Error binding the portable capability tracker: ",e)}}}function FVe(t,e,n,r={data:{},operation:null}){return t.portableCapability$(e).pipe(Zn(i=>i?t.dbListener(n):ot(r)))}var qM=new Set;function KM(t){return qM.add(t),()=>qM.delete(t)}function UVe(t){return new Promise(e=>{let n=!1,r=null,i=()=>{if(!n){n=!0,clearTimeout(o);try{r?.()}catch{}e()}},o=setTimeout(i,t);r=KM(i),La&&i()})}function VVe(t){return cf(()=>{let e=!1;try{if(t.isPortableFeedActive())return ot(null)}catch(r){e=!0,t.onError("portable check",r)}let n=new ue(r=>KM(()=>{try{(e||t.isPortableFeedActive())&&r.next(null)}catch(i){e=!0,r.next(null),t.onError("registration re-check",i)}}));return vs(t.firebaseDb$().pipe(En(r=>!!r)),n)})}function Nce(t){let e=t?.message;return typeof e=="string"&&/^NG0205(?!\d)/.test(e)}function BVe(t){if(La=t??null,Rce(La?.realtime),La)for(let e of Array.from(qM))try{e()}catch(n){b.catch("Error in portable adapter registration listener: ",n)}}function q2(){return La}var GVe=(()=>{let e=class e{constructor(r){this.injector=r}get configService(){return this._configService??=this.injector.get(fo)}get authService(){return this._authService??=this.injector.get(vd)}isPortableBackendActive(){return this.isPortableActive()}evaluatePortableGates(){try{return{chunkRegistered:!!La,flagOn:this.configService.getEnablePortableBackend()===!0,identifyRecorded:!!this.authService.getPortableBackend()}}catch(r){return Nce(r)||b.catch("Error in AdapterSelectorService evaluatePortableGates: ",r),null}}isPortableActive(){let r=this.evaluatePortableGates();return!!r&&r.chunkRegistered&&r.flagOn&&r.identifyRecorded}isPortableBackendPending(){let r=this.evaluatePortableGates();return!!r&&!r.chunkRegistered&&r.flagOn&&r.identifyRecorded}isPortableSession(){let r=this.evaluatePortableGates();return!!r&&r.flagOn&&r.identifyRecorded}portableConnectionAnnounces(r){try{return this.resolveRealtimeAdapter()?.hasCapability?.(r)===!0}catch(i){return b.catch("Error in AdapterSelectorService portableConnectionAnnounces: ",i),!1}}portableCapability$(r){return this.portableConnectionChanges$().pipe(De(()=>this.portableConnectionAnnounces(r)),ai())}portableCapabilityState(r){try{return!this.isPortableBackendActive()||!qv?"unknown":this.portableConnectionAnnounces(r)?"announced":qv.has(r)?"unknown":"absent"}catch(i){return b.catch("Error in AdapterSelectorService portableCapabilityState: ",i),"unknown"}}portableConnectionChanges$(){return new ue(r=>{let i,o=()=>{try{i?.(),i=void 0,this.isPortableBackendActive()&&(i=this.resolveRealtimeAdapter()?.onCapabilitiesChanged?.(()=>r.next()))}catch(a){b.catch("Error in AdapterSelectorService portableConnectionChanges$ bind: ",a)}r.next()};o();let s=KM(o);return()=>{s(),i?.()}})}resolveDbAdapter(){return this.isPortableActive()?La.db:this.injector.get(r4)}resolveRealtimeAdapter(){return this.isPortableActive()?La.realtime:this.injector.get(o4)}};e.\u0275fac=function(i){return new(i||e)(z(Ke))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function HVe(t){if(!t||typeof t!="object")return!1;let e=t;return e.ok?!1:e.code==="unimplemented"?!0:e.code==="invalid-argument"&&/^unsupported operation\b/i.test(String(e.message??""))}var qVe=new Set(f2);function KVe(t){try{let e=t?.reasonCode;return typeof e!="string"||!e.trim()?"":` [reason: ${e.trim()}]`}catch{return""}}var XVe="portable transport not connected",QVe="portable transport disconnected",JVe="portable transport send failed",wce="portable publish op '",bce="' requires a channel on the OperationRequest";function ZVe(t){return`${wce}${t}${bce}`}var eBe="portable request timed out",tBe="portable request failed in transport",nBe="portable session not established",rBe="portable apiEndpoint is not a secure URL; request not sent",iBe="portable request body could not be serialized; request not sent",oBe="portable request failed before it was sent";export{B as a,me as b,g4 as c,Oce as d,Mce as e,Lce as f,y as g,gt as h,ue as i,IS as j,Be as k,le as l,ac as m,oz as n,sz as o,nc as p,hr as q,ot as r,az as s,cz as t,z4 as u,De as v,oc as w,cf as x,lz as y,Hi as z,mz as A,bo as B,B4 as C,vs as D,En as E,w4 as F,ES as G,_S as H,U4 as I,sE as J,_n as K,yS as L,ai as M,rf as N,sc as O,aE as P,SS as Q,G4 as R,cE as S,j4 as T,nn as U,Zn as V,Is as W,H4 as X,lE as Y,$4 as Z,K4 as _,Z as $,ME as aa,J as ba,Lo as ca,q as da,z as ea,X as fa,er as ga,On as ha,$i as ia,bP as ja,OP as ka,jP as la,HP as ma,Ke as na,on as oa,Wn as pa,fr as qa,Xi as ra,Rc as sa,Br as ta,Kz as ua,Wt as va,LC as wa,f8 as xa,xs as ya,f_ as za,w_ as Aa,I8 as Ba,i5 as Ca,o5 as Da,s5 as Ea,l5 as Fa,u5 as Ga,R5 as Ha,Fo as Ia,Re as Ja,x5 as Ka,Aq as La,Cq as Ma,Zi as Na,kf as Oa,Bo as Pa,j_ as Qa,at as Ra,xq as Sa,no as Ta,Mc as Ua,_1 as Va,S9 as Wa,ks as Xa,ro as Ya,Uf as Za,A1 as _a,L9 as $a,R1 as ab,N1 as bb,W_ as cb,Fs as db,P1 as eb,x1 as fb,B9 as gb,j9 as hb,H9 as ib,$9 as jb,W9 as kb,z9 as lb,q9 as mb,k1 as nb,_D as ob,TD as pb,F1 as qb,yD as rb,ID as sb,U1 as tb,vD as ub,SD as vb,B1 as wb,Z9 as xb,G1 as yb,H1 as zb,$1 as Ab,iK as Bb,sK as Cb,aK as Db,lK as Eb,uK as Fb,dK as Gb,hK as Hb,fK as Ib,pK as Jb,gK as Kb,X1 as Lb,Q1 as Mb,NK as Nb,bK as Ob,BK as Pb,sF as Qb,AD as Rb,aF as Sb,cF as Tb,lF as Ub,$K as Vb,uF as Wb,hF as Xb,WK as Yb,zK as Zb,qK as _b,KK as $b,ZK as ac,eY as bc,tY as cc,nY as dc,rY as ec,iY as fc,oY as gc,sY as hc,aY as ic,cY as jc,lY as kc,uY as lc,hY as mc,pY as nc,gY as oc,mY as pc,EY as qc,_Y as rc,IY as sc,$f as tc,Wf as uc,wD as vc,uAe as wc,dAe as xc,hAe as yc,QY as zc,GD as Ac,fAe as Bc,pAe as Cc,gAe as Dc,io as Ec,HF as Fc,_7 as Gc,sU as Hc,T7 as Ic,KD as Jc,y7 as Kc,I7 as Lc,v7 as Mc,S7 as Nc,C7 as Oc,R7 as Pc,w7 as Qc,YD as Rc,uT as Sc,dT as Tc,W7 as Uc,K7 as Vc,wU as Wc,_X as Xc,TX as Yc,aR as Zc,jU as _c,dR as $c,pd as ad,vr as bd,Hs as cd,zT as dd,qc as ed,nr as fd,Pe as gd,Xt as hd,zn as id,uo as jd,rr as kd,qs as ld,ir as md,$e as nd,lZ as od,kLe as pd,FLe as qd,ULe as rd,Ei as sd,Ks as td,Qo as ud,_i as vd,de as wd,Ti as xd,Jo as yd,nPe as zd,rPe as Ad,iPe as Bd,Xs as Cd,Mee as Dd,Pee as Ed,qee as Fd,Zc as Gd,el as Hd,Bxe as Id,Gxe as Jd,zFe as Kd,qFe as Ld,KFe as Md,YFe as Nd,XFe as Od,QFe as Pd,Zo as Qd,oke as Rd,ske as Sd,ake as Td,WU as Ud,VX as Vd,cp as Wd,zt as Xd,b as Yd,kDe as Zd,FDe as _d,UDe as $d,VDe as ae,BDe as be,GDe as ce,jDe as de,oo as ee,HDe as fe,$De as ge,WDe as he,zDe as ie,vX as je,SX as ke,AX as le,CX as me,DX as ne,RX as oe,qDe as pe,NX as qe,cR as re,wX as se,Ir as te,TT as ue,bX as ve,id as we,xn as xe,OX as ye,yT as ze,MX as Ae,LX as Be,PX as Ce,KDe as De,YDe as Ee,XDe as Fe,xX as Ge,k as He,BU as Ie,MRe as Je,LRe as Ke,PRe as Le,xRe as Me,od as Ne,VRe as Oe,BRe as Pe,GRe as Qe,Wr as Re,Et as Se,zU as Te,qU as Ue,mNe as Ve,ENe as We,KU as Xe,hR as Ye,YU as Ze,fR as _e,bT as $e,BX as af,GX as bf,jX as cf,HX as df,$X as ef,WX as ff,zX as gf,qX as hf,KX as if,YX as jf,XX as kf,QX as lf,ZU as mf,eV as nf,tV as of,nV as pf,rV as qf,so as rf,jNe as sf,OT as tf,iV as uf,oV as vf,sV as wf,aV as xf,cV as yf,lV as zf,uV as Af,dV as Bf,hV as Cf,fV as Df,pV as Ef,gV as Ff,mV as Gf,Awe as Hf,Cwe as If,EV as Jf,pR as Kf,_V as Lf,TV as Mf,IV as Nf,vV as Of,ibe as Pf,obe as Qf,JX as Rf,ZX as Sf,l0e as Tf,MT as Uf,yR as Vf,$c as Wf,BV as Xf,y0e as Yf,jc as Zf,Yo as _f,I0e as $f,v0e as ag,S0e as bg,jV as cg,A0e as dg,C0e as eg,D0e as fg,R0e as gg,N0e as hg,w0e as ig,b0e as jg,HV as kg,$V as lg,O0e as mg,M0e as ng,tQ as og,L0e as pg,P0e as qg,x0e as rg,k0e as sg,F0e as tg,WV as ug,ad as vg,U0e as wg,zV as xg,KV as yg,NV as zg,wV as Ag,nQ as Bg,rQ as Cg,UT as Dg,hp as Eg,V0e as Fg,B0e as Gg,ao as Hg,G0e as Ig,cd as Jg,sQ as Kg,j0e as Lg,DR as Mg,OV as Ng,aQ as Og,xT as Pg,H0e as Qg,$0e as Rg,YV as Sg,XV as Tg,cQ as Ug,Gc as Vg,lQ as Wg,hQ as Xg,W0e as Yg,ZV as Zg,z0e as _g,q0e as $g,fQ as ah,pQ as bh,gQ as ch,mQ as dh,Wc as eh,K0e as fh,Y0e as gh,X0e as hh,vR as ih,Q0e as jh,_Q as kh,J0e as lh,Z0e as mh,tB as nh,eMe as oh,tMe as ph,nMe as qh,rMe as rh,iMe as sh,oMe as th,sMe as uh,LT as vh,aMe as wh,cMe as xh,lMe as yh,RR as zh,uMe as Ah,kV as Bh,dMe as Ch,hMe as Dh,fMe as Eh,pMe as Fh,gMe as Gh,mMe as Hh,EMe as Ih,_Me as Jh,TMe as Kh,yMe as Lh,IMe as Mh,vMe as Nh,SMe as Oh,AMe as Ph,CMe as Qh,DMe as Rh,RMe as Sh,NMe as Th,wMe as Uh,bMe as Vh,OMe as Wh,MMe as Xh,vQ as Yh,LMe as Zh,PMe as _h,xMe as $h,FV as ai,kMe as bi,FMe as ci,pp as di,SQ as ei,UMe as fi,VMe as gi,BMe as hi,GMe as ii,AQ as ji,jMe as ki,HMe as li,cB as mi,wR as ni,ud as oi,$Me as pi,dp as qi,WMe as ri,zMe as si,qMe as ti,AR as ui,KMe as vi,bQ as wi,YMe as xi,XMe as yi,HQ as zi,QMe as Ai,JMe as Bi,ZMe as Ci,UV as Di,eLe as Ei,$Q as Fi,iJ as Gi,oJ as Hi,vt as Ii,Td as Ji,tRe as Ki,nRe as Li,rRe as Mi,iRe as Ni,oRe as Oi,sRe as Pi,aRe as Qi,cRe as Ri,lRe as Si,uRe as Ti,dRe as Ui,hRe as Vi,IT as Wi,fRe as Xi,pRe as Yi,gRe as Zi,vT as _i,mRe as $i,ERe as aj,_Re as bj,TRe as cj,yRe as dj,IRe as ej,vRe as fj,ST as gj,SRe as hj,ARe as ij,AT as jj,PU as kj,xU as lj,kU as mj,FU as nj,CT as oj,Zs as pj,Rt as qj,fo as rj,nl as sj,pne as tj,vne as uj,Cke as vj,_y as wj,a2 as xj,zke as yj,qn as zj,qke as Aj,tVe as Bj,nVe as Cj,rVe as Dj,iVe as Ej,oVe as Fj,sVe as Gj,$v as Hj,t4 as Ij,Wv as Jj,r4 as Kj,i4 as Lj,o4 as Mj,kVe as Nj,FVe as Oj,KM as Pj,UVe as Qj,VVe as Rj,BVe as Sj,q2 as Tj,GVe as Uj,f2 as Vj,t1e as Wj,n1e as Xj,r1e as Yj,i1e as Zj,o1e as _j,s1e as $j,a1e as ak,c1e as bk,l1e as ck,u1e as dk,d1e as ek,h1e as fk,HVe as gk,KVe as hk,XVe as ik,QVe as jk,JVe as kk,wce as lk,bce as mk,ZVe as nk,eBe as ok,tBe as pk,nBe as qk,rBe as rk,iBe as sk,oBe as tk,T2 as uk,y2 as vk,Sy as wk,v1e as xk,S1e as yk,W2 as zk,vd as Ak};
|
|
174
|
+
`+t.stack),e}function R3(t){return(function(n,r){if(typeof n!="object"||n===null)return!1;let i=n;for(let o of r)if(o in i&&typeof i[o]=="function")return!0;return!1})(t,["next","error","complete"])}var Ni=class extends jl{constructor(e,n,r,i){super(e,n,r,i),this.type="firestore",this._queue=new Sv,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return y(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Sv(e),this._firestoreClient=void 0,yield e}})}};function Bv(t,e,n){n||(n=Hg);let r=uo(t,"firestore");if(r.isInitialized(n)){let i=r.getImmediate({identifier:n}),o=r.getOptions(n);if(mi(o,e))return i;throw new $(x.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new $(x.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<$W)throw new $(x.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&vr(e.host)&&Hs(e.host),r.initialize({options:e,instanceIdentifier:n})}function Oh(t,e){let n=typeof t=="object"?t:ir(),r=typeof t=="string"?t:e||Hg,i=uo(n,"firestore").getImmediate({identifier:r});if(!i._initialized){let o=pd("firestore");o&&m6(i,...o)}return i}function Mh(t){if(t._terminated)throw new $(x.FAILED_PRECONDITION,"The client has already been terminated.");return t._firestoreClient||gce(t),t._firestoreClient}function gce(t){var e,n,r;let i=t._freezeSettings(),o=(function(a,c,l,d){return new mO(a,c,l,d.host,d.ssl,d.experimentalForceLongPolling,d.experimentalAutoDetectLongPolling,p6(d.experimentalLongPollingOptions),d.useFetchStreams,d.isUsingEmulator)})(t._databaseId,((e=t._app)===null||e===void 0?void 0:e.options.appId)||"",t._persistenceKey,i);t._componentsProvider||!((n=i.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((r=i.localCache)===null||r===void 0)&&r._onlineComponentProvider)&&(t._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),t._firestoreClient=new W0(t._authCredentials,t._appCheckCredentials,t._queue,o,t._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(t._componentsProvider))}var z0=class{constructor(e="count",n){this._internalFieldPath=n,this.type="AggregateField",this.aggregateType=e}},q0=class{constructor(e,n,r){this._userDataWriter=n,this._data=r,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var cs=class t{constructor(e){this._byteString=e}static fromBase64String(e){try{return new t(Bt.fromBase64String(e))}catch(n){throw new $(x.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(e){return new t(Bt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:t._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(lm(e,t._jsonSchema))return t.fromBase64String(e.bytes)}};cs._jsonSchemaVersion="firestore/bytes/1.0",cs._jsonSchema={type:Vt("string",cs._jsonSchemaVersion),bytes:Vt("string")};var Ah=class{constructor(...e){for(let n=0;n<e.length;++n)if(e[n].length===0)throw new $(x.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Qt(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var sm=class{constructor(e){this._methodName=e}};var _a=class t{constructor(e,n){if(!isFinite(e)||e<-90||e>90)throw new $(x.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(n)||n<-180||n>180)throw new $(x.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=e,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return Ie(this._lat,e._lat)||Ie(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:t._jsonSchemaVersion}}static fromJSON(e){if(lm(e,t._jsonSchema))return new t(e.latitude,e.longitude)}};_a._jsonSchemaVersion="firestore/geoPoint/1.0",_a._jsonSchema={type:Vt("string",_a._jsonSchemaVersion),latitude:Vt("number"),longitude:Vt("number")};var Ta=class t{constructor(e){this._values=(e||[]).map(n=>n)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(r,i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;++o)if(r[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:t._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(lm(e,t._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(n=>typeof n=="number"))return new t(e.vectorValues);throw new $(x.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ta._jsonSchemaVersion="firestore/vectorValue/1.0",Ta._jsonSchema={type:Vt("string",Ta._jsonSchemaVersion),vectorValues:Vt("object")};var mce=/^__.*__$/,K0=class{constructor(e,n,r){this.data=e,this.fieldMask=n,this.fieldTransforms=r}toMutation(e,n){return this.fieldMask!==null?new Di(e,this.data,this.fieldMask,n,this.fieldTransforms):new Da(e,this.data,n,this.fieldTransforms)}},Av=class{constructor(e,n,r){this.data=e,this.fieldMask=n,this.fieldTransforms=r}toMutation(e,n){return new Di(e,this.data,this.fieldMask,n,this.fieldTransforms)}};function y6(t){switch(t){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw re(40011,{Ec:t})}}var Y0=class t{constructor(e,n,r,i,o,s){this.settings=e,this.databaseId=n,this.serializer=r,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new t(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var n;let r=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:r,mc:!1});return i.fc(e),i}gc(e){var n;let r=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:r,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return Dv(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(n=>e.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>e.isPrefixOf(n.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(y6(this.Ec)&&mce.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},X0=class{constructor(e,n,r){this.databaseId=e,this.ignoreUndefinedProperties=n,this.serializer=r||kv(e)}Dc(e,n,r,i=!1){return new Y0({Ec:e,methodName:n,bc:r,path:Qt.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function Gv(t){let e=t._freezeSettings(),n=kv(t._databaseId);return new X0(t._databaseId,!!e.ignoreUndefinedProperties,n)}function I6(t,e,n,r,i,o={}){let s=t.Dc(o.merge||o.mergeFields?2:0,e,n,i);jM("Data must be an object, but it was:",s,r);let a=S6(r,s),c,l;if(o.merge)c=new Nr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let d=[];for(let h of o.mergeFields){let f=Q0(e,h,n);if(!s.contains(f))throw new $(x.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);C6(d,f)||d.push(f)}c=new Nr(d),l=s.fieldTransforms.filter(h=>c.covers(h.field))}else c=null,l=s.fieldTransforms;return new K0(new Vn(a),c,l)}var Cv=class t extends sm{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof t}};function Ece(t,e,n,r){let i=t.Dc(1,e,n);jM("Data must be an object, but it was:",i,r);let o=[],s=Vn.empty();Oa(r,(c,l)=>{let d=HM(e,c,n);l=Pe(l);let h=i.gc(d);if(l instanceof Cv)o.push(d);else{let f=mm(l,h);f!=null&&(o.push(d),s.set(d,f))}});let a=new Nr(o);return new Av(s,a,i.fieldTransforms)}function _ce(t,e,n,r,i,o){let s=t.Dc(1,e,n),a=[Q0(e,r,n)],c=[i];if(o.length%2!=0)throw new $(x.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(Q0(e,o[f])),c.push(o[f+1]);let l=[],d=Vn.empty();for(let f=a.length-1;f>=0;--f)if(!C6(l,a[f])){let g=a[f],E=c[f];E=Pe(E);let I=s.gc(g);if(E instanceof Cv)l.push(g);else{let S=mm(E,I);S!=null&&(l.push(g),d.set(g,S))}}let h=new Nr(l);return new Av(d,h,s.fieldTransforms)}function v6(t,e,n,r=!1){return mm(n,t.Dc(r?4:3,e))}function mm(t,e){if(A6(t=Pe(t)))return jM("Unsupported field value:",e,t),S6(t,e);if(t instanceof sm)return(function(r,i){if(!y6(i.Ec))throw i.wc(`${r._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${r._methodName}() is not currently supported inside arrays`);let o=r._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(t,e),null;if(t===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(r,i){let o=[],s=0;for(let a of r){let c=mm(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(t,e)}return(function(r,i){if((r=Pe(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return rae(i.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){let o=yt.fromDate(r);return{timestampValue:Eh(i.serializer,o)}}if(r instanceof yt){let o=new yt(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:Eh(i.serializer,o)}}if(r instanceof _a)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof cs)return{bytesValue:DW(i.serializer,r._byteString)};if(r instanceof Zt){let o=i.databaseId,s=r.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:SM(r.firestore._databaseId||i.databaseId,r._key.path)}}if(r instanceof Ta)return(function(s,a){return{mapValue:{fields:{[EM]:{stringValue:_M},[hh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return vM(a.serializer,l)})}}}}}})(r,i);throw i.wc(`Unsupported field value: ${Nv(r)}`)})(t,e)}function S6(t,e){let n={};return Y3(t)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Oa(t,(r,i)=>{let o=mm(i,e.Vc(r));o!=null&&(n[r]=o)}),{mapValue:{fields:n}}}function A6(t){return!(typeof t!="object"||t===null||t instanceof Array||t instanceof Date||t instanceof yt||t instanceof _a||t instanceof cs||t instanceof Zt||t instanceof sm||t instanceof Ta)}function jM(t,e,n){if(!A6(n)||!L3(n)){let r=Nv(n);throw r==="an object"?e.wc(t+" a custom object"):e.wc(t+" "+r)}}function Q0(t,e,n){if((e=Pe(e))instanceof Ah)return e._internalPath;if(typeof e=="string")return HM(t,e);throw Dv("Field path arguments must be of type string or ",t,!1,void 0,n)}var Tce=new RegExp("[~\\*/\\[\\]]");function HM(t,e,n){if(e.search(Tce)>=0)throw Dv(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new Ah(...e.split("."))._internalPath}catch{throw Dv(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function Dv(t,e,n,r,i){let o=r&&!r.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${r}`),s&&(c+=` in document ${i}`),c+=")"),new $(x.INVALID_ARGUMENT,a+t+c)}function C6(t,e){return t.some(n=>n.isEqual(e))}var Hl=class{constructor(e,n,r,i,o){this._firestore=e,this._userDataWriter=n,this._key=r,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new Zt(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new J0(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let n=this._document.data.field(jv("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n)}}},J0=class extends Hl{data(){return super.data()}};function jv(t,e){return typeof e=="string"?HM(t,e):e instanceof Ah?e._internalPath:e._delegate._internalPath}function D6(t){if(t.limitType==="L"&&t.explicitOrderBy.length===0)throw new $(x.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var am=class{},Ch=class extends am{};function R6(t,e,...n){let r=[];e instanceof am&&r.push(e),r=r.concat(n),(function(o){let s=o.filter(c=>c instanceof Dh).length,a=o.filter(c=>c instanceof cm).length;if(s>1||s>0&&a>0)throw new $(x.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(r);for(let i of r)t=i._apply(t);return t}var cm=class t extends Ch{constructor(e,n,r){super(),this._field=e,this._op=n,this._value=r,this.type="where"}static _create(e,n,r){return new t(e,n,r)}_apply(e){let n=this._parse(e);return P6(e._query,n),new Ri(e.firestore,e.converter,wO(e._query,n))}_parse(e){let n=Gv(e.firestore);return(function(o,s,a,c,l,d,h){let f;if(l.isKeyField()){if(d==="array-contains"||d==="array-contains-any")throw new $(x.INVALID_ARGUMENT,`Invalid Query. You can't perform '${d}' queries on documentId().`);if(d==="in"||d==="not-in"){w3(h,d);let E=[];for(let I of h)E.push(N3(c,o,I));f={arrayValue:{values:E}}}else f=N3(c,o,h)}else d!=="in"&&d!=="not-in"&&d!=="array-contains-any"||w3(h,d),f=v6(a,s,h,d==="in"||d==="not-in");return xe.create(l,d,f)})(e._query,"where",n,e.firestore._databaseId,this._field,this._op,this._value)}};function N6(t,e,n){let r=e,i=jv("where",t);return cm._create(i,r,n)}var Dh=class t extends am{constructor(e,n){super(),this.type=e,this._queryConstraints=n}static _create(e,n){return new t(e,n)}_parse(e){let n=this._queryConstraints.map(r=>r._parse(e)).filter(r=>r.getFilters().length>0);return n.length===1?n[0]:Je.create(n,this._getOperator())}_apply(e){let n=this._parse(e);return n.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)P6(s,c),s=wO(s,c)})(e._query,n),new Ri(e.firestore,e.converter,wO(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function w6(...t){return t.forEach(e=>x6("or",e)),Dh._create("or",t)}function b6(...t){return t.forEach(e=>x6("and",e)),Dh._create("and",t)}var Z0=class t extends Ch{constructor(e,n){super(),this._field=e,this._direction=n,this.type="orderBy"}static _create(e,n){return new t(e,n)}_apply(e){let n=(function(i,o,s){if(i.startAt!==null)throw new $(x.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new $(x.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Pl(o,s)})(e._query,this._field,this._direction);return new Ri(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new vo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,n))}};function O6(t,e="asc"){let n=e,r=jv("orderBy",t);return Z0._create(r,n)}var eM=class t extends Ch{constructor(e,n,r){super(),this.type=e,this._limit=n,this._limitType=r}static _create(e,n,r){return new t(e,n,r)}_apply(e){return new Ri(e.firestore,e.converter,zI(e._query,this._limit,this._limitType))}};function M6(t){return Tse("limit",t),eM._create("limit",t,"F")}var tM=class t extends Ch{constructor(e,n,r){super(),this.type=e,this._docOrFields=n,this._inclusive=r}static _create(e,n,r){return new t(e,n,r)}_apply(e){let n=yce(e,this.type,this._docOrFields,this._inclusive);return new Ri(e.firestore,e.converter,(function(i,o){return new vo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,n))}};function L6(...t){return tM._create("startAfter",t,!1)}function yce(t,e,n,r){if(n[0]=Pe(n[0]),n[0]instanceof Hl)return(function(o,s,a,c,l){if(!c)throw new $(x.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let d=[];for(let h of eh(o))if(h.field.isKeyField())d.push(Ll(s,c.key));else{let f=c.data.field(h.field);if(Mv(f))throw new $(x.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+h.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=h.field.canonicalString();throw new $(x.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}d.push(f)}return new Io(d,l)})(t._query,t.firestore._databaseId,e,n[0]._document,r);{let i=Gv(t.firestore);return(function(s,a,c,l,d,h){let f=s.explicitOrderBy;if(d.length>f.length)throw new $(x.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let E=0;E<d.length;E++){let I=d[E];if(f[E].field.isKeyField()){if(typeof I!="string")throw new $(x.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof I}`);if(!yM(s)&&I.indexOf("/")!==-1)throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${I}' contains a slash.`);let S=s.path.child(Ue.fromString(I));if(!ee.isDocumentKey(S))throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${S}' is not because it contains an odd number of segments.`);let L=new ee(S);g.push(Ll(a,L))}else{let S=v6(c,l,I);g.push(S)}}return new Io(g,h)})(t._query,t.firestore._databaseId,i,e,n,r)}}function N3(t,e,n){if(typeof(n=Pe(n))=="string"){if(n==="")throw new $(x.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!yM(e)&&n.indexOf("/")!==-1)throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let r=e.path.child(Ue.fromString(n));if(!ee.isDocumentKey(r))throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Ll(t,new ee(r))}if(n instanceof Zt)return Ll(t,n._key);throw new $(x.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Nv(n)}.`)}function w3(t,e){if(!Array.isArray(t)||t.length===0)throw new $(x.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function P6(t,e){let n=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(t.filters,(function(i){switch(i){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(e.op));if(n!==null)throw n===e.op?new $(x.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new $(x.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`)}function x6(t,e){if(!(e instanceof cm||e instanceof Dh))throw new $(x.INVALID_ARGUMENT,`Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Rv=class{convertValue(e,n="none"){switch(va(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Tt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,n);case 5:return e.stringValue;case 6:return this.convertBytes(ds(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,n);case 11:return this.convertObject(e.mapValue,n);case 10:return this.convertVectorValue(e.mapValue);default:throw re(62114,{value:e})}}convertObject(e,n){return this.convertObjectMap(e.fields,n)}convertObjectMap(e,n="none"){let r={};return Oa(e,(i,o)=>{r[i]=this.convertValue(o,n)}),r}convertVectorValue(e){var n,r,i;let o=(i=(r=(n=e.fields)===null||n===void 0?void 0:n[hh].arrayValue)===null||r===void 0?void 0:r.values)===null||i===void 0?void 0:i.map(s=>Tt(s.doubleValue));return new Ta(o)}convertGeoPoint(e){return new _a(Tt(e.latitude),Tt(e.longitude))}convertArray(e,n){return(e.values||[]).map(r=>this.convertValue(r,n))}convertServerTimestamp(e,n){switch(n){case"previous":let r=Lv(e);return r==null?null:this.convertValue(r,n);case"estimate":return this.convertTimestamp(jg(e));default:return null}}convertTimestamp(e){let n=us(e);return new yt(n.seconds,n.nanos)}convertDocumentKey(e,n){let r=Ue.fromString(e);se(xW(r),9688,{name:e});let i=new dh(r.get(1),r.get(3)),o=new ee(r.popFirst(5));return i.isEqual(n)||wt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),o}};function k6(t,e,n){let r;return r=t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e,r}var nM=class extends Rv{constructor(e){super(),this.firestore=e}convertBytes(e){return new cs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new Zt(this.firestore,null,n)}};function Ice(){return new z0("count")}var ma=class{constructor(e,n){this.hasPendingWrites=e,this.fromCache=n}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},ya=class t extends Hl{constructor(e,n,r,i,o,s){super(e,n,r,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let n=new nh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,n={}){if(this._document){let r=this._document.data.field(jv("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r,n.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new $(x.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,n={};return n.type=t._jsonSchemaVersion,n.bundle="",n.bundleSource="DocumentSnapshot",n.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?n:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),n.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),n)}};ya._jsonSchemaVersion="firestore/documentSnapshot/1.0",ya._jsonSchema={type:Vt("string",ya._jsonSchemaVersion),bundleSource:Vt("string","DocumentSnapshot"),bundleName:Vt("string"),bundle:Vt("string")};var nh=class extends ya{data(e={}){return super.data(e)}},Ml=class t{constructor(e,n,r,i){this._firestore=e,this._userDataWriter=n,this._snapshot=i,this.metadata=new ma(i.hasPendingWrites,i.fromCache),this.query=r}get docs(){let e=[];return this.forEach(n=>e.push(n)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,n){this._snapshot.docs.forEach(r=>{e.call(n,new nh(this._firestore,this._userDataWriter,r.key,r,new ma(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let n=!!e.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new $(x.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===n||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new nh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ma(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new nh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new ma(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,d=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),d=s.indexOf(a.doc.key)),{type:vce(a.type),doc:c,oldIndex:l,newIndex:d}})}})(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new $(x.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=t._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=xg.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let n=[],r=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(n.push(o._document),r.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function vce(t){switch(t){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return re(61501,{type:t})}}function F6(t){t=lr(t,Zt);let e=lr(t.firestore,Ni);return hce(Mh(e),t._key).then(n=>H6(e,t,n))}Ml._jsonSchemaVersion="firestore/querySnapshot/1.0",Ml._jsonSchema={type:Vt("string",Ml._jsonSchemaVersion),bundleSource:Vt("string","QuerySnapshot"),bundleName:Vt("string"),bundle:Vt("string")};var $l=class extends Rv{constructor(e){super(),this.firestore=e}convertBytes(e){return new cs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new Zt(this.firestore,null,n)}};function U6(t){t=lr(t,Ri);let e=lr(t.firestore,Ni),n=Mh(e),r=new $l(e);return D6(t._query),fce(n,t._query).then(i=>new Ml(e,r,t,i))}function V6(t,e,n){t=lr(t,Zt);let r=lr(t.firestore,Ni),i=k6(t.converter,e,n);return j6(r,[I6(Gv(r),"setDoc",t._key,i,t.converter!==null,n).toMutation(t._key,Sn.none())])}function B6(t){return j6(lr(t.firestore,Ni),[new Ul(t._key,Sn.none())])}function G6(t,...e){var n,r,i;t=Pe(t);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||R3(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(R3(e[s])){let h=e[s];e[s]=(n=h.next)===null||n===void 0?void 0:n.bind(h),e[s+1]=(r=h.error)===null||r===void 0?void 0:r.bind(h),e[s+2]=(i=h.complete)===null||i===void 0?void 0:i.bind(h)}let c,l,d;if(t instanceof Zt)l=lr(t.firestore,Ni),d=fm(t._key.path),c={next:h=>{e[s]&&e[s](H6(l,t,h))},error:e[s+1],complete:e[s+2]};else{let h=lr(t,Ri);l=lr(h.firestore,Ni),d=h._query;let f=new $l(l);c={next:g=>{e[s]&&e[s](new Ml(l,f,h,g))},error:e[s+1],complete:e[s+2]},D6(t._query)}return(function(f,g,E,I){let S=new om(I),L=new im(g,S,E);return f.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return OM(yield Iv(f),L)})),()=>{S.Ou(),f.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return MM(yield Iv(f),L)}))}})(Mh(l),d,a,c)}function j6(t,e){return(function(r,i){let o=new cr;return r.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){return Xae(yield dce(r),i,o)})),o.promise})(Mh(t),e)}function H6(t,e,n){let r=n.docs.get(e._key),i=new $l(t);return new ya(t,i,e._key,r,new ma(n.hasPendingWrites,n.fromCache),e.converter)}function $6(t){return W6(t,{count:Ice()})}function W6(t,e){let n=lr(t.firestore,Ni),r=Mh(n),i=zse(e,(o,s)=>new LO(s,o.aggregateType,o._internalFieldPath));return pce(r,t._query,i).then(o=>(function(a,c,l){let d=new $l(a);return new q0(c,d,l)})(n,t,o))}var rM=class{constructor(e){let n;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),n=e.tabManager):(n=Sce(void 0),n._initialize(e)),this._onlineComponentProvider=n._onlineComponentProvider,this._offlineComponentProvider=n._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function $M(t){return new rM(t)}var iM=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=BM.provider,this._offlineComponentProvider={build:n=>new yv(n,e?.cacheSizeBytes,this.forceOwnership)}}},oM=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=BM.provider,this._offlineComponentProvider={build:n=>new j0(n,e?.cacheSizeBytes)}}};function Sce(t){return new iM(t?.forceOwnership)}function WM(){return new oM}var Ace={maxAttempts:5};function Dg(t,e){if((t=Pe(t)).firestore!==e)throw new $(x.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return t}var sM=class{constructor(e,n){this._firestore=e,this._transaction=n,this._dataReader=Gv(e)}get(e){let n=Dg(e,this._firestore),r=new nM(this._firestore);return this._transaction.lookup([n._key]).then(i=>{if(!i||i.length!==1)return re(24041);let o=i[0];if(o.isFoundDocument())return new Hl(this._firestore,r,o.key,o,n.converter);if(o.isNoDocument())return new Hl(this._firestore,r,n._key,null,n.converter);throw re(18433,{doc:o})})}set(e,n,r){let i=Dg(e,this._firestore),o=k6(i.converter,n,r),s=I6(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,r);return this._transaction.set(i._key,s),this}update(e,n,r,...i){let o=Dg(e,this._firestore),s;return s=typeof(n=Pe(n))=="string"||n instanceof Ah?_ce(this._dataReader,"Transaction.update",o._key,n,r,i):Ece(this._dataReader,"Transaction.update",o._key,n),this._transaction.update(o._key,s),this}delete(e){let n=Dg(e,this._firestore);return this._transaction.delete(n._key),this}};var aM=class extends sM{constructor(e,n){super(e,n),this._firestore=e}get(e){let n=Dg(e,this._firestore),r=new $l(this._firestore);return super.get(e).then(i=>new ya(this._firestore,r,n._key,i._document,new ma(!1,!1),n.converter))}};function z6(t,e,n){t=lr(t,Ni);let r=Object.assign(Object.assign({},Ace),n);return(function(o){if(o.maxAttempts<1)throw new $(x.INVALID_ARGUMENT,"Max attempts must be at least 1")})(r),(function(o,s,a){let c=new cr;return o.asyncQueue.enqueueAndForget(()=>y(null,null,function*(){let l=yield f6(o);new $0(o.asyncQueue,l,a,s,c).zu()})),c.promise})(Mh(t),i=>e(new aM(t,i)),r)}(function(e,n=!0){(function(i){Rh=i})(qs),zn(new Xt("firestore",(r,{instanceIdentifier:i,options:o})=>{let s=r.getProvider("app").getImmediate(),a=new Ni(new rO(r.getProvider("auth-internal")),new sO(s,r.getProvider("app-check-internal")),(function(l,d){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new $(x.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new dh(l.options.projectId,d)})(s,i),s);return o=Object.assign({useFetchStreams:n},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),$e(p$,g$,e),$e(p$,g$,"esm2017")})();var nVe=de(b6,!0,2);var Hv=de(E6,!0,2),q6=de(_6,!0,2);var K6=de(B6,!0,2);var Em=de(T6,!0,2);var Y6=de($6,!0),zM=de(F6,!0);var X6=de(U6,!0);var rVe=de(M6,!0,2);var Q6=de(G6,!0);var iVe=de(w6,!0,2),oVe=de(O6,!0,2),J6=de(R6,!0,2);var Z6=de(z6,!0),e4=de(V6,!0,2);var sVe=de(L6,!0,2);var aVe=de(N6,!0,2);var $v=class{static getFirestoreProdDbName(e,n){return n?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||n?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(n){return b.error("Error in isTestingDb:",n),!1}}};var t4=(()=>{let e=class e{constructor(r,i,o){this.configService=r,this.authService=i,this.loggingService=o,this.firestore$=new le(null);try{oc([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(En(([s,a])=>!!s&&!!a),_n(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let h=sessionStorage?.getItem("veltFirestoreLogLevel")||zt?.firebaseLogLevel||"silent";cM(h)}catch(h){this.loggingService.catch("Error in FirestoreService setLogLevel: ",h)}let l=$v.getFirestoreProdDbName(a,s.firebaseOptions),d=this.configService.getProxyConfig();if(d?.v2DbHost){let h={host:d.v2DbHost,ssl:!0};d.forceLongPolling?h.experimentalForceLongPolling=!0:h.experimentalAutoDetectLongPolling=!0,c&&(h.localCache=$M({tabManager:WM()}));try{this.firestore$.next(Bv(ir(),h,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next(Oh(l))}}else if(c)try{let h=ir(),f=Bv(h,{localCache:$M({tabManager:WM()})},l);this.firestore$.next(f)}catch{this.firestore$.next(Oh(l))}else this.firestore$.next(Oh(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let r=this.getFirestoreValue()||Oh("DocumentIdDb");if(r){let i=Hv(r,"generateDocumentId");return Em(i).id}return}catch(r){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",r);return}}};e.\u0275fac=function(i){return new(i||e)(z(fo),z(vd),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Wv=(()=>{let e=class e{constructor(r,i,o){this.authService=r,this.configService=i,this.loggingService=o,this.db$=new le(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=BV(c,a.v1DbHost),a?.forceLongPolling&&kb());let l=Vd(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(r){try{let o=r?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(z(vd),z(fo),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Or={doc:Em,collection:Hv,collectionGroup:q6,query:J6,getDoc:zM,getDocs:X6,getCountFromServer:Y6,setDoc:e4,deleteDoc:K6,onSnapshot:Q6,runTransaction:Z6},r4=(()=>{let e=class e{constructor(r,i,o){this.firestoreService=r,this.databaseService=i,this.loggingService=o}read(r){return y(this,null,function*(){if((r.store??"firestore")==="rtdb"){let a=this.databaseService.getDbValue();return a?{data:(yield _g(Bd(a,r.location)))?.val()}:{data:void 0}}let o=this.firestoreService.getFirestoreValue();return o?{data:(yield zM(Em(o,r.location)))?.data()}:{data:void 0}})}runTransaction(r){return y(this,null,function*(){return r()})}firestoreDoc(r,i){return Or.doc(r,i)}firestoreCollection(r,i){return Or.collection(r,i)}firestoreCollectionGroup(r,i){return Or.collectionGroup(r,i)}firestoreQuery(r,...i){return Or.query(r,...i)}firestoreGetDoc(r){return Or.getDoc(r)}firestoreGetDocs(r){return Or.getDocs(r)}firestoreGetCountFromServer(r){return Or.getCountFromServer(r)}firestoreSetDoc(r,i,o){return o?Or.setDoc(r,i,o):Or.setDoc(r,i)}firestoreDeleteDoc(r){return Or.deleteDoc(r)}firestoreOnSnapshot(r,i,o){return o?Or.onSnapshot(r,i,o):Or.onSnapshot(r,i)}firestoreRunTransaction(r,i){return Or.runTransaction(r,i)}addComment(r){return this.deferred("addComment")}editComment(r){return this.deferred("editComment")}addReaction(r){return this.deferred("addReaction")}editReaction(r){return this.deferred("editReaction")}deleteReaction(r){return this.deferred("deleteReaction")}addArea(r){return this.deferred("addArea")}deleteArea(r){return this.deferred("deleteArea")}recordDocumentView(r){return this.deferred("recordDocumentView")}getActivitiesForDocuments(r){return this.deferred("getActivitiesForDocuments")}getActivitiesForEntity(r){return this.deferred("getActivitiesForEntity")}deleteComment(r){return this.deferred("deleteComment")}setCommentResolved(r){return this.deferred("setCommentResolved")}setCommentMetadata(r){return this.deferred("setCommentMetadata")}bumpCommentViews(r){return this.deferred("bumpCommentViews")}markCommentThreadRead(r){return this.deferred("markCommentThreadRead")}markNotificationRead(r){return this.deferred("markNotificationRead")}addNotification(r){return this.deferred("addNotification")}deleteNotification(r){return this.deferred("deleteNotification")}updateNotification(r){return this.deferred("updateNotification")}updatePresence(r){return this.deferred("updatePresence")}grantAccess(r){return this.deferred("grantAccess")}revokeAccess(r){return this.deferred("revokeAccess")}getAccess(r){return this.deferred("getAccess")}upsertOrgUserProfile(r){return this.deferred("upsertOrgUserProfile")}upsertDocMetadata(r){return this.deferred("upsertDocMetadata")}upsertOrgMetadata(r){return this.deferred("upsertOrgMetadata")}createActivity(r){return this.deferred("createActivity")}saveCrdtVersion(r){return this.deferred("saveCrdtVersion")}getCrdtVersion(r){return this.deferred("getCrdtVersion")}listCrdtVersions(r){return this.deferred("listCrdtVersions")}getOrganizationUsers(r){return this.deferred("getOrganizationUsers")}searchOrganizationUsers(r){return this.deferred("searchOrganizationUsers")}setLocationMetadata(r){return this.deferred("setLocationMetadata")}fetchLocations(r){return this.deferred("fetchLocations")}createFolder(r){return this.deferred("createFolder")}setDocumentMetadata(r){return this.deferred("setDocumentMetadata")}getDocuments(r){return this.deferred("getDocuments")}fetchDocuments(r){return this.deferred("fetchDocuments")}fetchFolders(r){return this.deferred("fetchFolders")}fetchCommentAnnotations(r){return this.deferred("fetchCommentAnnotations")}getCommentAnnotationsCount(r){return this.deferred("getCommentAnnotationsCount")}markNotificationReadDoc(r){return this.deferred("markNotificationReadDoc")}getUserPermissions(r){return this.deferred("getUserPermissions")}setUserConfig(r){return this.deferred("setUserConfig")}addMultiThread(r){return this.deferred("addMultiThread")}editMultiThread(r){return this.deferred("editMultiThread")}deleteMultiThread(r){return this.deferred("deleteMultiThread")}getUploadUrl(r){return this.deferred("getUploadUrl")}getDownloadUrl(r){return this.deferred("getDownloadUrl")}deleteAttachment(r){return this.deferred("deleteAttachment")}getNotificationsForDocuments(r){return this.deferred("getNotificationsForDocuments")}getDocumentMetadataFromIds(r){return this.deferred("getDocumentMetadataFromIds")}getCrossOrgUserNotifications(r){return this.deferred("getCrossOrgUserNotifications")}deferred(r){return this.loggingService.warn(`[WB] FirebaseDbAdapter.${r} called but write-op wiring is deferred to Phase A (self-hosting Step 0). The SDK uses its existing direct write path in Step 0.`),Promise.resolve({ok:!1,code:"unimplemented",message:`FirebaseDbAdapter.${r} wiring deferred to Phase A`})}};e.\u0275fac=function(i){return new(i||e)(z(t4),z(Wv),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();var Dce={comment:{mode:"persistent",scope:"doc"},notification:{mode:"persistent",scope:"user"},notificationIndex:{mode:"persistent",scope:"user"},crdt:{mode:"persistent",scope:"doc"},presence:{mode:"ephemeral",scope:"doc"},crdtSyncPresence:{mode:"ephemeral",scope:"doc"},crdtPresence:{mode:"ephemeral",scope:"doc"},liveState:{mode:"ephemeral",scope:"doc"},cursor:{mode:"ephemeral",scope:"doc"},huddle:{mode:"ephemeral",scope:"doc"},syncVideoPlayer:{mode:"ephemeral",scope:"doc"},heartbeat:{mode:"ephemeral",scope:"org"},flockSession:{mode:"ephemeral",scope:"doc"},selection:{mode:"ephemeral",scope:"doc"},reaction:{mode:"persistent",scope:"doc"},area:{mode:"persistent",scope:"doc"},lastActivityTimestamp:{mode:"persistent",scope:"org"},lastNotificationTimestamp:{mode:"persistent",scope:"org"},documentViews:{mode:"persistent",scope:"doc"},commentViews:{mode:"persistent",scope:"doc"},organizationCommentViews:{mode:"persistent",scope:"org"},folderCommentViews:{mode:"persistent",scope:"org"},userConfig:{mode:"persistent",scope:"user"},organizationUserConfig:{mode:"persistent",scope:"user"},organizationUsers:{mode:"persistent",scope:"org"},organizationGroups:{mode:"persistent",scope:"org"},customerMetadata:{mode:"persistent",scope:"org"},multiThread:{mode:"persistent",scope:"doc"}};function i4(t){return Dce[t]}var Ze={getDatabase:Vd,ref:Bd,query:a$,get:_g,set:u$,update:d$,remove:c$,push:s$,runTransaction:l$,onValue:Gb,onChildAdded:n$,onChildChanged:r$,onChildRemoved:i$,off:t$,objectVal:ZH,listVal:JH,stateChanges:e$,onDisconnect:o$},o4=(()=>{let e=class e{constructor(r,i){this.databaseService=r,this.loggingService=i}getServerTimeOffset(){return y(this,null,function*(){try{let r=this.databaseService.getDbValue();if(!r)return 0;let o=(yield _g(Bd(r,e.SERVER_TIME_OFFSET_PATH)))?.val();return typeof o=="number"?o:0}catch(r){return this.loggingService.catch("Error in FirebaseRealtimeAdapter getServerTimeOffset: ",r),0}})}onServerTimeOffset(r){let i=null,o=null;try{o=this.databaseService.getDb().subscribe(s=>{if(s){let a=Bd(s,e.SERVER_TIME_OFFSET_PATH);i=Gb(a,c=>{try{r(c?.val())}catch(l){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset callback: ",l)}})}})}catch(s){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset: ",s)}return()=>{try{i&&(i(),i=null),o?.unsubscribe(),o=null}catch(s){this.loggingService.catch("Error tearing down FirebaseRealtimeAdapter onServerTimeOffset: ",s)}}}getChannelTag(r){return i4(r)}getDatabaseInstance(r){return r?Ze.getDatabase(void 0,r):Ze.getDatabase()}rtdbRef(r,i){return Ze.ref(r,i)}rtdbQueryRef(r,...i){return Ze.query(r,...i)}rtdbGet(r){return Ze.get(r)}rtdbSet(r,i,o){return this.getChannelTag(r),Ze.set(i,o)}rtdbUpdate(r,i,o){return this.getChannelTag(r),Ze.update(i,o)}rtdbRemove(r,i){return this.getChannelTag(r),Ze.remove(i)}rtdbPush(r,i,o){return this.getChannelTag(r),o===void 0?Ze.push(i):Ze.push(i,o)}rtdbRunTransaction(r,i,o){return this.getChannelTag(r),Ze.runTransaction(i,o)}rtdbOnValue(r,i,o,s,a){return this.getChannelTag(r),typeof s=="function"?a?Ze.onValue(i,o,s,a):Ze.onValue(i,o,s):s?Ze.onValue(i,o,s):Ze.onValue(i,o)}rtdbOnChildAdded(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildAdded(i,o,s):Ze.onChildAdded(i,o)}rtdbOnChildChanged(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildChanged(i,o,s):Ze.onChildChanged(i,o)}rtdbOnChildRemoved(r,i,o,s){return this.getChannelTag(r),s?Ze.onChildRemoved(i,o,s):Ze.onChildRemoved(i,o)}rtdbOff(r,i,o){Ze.off(r,i,o)}rtdbObjectVal$(r,i){return this.getChannelTag(r),Ze.objectVal(i)}rtdbListVal$(r,i){return this.getChannelTag(r),Ze.listVal(i)}rtdbStateChanges$(r,i){return this.getChannelTag(r),Ze.stateChanges(i)}rtdbOnDisconnectSet(r,i,o){return this.getChannelTag(r),Ze.onDisconnect(i).set(o)}rtdbOnDisconnectUpdate(r,i,o){return this.getChannelTag(r),Ze.onDisconnect(i).update(o)}rtdbOnDisconnectRemove(r,i){return this.getChannelTag(r),Ze.onDisconnect(i).remove()}rtdbOnDisconnectCancel(r,i){return this.getChannelTag(r),Ze.onDisconnect(i).cancel()}subscribe(r,i,o,s){return{unsubscribe:()=>{}}}publish(r,i,o){return y(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.publish wiring deferred to Phase A"}})}presence(r,i){return y(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.presence wiring deferred to Phase A"}})}onDisconnect(r,i){return y(this,null,function*(){return()=>{}})}};e.SERVER_TIME_OFFSET_PATH=".info/serverTimeOffset",e.\u0275fac=function(i){return new(i||e)(z(Wv),z(Rt))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function FVe(t,e,n){let r=t?.[e];return typeof r!="function"?Promise.resolve({ok:!1,code:"unimplemented",message:`the portable adapter does not implement '${e}'`}):r.call(t,n)}var La=null,qv=null,zv,s4;function Rce(t){if(!(t&&t===s4&&zv)){s4=t;try{zv?.()}catch(e){b.catch("Error releasing the portable capability tracker: ",e)}zv=void 0,qv=null;try{zv=t?.onCapabilitiesChanged?.(e=>{qv=e?.size?new Set(e):null})}catch(e){b.catch("Error binding the portable capability tracker: ",e)}}}function UVe(t,e,n,r={data:{},operation:null}){return t.portableCapability$(e).pipe(Zn(i=>i?t.dbListener(n):ot(r)))}var qM=new Set;function KM(t){return qM.add(t),()=>qM.delete(t)}function VVe(t){return new Promise(e=>{let n=!1,r=null,i=()=>{if(!n){n=!0,clearTimeout(o);try{r?.()}catch{}e()}},o=setTimeout(i,t);r=KM(i),La&&i()})}function BVe(t){return cf(()=>{let e=!1;try{if(t.isPortableFeedActive())return ot(null)}catch(r){e=!0,t.onError("portable check",r)}let n=new ue(r=>KM(()=>{try{(e||t.isPortableFeedActive())&&r.next(null)}catch(i){e=!0,r.next(null),t.onError("registration re-check",i)}}));return vs(t.firebaseDb$().pipe(En(r=>!!r)),n)})}function Nce(t){let e=t?.message;return typeof e=="string"&&/^NG0205(?!\d)/.test(e)}function GVe(t){if(La=t??null,Rce(La?.realtime),La)for(let e of Array.from(qM))try{e()}catch(n){b.catch("Error in portable adapter registration listener: ",n)}}function q2(){return La}var jVe=(()=>{let e=class e{constructor(r){this.injector=r}get configService(){return this._configService??=this.injector.get(fo)}get authService(){return this._authService??=this.injector.get(vd)}isPortableBackendActive(){return this.isPortableActive()}evaluatePortableGates(){try{return{chunkRegistered:!!La,flagOn:this.configService.getEnablePortableBackend()===!0,identifyRecorded:!!this.authService.getPortableBackend()}}catch(r){return Nce(r)||b.catch("Error in AdapterSelectorService evaluatePortableGates: ",r),null}}isPortableActive(){let r=this.evaluatePortableGates();return!!r&&r.chunkRegistered&&r.flagOn&&r.identifyRecorded}isPortableBackendPending(){let r=this.evaluatePortableGates();return!!r&&!r.chunkRegistered&&r.flagOn&&r.identifyRecorded}isPortableSession(){let r=this.evaluatePortableGates();return!!r&&r.flagOn&&r.identifyRecorded}portableConnectionAnnounces(r){try{return this.resolveRealtimeAdapter()?.hasCapability?.(r)===!0}catch(i){return b.catch("Error in AdapterSelectorService portableConnectionAnnounces: ",i),!1}}portableCapability$(r){return this.portableConnectionChanges$().pipe(De(()=>this.portableConnectionAnnounces(r)),ai())}portableCapabilityState(r){try{return!this.isPortableBackendActive()||!qv?"unknown":this.portableConnectionAnnounces(r)?"announced":qv.has(r)?"unknown":"absent"}catch(i){return b.catch("Error in AdapterSelectorService portableCapabilityState: ",i),"unknown"}}portableConnectionChanges$(){return new ue(r=>{let i,o=()=>{try{i?.(),i=void 0,this.isPortableBackendActive()&&(i=this.resolveRealtimeAdapter()?.onCapabilitiesChanged?.(()=>r.next()))}catch(a){b.catch("Error in AdapterSelectorService portableConnectionChanges$ bind: ",a)}r.next()};o();let s=KM(o);return()=>{s(),i?.()}})}resolveDbAdapter(){return this.isPortableActive()?La.db:this.injector.get(r4)}resolveRealtimeAdapter(){return this.isPortableActive()?La.realtime:this.injector.get(o4)}};e.\u0275fac=function(i){return new(i||e)(z(Ke))},e.\u0275prov=J({token:e,factory:e.\u0275fac,providedIn:"root"});let t=e;return t})();function $Ve(t){if(!t||typeof t!="object")return!1;let e=t;return e.ok?!1:e.code==="unimplemented"?!0:e.code==="invalid-argument"&&/^unsupported operation\b/i.test(String(e.message??""))}var KVe=new Set(f2);function YVe(t){try{let e=t?.reasonCode;return typeof e!="string"||!e.trim()?"":` [reason: ${e.trim()}]`}catch{return""}}var QVe="portable transport not connected",JVe="portable transport disconnected",ZVe="portable transport send failed",wce="portable publish op '",bce="' requires a channel on the OperationRequest";function eBe(t){return`${wce}${t}${bce}`}var tBe="portable request timed out",nBe="portable request failed in transport",rBe="portable session not established",iBe="portable apiEndpoint is not a secure URL; request not sent",oBe="portable request body could not be serialized; request not sent",sBe="portable request failed before it was sent";export{B as a,me as b,g4 as c,Oce as d,Mce as e,Lce as f,y as g,gt as h,ue as i,IS as j,Be as k,le as l,ac as m,oz as n,sz as o,nc as p,hr as q,ot as r,az as s,cz as t,z4 as u,De as v,oc as w,cf as x,lz as y,Hi as z,mz as A,bo as B,B4 as C,vs as D,En as E,w4 as F,ES as G,_S as H,U4 as I,sE as J,_n as K,yS as L,ai as M,rf as N,sc as O,aE as P,SS as Q,G4 as R,cE as S,j4 as T,nn as U,Zn as V,Is as W,H4 as X,lE as Y,$4 as Z,K4 as _,Z as $,ME as aa,J as ba,Lo as ca,q as da,z as ea,X as fa,er as ga,On as ha,$i as ia,bP as ja,OP as ka,jP as la,HP as ma,Ke as na,on as oa,Wn as pa,fr as qa,Xi as ra,Rc as sa,Br as ta,Kz as ua,Wt as va,LC as wa,f8 as xa,xs as ya,f_ as za,w_ as Aa,I8 as Ba,i5 as Ca,o5 as Da,s5 as Ea,l5 as Fa,u5 as Ga,R5 as Ha,Fo as Ia,Re as Ja,x5 as Ka,Aq as La,Cq as Ma,Zi as Na,kf as Oa,Bo as Pa,j_ as Qa,at as Ra,xq as Sa,no as Ta,Mc as Ua,_1 as Va,S9 as Wa,ks as Xa,ro as Ya,Uf as Za,A1 as _a,L9 as $a,R1 as ab,N1 as bb,W_ as cb,Fs as db,P1 as eb,x1 as fb,B9 as gb,j9 as hb,H9 as ib,$9 as jb,W9 as kb,z9 as lb,q9 as mb,k1 as nb,_D as ob,TD as pb,F1 as qb,yD as rb,ID as sb,U1 as tb,vD as ub,SD as vb,B1 as wb,Z9 as xb,G1 as yb,H1 as zb,$1 as Ab,iK as Bb,sK as Cb,aK as Db,lK as Eb,uK as Fb,dK as Gb,hK as Hb,fK as Ib,pK as Jb,gK as Kb,X1 as Lb,Q1 as Mb,NK as Nb,bK as Ob,BK as Pb,sF as Qb,AD as Rb,aF as Sb,cF as Tb,lF as Ub,$K as Vb,uF as Wb,hF as Xb,WK as Yb,zK as Zb,qK as _b,KK as $b,ZK as ac,eY as bc,tY as cc,nY as dc,rY as ec,iY as fc,oY as gc,sY as hc,aY as ic,cY as jc,lY as kc,uY as lc,hY as mc,pY as nc,gY as oc,mY as pc,EY as qc,_Y as rc,IY as sc,$f as tc,Wf as uc,wD as vc,uAe as wc,dAe as xc,hAe as yc,QY as zc,GD as Ac,fAe as Bc,pAe as Cc,gAe as Dc,io as Ec,HF as Fc,_7 as Gc,sU as Hc,T7 as Ic,KD as Jc,y7 as Kc,I7 as Lc,v7 as Mc,S7 as Nc,C7 as Oc,R7 as Pc,w7 as Qc,YD as Rc,uT as Sc,dT as Tc,W7 as Uc,K7 as Vc,wU as Wc,_X as Xc,TX as Yc,aR as Zc,jU as _c,dR as $c,pd as ad,vr as bd,Hs as cd,zT as dd,qc as ed,nr as fd,Pe as gd,Xt as hd,zn as id,uo as jd,rr as kd,qs as ld,ir as md,$e as nd,lZ as od,kLe as pd,FLe as qd,ULe as rd,Ei as sd,Ks as td,Qo as ud,_i as vd,de as wd,Ti as xd,Jo as yd,nPe as zd,rPe as Ad,iPe as Bd,Xs as Cd,Mee as Dd,Pee as Ed,qee as Fd,Zc as Gd,el as Hd,Bxe as Id,Gxe as Jd,qFe as Kd,KFe as Ld,YFe as Md,XFe as Nd,QFe as Od,JFe as Pd,Zo as Qd,oke as Rd,ske as Sd,ake as Td,WU as Ud,VX as Vd,cp as Wd,zt as Xd,b as Yd,kDe as Zd,FDe as _d,UDe as $d,VDe as ae,BDe as be,GDe as ce,jDe as de,oo as ee,HDe as fe,$De as ge,WDe as he,zDe as ie,vX as je,SX as ke,AX as le,CX as me,DX as ne,RX as oe,qDe as pe,NX as qe,cR as re,wX as se,Ir as te,TT as ue,bX as ve,id as we,xn as xe,OX as ye,yT as ze,MX as Ae,LX as Be,PX as Ce,KDe as De,YDe as Ee,XDe as Fe,xX as Ge,k as He,BU as Ie,MRe as Je,LRe as Ke,PRe as Le,xRe as Me,od as Ne,VRe as Oe,BRe as Pe,GRe as Qe,Wr as Re,Et as Se,zU as Te,qU as Ue,mNe as Ve,ENe as We,KU as Xe,hR as Ye,YU as Ze,fR as _e,bT as $e,BX as af,GX as bf,jX as cf,HX as df,$X as ef,WX as ff,zX as gf,qX as hf,KX as if,YX as jf,XX as kf,QX as lf,ZU as mf,eV as nf,tV as of,nV as pf,rV as qf,so as rf,jNe as sf,OT as tf,iV as uf,oV as vf,sV as wf,aV as xf,cV as yf,lV as zf,uV as Af,dV as Bf,hV as Cf,fV as Df,pV as Ef,gV as Ff,mV as Gf,Awe as Hf,Cwe as If,EV as Jf,pR as Kf,_V as Lf,TV as Mf,IV as Nf,vV as Of,ibe as Pf,obe as Qf,JX as Rf,ZX as Sf,l0e as Tf,MT as Uf,yR as Vf,$c as Wf,BV as Xf,y0e as Yf,jc as Zf,Yo as _f,I0e as $f,v0e as ag,S0e as bg,jV as cg,A0e as dg,C0e as eg,D0e as fg,R0e as gg,N0e as hg,w0e as ig,b0e as jg,HV as kg,$V as lg,O0e as mg,M0e as ng,tQ as og,L0e as pg,P0e as qg,x0e as rg,k0e as sg,F0e as tg,WV as ug,ad as vg,U0e as wg,zV as xg,KV as yg,NV as zg,wV as Ag,nQ as Bg,rQ as Cg,UT as Dg,hp as Eg,V0e as Fg,B0e as Gg,ao as Hg,G0e as Ig,cd as Jg,sQ as Kg,j0e as Lg,DR as Mg,OV as Ng,aQ as Og,xT as Pg,H0e as Qg,$0e as Rg,YV as Sg,XV as Tg,cQ as Ug,Gc as Vg,lQ as Wg,hQ as Xg,W0e as Yg,ZV as Zg,z0e as _g,q0e as $g,fQ as ah,pQ as bh,gQ as ch,mQ as dh,Wc as eh,K0e as fh,Y0e as gh,X0e as hh,vR as ih,Q0e as jh,_Q as kh,J0e as lh,Z0e as mh,tB as nh,eMe as oh,tMe as ph,nMe as qh,rMe as rh,iMe as sh,oMe as th,sMe as uh,LT as vh,aMe as wh,cMe as xh,lMe as yh,RR as zh,uMe as Ah,kV as Bh,dMe as Ch,hMe as Dh,fMe as Eh,pMe as Fh,gMe as Gh,mMe as Hh,EMe as Ih,_Me as Jh,TMe as Kh,yMe as Lh,IMe as Mh,vMe as Nh,SMe as Oh,AMe as Ph,CMe as Qh,DMe as Rh,RMe as Sh,NMe as Th,wMe as Uh,bMe as Vh,OMe as Wh,MMe as Xh,vQ as Yh,LMe as Zh,PMe as _h,xMe as $h,FV as ai,kMe as bi,FMe as ci,pp as di,SQ as ei,UMe as fi,VMe as gi,BMe as hi,GMe as ii,AQ as ji,jMe as ki,HMe as li,cB as mi,wR as ni,ud as oi,$Me as pi,dp as qi,WMe as ri,zMe as si,qMe as ti,AR as ui,KMe as vi,bQ as wi,YMe as xi,XMe as yi,HQ as zi,QMe as Ai,JMe as Bi,ZMe as Ci,UV as Di,eLe as Ei,$Q as Fi,iJ as Gi,oJ as Hi,vt as Ii,Td as Ji,tRe as Ki,nRe as Li,rRe as Mi,iRe as Ni,oRe as Oi,sRe as Pi,aRe as Qi,cRe as Ri,lRe as Si,uRe as Ti,dRe as Ui,hRe as Vi,IT as Wi,fRe as Xi,pRe as Yi,gRe as Zi,vT as _i,mRe as $i,ERe as aj,_Re as bj,TRe as cj,yRe as dj,IRe as ej,vRe as fj,ST as gj,SRe as hj,ARe as ij,AT as jj,PU as kj,xU as lj,kU as mj,FU as nj,CT as oj,Zs as pj,Rt as qj,fo as rj,nl as sj,pne as tj,vne as uj,Cke as vj,_y as wj,a2 as xj,zke as yj,qn as zj,qke as Aj,nVe as Bj,rVe as Cj,iVe as Dj,oVe as Ej,sVe as Fj,aVe as Gj,$v as Hj,t4 as Ij,Wv as Jj,r4 as Kj,i4 as Lj,o4 as Mj,FVe as Nj,UVe as Oj,KM as Pj,VVe as Qj,BVe as Rj,GVe as Sj,q2 as Tj,jVe as Uj,f2 as Vj,t1e as Wj,n1e as Xj,r1e as Yj,i1e as Zj,o1e as _j,s1e as $j,a1e as ak,c1e as bk,l1e as ck,u1e as dk,d1e as ek,h1e as fk,f1e as gk,$Ve as hk,YVe as ik,QVe as jk,JVe as kk,ZVe as lk,wce as mk,bce as nk,eBe as ok,tBe as pk,nBe as qk,rBe as rk,iBe as sk,oBe as tk,sBe as uk,T2 as vk,y2 as wk,Sy as xk,S1e as yk,A1e as zk,W2 as Ak,vd as Bk};
|